use SDValue bool operator; NFCI
[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 visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitBSWAP(SDNode *N);
259     SDValue visitCTLZ(SDNode *N);
260     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTTZ(SDNode *N);
262     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTPOP(SDNode *N);
264     SDValue visitSELECT(SDNode *N);
265     SDValue visitVSELECT(SDNode *N);
266     SDValue visitSELECT_CC(SDNode *N);
267     SDValue visitSETCC(SDNode *N);
268     SDValue visitSIGN_EXTEND(SDNode *N);
269     SDValue visitZERO_EXTEND(SDNode *N);
270     SDValue visitANY_EXTEND(SDNode *N);
271     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273     SDValue visitTRUNCATE(SDNode *N);
274     SDValue visitBITCAST(SDNode *N);
275     SDValue visitBUILD_PAIR(SDNode *N);
276     SDValue visitFADD(SDNode *N);
277     SDValue visitFSUB(SDNode *N);
278     SDValue visitFMUL(SDNode *N);
279     SDValue visitFMA(SDNode *N);
280     SDValue visitFDIV(SDNode *N);
281     SDValue visitFREM(SDNode *N);
282     SDValue visitFSQRT(SDNode *N);
283     SDValue visitFCOPYSIGN(SDNode *N);
284     SDValue visitSINT_TO_FP(SDNode *N);
285     SDValue visitUINT_TO_FP(SDNode *N);
286     SDValue visitFP_TO_SINT(SDNode *N);
287     SDValue visitFP_TO_UINT(SDNode *N);
288     SDValue visitFP_ROUND(SDNode *N);
289     SDValue visitFP_ROUND_INREG(SDNode *N);
290     SDValue visitFP_EXTEND(SDNode *N);
291     SDValue visitFNEG(SDNode *N);
292     SDValue visitFABS(SDNode *N);
293     SDValue visitFCEIL(SDNode *N);
294     SDValue visitFTRUNC(SDNode *N);
295     SDValue visitFFLOOR(SDNode *N);
296     SDValue visitFMINNUM(SDNode *N);
297     SDValue visitFMAXNUM(SDNode *N);
298     SDValue visitBRCOND(SDNode *N);
299     SDValue visitBR_CC(SDNode *N);
300     SDValue visitLOAD(SDNode *N);
301     SDValue visitSTORE(SDNode *N);
302     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304     SDValue visitBUILD_VECTOR(SDNode *N);
305     SDValue visitCONCAT_VECTORS(SDNode *N);
306     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307     SDValue visitVECTOR_SHUFFLE(SDNode *N);
308     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309     SDValue visitINSERT_SUBVECTOR(SDNode *N);
310     SDValue visitMLOAD(SDNode *N);
311     SDValue visitMSTORE(SDNode *N);
312     SDValue visitMGATHER(SDNode *N);
313     SDValue visitMSCATTER(SDNode *N);
314     SDValue visitFP_TO_FP16(SDNode *N);
315
316     SDValue visitFADDForFMACombine(SDNode *N);
317     SDValue visitFSUBForFMACombine(SDNode *N);
318
319     SDValue XformToShuffleWithZero(SDNode *N);
320     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
321
322     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
323
324     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328                              SDValue N3, ISD::CondCode CC,
329                              bool NotExtCompare = false);
330     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331                           SDLoc DL, bool foldBooleans = true);
332
333     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
334                            SDValue &CC) const;
335     bool isOneUseSetCC(SDValue N) const;
336
337     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
338                                          unsigned HiOp);
339     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340     SDValue CombineExtLoad(SDNode *N);
341     SDValue combineRepeatedFPDivisors(SDNode *N);
342     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
343     SDValue BuildSDIV(SDNode *N);
344     SDValue BuildSDIVPow2(SDNode *N);
345     SDValue BuildUDIV(SDNode *N);
346     SDValue BuildReciprocalEstimate(SDValue Op);
347     SDValue BuildRsqrtEstimate(SDValue Op);
348     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
349     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
350     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
351                                bool DemandHighBits = true);
352     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
353     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
354                               SDValue InnerPos, SDValue InnerNeg,
355                               unsigned PosOpcode, unsigned NegOpcode,
356                               SDLoc DL);
357     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
358     SDValue ReduceLoadWidth(SDNode *N);
359     SDValue ReduceLoadOpStoreWidth(SDNode *N);
360     SDValue TransformFPLoadStorePair(SDNode *N);
361     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
362     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
363
364     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
365
366     /// Walk up chain skipping non-aliasing memory nodes,
367     /// looking for aliasing nodes and adding them to the Aliases vector.
368     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
369                           SmallVectorImpl<SDValue> &Aliases);
370
371     /// Return true if there is any possibility that the two addresses overlap.
372     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
373
374     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
375     /// chain (aliasing node.)
376     SDValue FindBetterChain(SDNode *N, SDValue Chain);
377
378     /// Holds a pointer to an LSBaseSDNode as well as information on where it
379     /// is located in a sequence of memory operations connected by a chain.
380     struct MemOpLink {
381       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
382       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
383       // Ptr to the mem node.
384       LSBaseSDNode *MemNode;
385       // Offset from the base ptr.
386       int64_t OffsetFromBase;
387       // What is the sequence number of this mem node.
388       // Lowest mem operand in the DAG starts at zero.
389       unsigned SequenceNum;
390     };
391
392     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
393     /// constant build_vector of the stored constant values in Stores.
394     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
395                                          SDLoc SL,
396                                          ArrayRef<MemOpLink> Stores,
397                                          EVT Ty) const;
398
399     /// This is a helper function for MergeConsecutiveStores. When the source
400     /// elements of the consecutive stores are all constants or all extracted
401     /// vector elements, try to merge them into one larger store.
402     /// \return True if a merged store was created.
403     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
404                                          EVT MemVT, unsigned NumElem,
405                                          bool IsConstantSrc, bool UseVector);
406
407     /// This is a helper function for MergeConsecutiveStores.
408     /// Stores that may be merged are placed in StoreNodes.
409     /// Loads that may alias with those stores are placed in AliasLoadNodes.
410     void getStoreMergeAndAliasCandidates(
411         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
412         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
413
414     /// Merge consecutive store operations into a wide store.
415     /// This optimization uses wide integers or vectors when possible.
416     /// \return True if some memory operations were changed.
417     bool MergeConsecutiveStores(StoreSDNode *N);
418
419     /// \brief Try to transform a truncation where C is a constant:
420     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
421     ///
422     /// \p N needs to be a truncation and its first operand an AND. Other
423     /// requirements are checked by the function (e.g. that trunc is
424     /// single-use) and if missed an empty SDValue is returned.
425     SDValue distributeTruncateThroughAnd(SDNode *N);
426
427   public:
428     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
429         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
430           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
431       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
432     }
433
434     /// Runs the dag combiner on all nodes in the work list
435     void Run(CombineLevel AtLevel);
436
437     SelectionDAG &getDAG() const { return DAG; }
438
439     /// Returns a type large enough to hold any valid shift amount - before type
440     /// legalization these can be huge.
441     EVT getShiftAmountTy(EVT LHSTy) {
442       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
443       if (LHSTy.isVector())
444         return LHSTy;
445       auto &DL = DAG.getDataLayout();
446       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
447                         : TLI.getPointerTy(DL);
448     }
449
450     /// This method returns true if we are running before type legalization or
451     /// if the specified VT is legal.
452     bool isTypeLegal(const EVT &VT) {
453       if (!LegalTypes) return true;
454       return TLI.isTypeLegal(VT);
455     }
456
457     /// Convenience wrapper around TargetLowering::getSetCCResultType
458     EVT getSetCCResultType(EVT VT) const {
459       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
460     }
461   };
462 }
463
464
465 namespace {
466 /// This class is a DAGUpdateListener that removes any deleted
467 /// nodes from the worklist.
468 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
469   DAGCombiner &DC;
470 public:
471   explicit WorklistRemover(DAGCombiner &dc)
472     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
473
474   void NodeDeleted(SDNode *N, SDNode *E) override {
475     DC.removeFromWorklist(N);
476   }
477 };
478 }
479
480 //===----------------------------------------------------------------------===//
481 //  TargetLowering::DAGCombinerInfo implementation
482 //===----------------------------------------------------------------------===//
483
484 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
485   ((DAGCombiner*)DC)->AddToWorklist(N);
486 }
487
488 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
489   ((DAGCombiner*)DC)->removeFromWorklist(N);
490 }
491
492 SDValue TargetLowering::DAGCombinerInfo::
493 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
494   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
495 }
496
497 SDValue TargetLowering::DAGCombinerInfo::
498 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
499   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
500 }
501
502
503 SDValue TargetLowering::DAGCombinerInfo::
504 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
505   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
506 }
507
508 void TargetLowering::DAGCombinerInfo::
509 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
510   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
511 }
512
513 //===----------------------------------------------------------------------===//
514 // Helper Functions
515 //===----------------------------------------------------------------------===//
516
517 void DAGCombiner::deleteAndRecombine(SDNode *N) {
518   removeFromWorklist(N);
519
520   // If the operands of this node are only used by the node, they will now be
521   // dead. Make sure to re-visit them and recursively delete dead nodes.
522   for (const SDValue &Op : N->ops())
523     // For an operand generating multiple values, one of the values may
524     // become dead allowing further simplification (e.g. split index
525     // arithmetic from an indexed load).
526     if (Op->hasOneUse() || Op->getNumValues() > 1)
527       AddToWorklist(Op.getNode());
528
529   DAG.DeleteNode(N);
530 }
531
532 /// Return 1 if we can compute the negated form of the specified expression for
533 /// the same cost as the expression itself, or 2 if we can compute the negated
534 /// form more cheaply than the expression itself.
535 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
536                                const TargetLowering &TLI,
537                                const TargetOptions *Options,
538                                unsigned Depth = 0) {
539   // fneg is removable even if it has multiple uses.
540   if (Op.getOpcode() == ISD::FNEG) return 2;
541
542   // Don't allow anything with multiple uses.
543   if (!Op.hasOneUse()) return 0;
544
545   // Don't recurse exponentially.
546   if (Depth > 6) return 0;
547
548   switch (Op.getOpcode()) {
549   default: return false;
550   case ISD::ConstantFP:
551     // Don't invert constant FP values after legalize.  The negated constant
552     // isn't necessarily legal.
553     return LegalOperations ? 0 : 1;
554   case ISD::FADD:
555     // FIXME: determine better conditions for this xform.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // After operation legalization, it might not be legal to create new FSUBs.
559     if (LegalOperations &&
560         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
561       return 0;
562
563     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
564     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565                                     Options, Depth + 1))
566       return V;
567     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
568     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
569                               Depth + 1);
570   case ISD::FSUB:
571     // We can't turn -(A-B) into B-A when we honor signed zeros.
572     if (!Options->UnsafeFPMath) return 0;
573
574     // fold (fneg (fsub A, B)) -> (fsub B, A)
575     return 1;
576
577   case ISD::FMUL:
578   case ISD::FDIV:
579     if (Options->HonorSignDependentRoundingFPMath()) return 0;
580
581     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
582     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
583                                     Options, Depth + 1))
584       return V;
585
586     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
587                               Depth + 1);
588
589   case ISD::FP_EXTEND:
590   case ISD::FP_ROUND:
591   case ISD::FSIN:
592     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
593                               Depth + 1);
594   }
595 }
596
597 /// If isNegatibleForFree returns true, return the newly negated expression.
598 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
599                                     bool LegalOperations, unsigned Depth = 0) {
600   const TargetOptions &Options = DAG.getTarget().Options;
601   // fneg is removable even if it has multiple uses.
602   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
603
604   // Don't allow anything with multiple uses.
605   assert(Op.hasOneUse() && "Unknown reuse!");
606
607   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
608   switch (Op.getOpcode()) {
609   default: llvm_unreachable("Unknown code");
610   case ISD::ConstantFP: {
611     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
612     V.changeSign();
613     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
614   }
615   case ISD::FADD:
616     // FIXME: determine better conditions for this xform.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
620     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
621                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
622       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
623                          GetNegatedExpression(Op.getOperand(0), DAG,
624                                               LegalOperations, Depth+1),
625                          Op.getOperand(1));
626     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
627     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
628                        GetNegatedExpression(Op.getOperand(1), DAG,
629                                             LegalOperations, Depth+1),
630                        Op.getOperand(0));
631   case ISD::FSUB:
632     // We can't turn -(A-B) into B-A when we honor signed zeros.
633     assert(Options.UnsafeFPMath);
634
635     // fold (fneg (fsub 0, B)) -> B
636     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
637       if (N0CFP->isZero())
638         return Op.getOperand(1);
639
640     // fold (fneg (fsub A, B)) -> (fsub B, A)
641     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(1), Op.getOperand(0));
643
644   case ISD::FMUL:
645   case ISD::FDIV:
646     assert(!Options.HonorSignDependentRoundingFPMath());
647
648     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
649     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
650                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
651       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
652                          GetNegatedExpression(Op.getOperand(0), DAG,
653                                               LegalOperations, Depth+1),
654                          Op.getOperand(1));
655
656     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
657     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
658                        Op.getOperand(0),
659                        GetNegatedExpression(Op.getOperand(1), DAG,
660                                             LegalOperations, Depth+1));
661
662   case ISD::FP_EXTEND:
663   case ISD::FSIN:
664     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
665                        GetNegatedExpression(Op.getOperand(0), DAG,
666                                             LegalOperations, Depth+1));
667   case ISD::FP_ROUND:
668       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
669                          GetNegatedExpression(Op.getOperand(0), DAG,
670                                               LegalOperations, Depth+1),
671                          Op.getOperand(1));
672   }
673 }
674
675 // Return true if this node is a setcc, or is a select_cc
676 // that selects between the target values used for true and false, making it
677 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
678 // the appropriate nodes based on the type of node we are checking. This
679 // simplifies life a bit for the callers.
680 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
681                                     SDValue &CC) const {
682   if (N.getOpcode() == ISD::SETCC) {
683     LHS = N.getOperand(0);
684     RHS = N.getOperand(1);
685     CC  = N.getOperand(2);
686     return true;
687   }
688
689   if (N.getOpcode() != ISD::SELECT_CC ||
690       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
691       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
692     return false;
693
694   if (TLI.getBooleanContents(N.getValueType()) ==
695       TargetLowering::UndefinedBooleanContent)
696     return false;
697
698   LHS = N.getOperand(0);
699   RHS = N.getOperand(1);
700   CC  = N.getOperand(4);
701   return true;
702 }
703
704 /// Return true if this is a SetCC-equivalent operation with only one use.
705 /// If this is true, it allows the users to invert the operation for free when
706 /// it is profitable to do so.
707 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
708   SDValue N0, N1, N2;
709   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
710     return true;
711   return false;
712 }
713
714 /// Returns true if N is a BUILD_VECTOR node whose
715 /// elements are all the same constant or undefined.
716 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
717   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
718   if (!C)
719     return false;
720
721   APInt SplatUndef;
722   unsigned SplatBitSize;
723   bool HasAnyUndefs;
724   EVT EltVT = N->getValueType(0).getVectorElementType();
725   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
726                              HasAnyUndefs) &&
727           EltVT.getSizeInBits() >= SplatBitSize);
728 }
729
730 // \brief Returns the SDNode if it is a constant integer BuildVector
731 // or constant integer.
732 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
733   if (isa<ConstantSDNode>(N))
734     return N.getNode();
735   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
736     return N.getNode();
737   return nullptr;
738 }
739
740 // \brief Returns the SDNode if it is a constant float BuildVector
741 // or constant float.
742 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
743   if (isa<ConstantFPSDNode>(N))
744     return N.getNode();
745   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
746     return N.getNode();
747   return nullptr;
748 }
749
750 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
751 // int.
752 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
753   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
754     return CN;
755
756   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
757     BitVector UndefElements;
758     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
759
760     // BuildVectors can truncate their operands. Ignore that case here.
761     // FIXME: We blindly ignore splats which include undef which is overly
762     // pessimistic.
763     if (CN && UndefElements.none() &&
764         CN->getValueType(0) == N.getValueType().getScalarType())
765       return CN;
766   }
767
768   return nullptr;
769 }
770
771 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
772 // float.
773 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
774   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
775     return CN;
776
777   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
778     BitVector UndefElements;
779     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
780
781     if (CN && UndefElements.none())
782       return CN;
783   }
784
785   return nullptr;
786 }
787
788 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
789                                     SDValue N0, SDValue N1) {
790   EVT VT = N0.getValueType();
791   if (N0.getOpcode() == Opc) {
792     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
793       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
794         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
795         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
796           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
797         return SDValue();
798       }
799       if (N0.hasOneUse()) {
800         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
801         // use
802         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
803         if (!OpNode.getNode())
804           return SDValue();
805         AddToWorklist(OpNode.getNode());
806         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
807       }
808     }
809   }
810
811   if (N1.getOpcode() == Opc) {
812     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
813       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
814         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
815         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
816           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
817         return SDValue();
818       }
819       if (N1.hasOneUse()) {
820         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
821         // use
822         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
823         if (!OpNode.getNode())
824           return SDValue();
825         AddToWorklist(OpNode.getNode());
826         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
827       }
828     }
829   }
830
831   return SDValue();
832 }
833
834 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
835                                bool AddTo) {
836   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
837   ++NodesCombined;
838   DEBUG(dbgs() << "\nReplacing.1 ";
839         N->dump(&DAG);
840         dbgs() << "\nWith: ";
841         To[0].getNode()->dump(&DAG);
842         dbgs() << " and " << NumTo-1 << " other values\n");
843   for (unsigned i = 0, e = NumTo; i != e; ++i)
844     assert((!To[i].getNode() ||
845             N->getValueType(i) == To[i].getValueType()) &&
846            "Cannot combine value to value of different type!");
847
848   WorklistRemover DeadNodes(*this);
849   DAG.ReplaceAllUsesWith(N, To);
850   if (AddTo) {
851     // Push the new nodes and any users onto the worklist
852     for (unsigned i = 0, e = NumTo; i != e; ++i) {
853       if (To[i].getNode()) {
854         AddToWorklist(To[i].getNode());
855         AddUsersToWorklist(To[i].getNode());
856       }
857     }
858   }
859
860   // Finally, if the node is now dead, remove it from the graph.  The node
861   // may not be dead if the replacement process recursively simplified to
862   // something else needing this node.
863   if (N->use_empty())
864     deleteAndRecombine(N);
865   return SDValue(N, 0);
866 }
867
868 void DAGCombiner::
869 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
870   // Replace all uses.  If any nodes become isomorphic to other nodes and
871   // are deleted, make sure to remove them from our worklist.
872   WorklistRemover DeadNodes(*this);
873   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
874
875   // Push the new node and any (possibly new) users onto the worklist.
876   AddToWorklist(TLO.New.getNode());
877   AddUsersToWorklist(TLO.New.getNode());
878
879   // Finally, if the node is now dead, remove it from the graph.  The node
880   // may not be dead if the replacement process recursively simplified to
881   // something else needing this node.
882   if (TLO.Old.getNode()->use_empty())
883     deleteAndRecombine(TLO.Old.getNode());
884 }
885
886 /// Check the specified integer node value to see if it can be simplified or if
887 /// things it uses can be simplified by bit propagation. If so, return true.
888 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
889   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
890   APInt KnownZero, KnownOne;
891   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
892     return false;
893
894   // Revisit the node.
895   AddToWorklist(Op.getNode());
896
897   // Replace the old value with the new one.
898   ++NodesCombined;
899   DEBUG(dbgs() << "\nReplacing.2 ";
900         TLO.Old.getNode()->dump(&DAG);
901         dbgs() << "\nWith: ";
902         TLO.New.getNode()->dump(&DAG);
903         dbgs() << '\n');
904
905   CommitTargetLoweringOpt(TLO);
906   return true;
907 }
908
909 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
910   SDLoc dl(Load);
911   EVT VT = Load->getValueType(0);
912   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
913
914   DEBUG(dbgs() << "\nReplacing.9 ";
915         Load->dump(&DAG);
916         dbgs() << "\nWith: ";
917         Trunc.getNode()->dump(&DAG);
918         dbgs() << '\n');
919   WorklistRemover DeadNodes(*this);
920   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
921   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
922   deleteAndRecombine(Load);
923   AddToWorklist(Trunc.getNode());
924 }
925
926 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
927   Replace = false;
928   SDLoc dl(Op);
929   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
930     EVT MemVT = LD->getMemoryVT();
931     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
932       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
933                                                        : ISD::EXTLOAD)
934       : LD->getExtensionType();
935     Replace = true;
936     return DAG.getExtLoad(ExtType, dl, PVT,
937                           LD->getChain(), LD->getBasePtr(),
938                           MemVT, LD->getMemOperand());
939   }
940
941   unsigned Opc = Op.getOpcode();
942   switch (Opc) {
943   default: break;
944   case ISD::AssertSext:
945     return DAG.getNode(ISD::AssertSext, dl, PVT,
946                        SExtPromoteOperand(Op.getOperand(0), PVT),
947                        Op.getOperand(1));
948   case ISD::AssertZext:
949     return DAG.getNode(ISD::AssertZext, dl, PVT,
950                        ZExtPromoteOperand(Op.getOperand(0), PVT),
951                        Op.getOperand(1));
952   case ISD::Constant: {
953     unsigned ExtOpc =
954       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
955     return DAG.getNode(ExtOpc, dl, PVT, Op);
956   }
957   }
958
959   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
960     return SDValue();
961   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
962 }
963
964 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
965   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
966     return SDValue();
967   EVT OldVT = Op.getValueType();
968   SDLoc dl(Op);
969   bool Replace = false;
970   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
971   if (!NewOp.getNode())
972     return SDValue();
973   AddToWorklist(NewOp.getNode());
974
975   if (Replace)
976     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
977   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
978                      DAG.getValueType(OldVT));
979 }
980
981 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
982   EVT OldVT = Op.getValueType();
983   SDLoc dl(Op);
984   bool Replace = false;
985   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
986   if (!NewOp.getNode())
987     return SDValue();
988   AddToWorklist(NewOp.getNode());
989
990   if (Replace)
991     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
992   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
993 }
994
995 /// Promote the specified integer binary operation if the target indicates it is
996 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
997 /// i32 since i16 instructions are longer.
998 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
999   if (!LegalOperations)
1000     return SDValue();
1001
1002   EVT VT = Op.getValueType();
1003   if (VT.isVector() || !VT.isInteger())
1004     return SDValue();
1005
1006   // If operation type is 'undesirable', e.g. i16 on x86, consider
1007   // promoting it.
1008   unsigned Opc = Op.getOpcode();
1009   if (TLI.isTypeDesirableForOp(Opc, VT))
1010     return SDValue();
1011
1012   EVT PVT = VT;
1013   // Consult target whether it is a good idea to promote this operation and
1014   // what's the right type to promote it to.
1015   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016     assert(PVT != VT && "Don't know what type to promote to!");
1017
1018     bool Replace0 = false;
1019     SDValue N0 = Op.getOperand(0);
1020     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1021     if (!NN0.getNode())
1022       return SDValue();
1023
1024     bool Replace1 = false;
1025     SDValue N1 = Op.getOperand(1);
1026     SDValue NN1;
1027     if (N0 == N1)
1028       NN1 = NN0;
1029     else {
1030       NN1 = PromoteOperand(N1, PVT, Replace1);
1031       if (!NN1.getNode())
1032         return SDValue();
1033     }
1034
1035     AddToWorklist(NN0.getNode());
1036     if (NN1.getNode())
1037       AddToWorklist(NN1.getNode());
1038
1039     if (Replace0)
1040       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1041     if (Replace1)
1042       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1043
1044     DEBUG(dbgs() << "\nPromoting ";
1045           Op.getNode()->dump(&DAG));
1046     SDLoc dl(Op);
1047     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1048                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1049   }
1050   return SDValue();
1051 }
1052
1053 /// Promote the specified integer shift operation if the target indicates it is
1054 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1055 /// i32 since i16 instructions are longer.
1056 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1057   if (!LegalOperations)
1058     return SDValue();
1059
1060   EVT VT = Op.getValueType();
1061   if (VT.isVector() || !VT.isInteger())
1062     return SDValue();
1063
1064   // If operation type is 'undesirable', e.g. i16 on x86, consider
1065   // promoting it.
1066   unsigned Opc = Op.getOpcode();
1067   if (TLI.isTypeDesirableForOp(Opc, VT))
1068     return SDValue();
1069
1070   EVT PVT = VT;
1071   // Consult target whether it is a good idea to promote this operation and
1072   // what's the right type to promote it to.
1073   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1074     assert(PVT != VT && "Don't know what type to promote to!");
1075
1076     bool Replace = false;
1077     SDValue N0 = Op.getOperand(0);
1078     if (Opc == ISD::SRA)
1079       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1080     else if (Opc == ISD::SRL)
1081       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1082     else
1083       N0 = PromoteOperand(N0, PVT, Replace);
1084     if (!N0.getNode())
1085       return SDValue();
1086
1087     AddToWorklist(N0.getNode());
1088     if (Replace)
1089       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1090
1091     DEBUG(dbgs() << "\nPromoting ";
1092           Op.getNode()->dump(&DAG));
1093     SDLoc dl(Op);
1094     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1095                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1096   }
1097   return SDValue();
1098 }
1099
1100 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1101   if (!LegalOperations)
1102     return SDValue();
1103
1104   EVT VT = Op.getValueType();
1105   if (VT.isVector() || !VT.isInteger())
1106     return SDValue();
1107
1108   // If operation type is 'undesirable', e.g. i16 on x86, consider
1109   // promoting it.
1110   unsigned Opc = Op.getOpcode();
1111   if (TLI.isTypeDesirableForOp(Opc, VT))
1112     return SDValue();
1113
1114   EVT PVT = VT;
1115   // Consult target whether it is a good idea to promote this operation and
1116   // what's the right type to promote it to.
1117   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1118     assert(PVT != VT && "Don't know what type to promote to!");
1119     // fold (aext (aext x)) -> (aext x)
1120     // fold (aext (zext x)) -> (zext x)
1121     // fold (aext (sext x)) -> (sext x)
1122     DEBUG(dbgs() << "\nPromoting ";
1123           Op.getNode()->dump(&DAG));
1124     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1125   }
1126   return SDValue();
1127 }
1128
1129 bool DAGCombiner::PromoteLoad(SDValue Op) {
1130   if (!LegalOperations)
1131     return false;
1132
1133   EVT VT = Op.getValueType();
1134   if (VT.isVector() || !VT.isInteger())
1135     return false;
1136
1137   // If operation type is 'undesirable', e.g. i16 on x86, consider
1138   // promoting it.
1139   unsigned Opc = Op.getOpcode();
1140   if (TLI.isTypeDesirableForOp(Opc, VT))
1141     return false;
1142
1143   EVT PVT = VT;
1144   // Consult target whether it is a good idea to promote this operation and
1145   // what's the right type to promote it to.
1146   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147     assert(PVT != VT && "Don't know what type to promote to!");
1148
1149     SDLoc dl(Op);
1150     SDNode *N = Op.getNode();
1151     LoadSDNode *LD = cast<LoadSDNode>(N);
1152     EVT MemVT = LD->getMemoryVT();
1153     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1154       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1155                                                        : ISD::EXTLOAD)
1156       : LD->getExtensionType();
1157     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1158                                    LD->getChain(), LD->getBasePtr(),
1159                                    MemVT, LD->getMemOperand());
1160     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1161
1162     DEBUG(dbgs() << "\nPromoting ";
1163           N->dump(&DAG);
1164           dbgs() << "\nTo: ";
1165           Result.getNode()->dump(&DAG);
1166           dbgs() << '\n');
1167     WorklistRemover DeadNodes(*this);
1168     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1169     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1170     deleteAndRecombine(N);
1171     AddToWorklist(Result.getNode());
1172     return true;
1173   }
1174   return false;
1175 }
1176
1177 /// \brief Recursively delete a node which has no uses and any operands for
1178 /// which it is the only use.
1179 ///
1180 /// Note that this both deletes the nodes and removes them from the worklist.
1181 /// It also adds any nodes who have had a user deleted to the worklist as they
1182 /// may now have only one use and subject to other combines.
1183 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1184   if (!N->use_empty())
1185     return false;
1186
1187   SmallSetVector<SDNode *, 16> Nodes;
1188   Nodes.insert(N);
1189   do {
1190     N = Nodes.pop_back_val();
1191     if (!N)
1192       continue;
1193
1194     if (N->use_empty()) {
1195       for (const SDValue &ChildN : N->op_values())
1196         Nodes.insert(ChildN.getNode());
1197
1198       removeFromWorklist(N);
1199       DAG.DeleteNode(N);
1200     } else {
1201       AddToWorklist(N);
1202     }
1203   } while (!Nodes.empty());
1204   return true;
1205 }
1206
1207 //===----------------------------------------------------------------------===//
1208 //  Main DAG Combiner implementation
1209 //===----------------------------------------------------------------------===//
1210
1211 void DAGCombiner::Run(CombineLevel AtLevel) {
1212   // set the instance variables, so that the various visit routines may use it.
1213   Level = AtLevel;
1214   LegalOperations = Level >= AfterLegalizeVectorOps;
1215   LegalTypes = Level >= AfterLegalizeTypes;
1216
1217   // Add all the dag nodes to the worklist.
1218   for (SDNode &Node : DAG.allnodes())
1219     AddToWorklist(&Node);
1220
1221   // Create a dummy node (which is not added to allnodes), that adds a reference
1222   // to the root node, preventing it from being deleted, and tracking any
1223   // changes of the root.
1224   HandleSDNode Dummy(DAG.getRoot());
1225
1226   // while the worklist isn't empty, find a node and
1227   // try and combine it.
1228   while (!WorklistMap.empty()) {
1229     SDNode *N;
1230     // The Worklist holds the SDNodes in order, but it may contain null entries.
1231     do {
1232       N = Worklist.pop_back_val();
1233     } while (!N);
1234
1235     bool GoodWorklistEntry = WorklistMap.erase(N);
1236     (void)GoodWorklistEntry;
1237     assert(GoodWorklistEntry &&
1238            "Found a worklist entry without a corresponding map entry!");
1239
1240     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1241     // N is deleted from the DAG, since they too may now be dead or may have a
1242     // reduced number of uses, allowing other xforms.
1243     if (recursivelyDeleteUnusedNodes(N))
1244       continue;
1245
1246     WorklistRemover DeadNodes(*this);
1247
1248     // If this combine is running after legalizing the DAG, re-legalize any
1249     // nodes pulled off the worklist.
1250     if (Level == AfterLegalizeDAG) {
1251       SmallSetVector<SDNode *, 16> UpdatedNodes;
1252       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1253
1254       for (SDNode *LN : UpdatedNodes) {
1255         AddToWorklist(LN);
1256         AddUsersToWorklist(LN);
1257       }
1258       if (!NIsValid)
1259         continue;
1260     }
1261
1262     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1263
1264     // Add any operands of the new node which have not yet been combined to the
1265     // worklist as well. Because the worklist uniques things already, this
1266     // won't repeatedly process the same operand.
1267     CombinedNodes.insert(N);
1268     for (const SDValue &ChildN : N->op_values())
1269       if (!CombinedNodes.count(ChildN.getNode()))
1270         AddToWorklist(ChildN.getNode());
1271
1272     SDValue RV = combine(N);
1273
1274     if (!RV.getNode())
1275       continue;
1276
1277     ++NodesCombined;
1278
1279     // If we get back the same node we passed in, rather than a new node or
1280     // zero, we know that the node must have defined multiple values and
1281     // CombineTo was used.  Since CombineTo takes care of the worklist
1282     // mechanics for us, we have no work to do in this case.
1283     if (RV.getNode() == N)
1284       continue;
1285
1286     assert(N->getOpcode() != ISD::DELETED_NODE &&
1287            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1288            "Node was deleted but visit returned new node!");
1289
1290     DEBUG(dbgs() << " ... into: ";
1291           RV.getNode()->dump(&DAG));
1292
1293     // Transfer debug value.
1294     DAG.TransferDbgValues(SDValue(N, 0), RV);
1295     if (N->getNumValues() == RV.getNode()->getNumValues())
1296       DAG.ReplaceAllUsesWith(N, RV.getNode());
1297     else {
1298       assert(N->getValueType(0) == RV.getValueType() &&
1299              N->getNumValues() == 1 && "Type mismatch");
1300       SDValue OpV = RV;
1301       DAG.ReplaceAllUsesWith(N, &OpV);
1302     }
1303
1304     // Push the new node and any users onto the worklist
1305     AddToWorklist(RV.getNode());
1306     AddUsersToWorklist(RV.getNode());
1307
1308     // Finally, if the node is now dead, remove it from the graph.  The node
1309     // may not be dead if the replacement process recursively simplified to
1310     // something else needing this node. This will also take care of adding any
1311     // operands which have lost a user to the worklist.
1312     recursivelyDeleteUnusedNodes(N);
1313   }
1314
1315   // If the root changed (e.g. it was a dead load, update the root).
1316   DAG.setRoot(Dummy.getValue());
1317   DAG.RemoveDeadNodes();
1318 }
1319
1320 SDValue DAGCombiner::visit(SDNode *N) {
1321   switch (N->getOpcode()) {
1322   default: break;
1323   case ISD::TokenFactor:        return visitTokenFactor(N);
1324   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1325   case ISD::ADD:                return visitADD(N);
1326   case ISD::SUB:                return visitSUB(N);
1327   case ISD::ADDC:               return visitADDC(N);
1328   case ISD::SUBC:               return visitSUBC(N);
1329   case ISD::ADDE:               return visitADDE(N);
1330   case ISD::SUBE:               return visitSUBE(N);
1331   case ISD::MUL:                return visitMUL(N);
1332   case ISD::SDIV:               return visitSDIV(N);
1333   case ISD::UDIV:               return visitUDIV(N);
1334   case ISD::SREM:               return visitSREM(N);
1335   case ISD::UREM:               return visitUREM(N);
1336   case ISD::MULHU:              return visitMULHU(N);
1337   case ISD::MULHS:              return visitMULHS(N);
1338   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1339   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1340   case ISD::SMULO:              return visitSMULO(N);
1341   case ISD::UMULO:              return visitUMULO(N);
1342   case ISD::SDIVREM:            return visitSDIVREM(N);
1343   case ISD::UDIVREM:            return visitUDIVREM(N);
1344   case ISD::AND:                return visitAND(N);
1345   case ISD::OR:                 return visitOR(N);
1346   case ISD::XOR:                return visitXOR(N);
1347   case ISD::SHL:                return visitSHL(N);
1348   case ISD::SRA:                return visitSRA(N);
1349   case ISD::SRL:                return visitSRL(N);
1350   case ISD::ROTR:
1351   case ISD::ROTL:               return visitRotate(N);
1352   case ISD::BSWAP:              return visitBSWAP(N);
1353   case ISD::CTLZ:               return visitCTLZ(N);
1354   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1355   case ISD::CTTZ:               return visitCTTZ(N);
1356   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1357   case ISD::CTPOP:              return visitCTPOP(N);
1358   case ISD::SELECT:             return visitSELECT(N);
1359   case ISD::VSELECT:            return visitVSELECT(N);
1360   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1361   case ISD::SETCC:              return visitSETCC(N);
1362   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1363   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1364   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1365   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1366   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1367   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1368   case ISD::BITCAST:            return visitBITCAST(N);
1369   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1370   case ISD::FADD:               return visitFADD(N);
1371   case ISD::FSUB:               return visitFSUB(N);
1372   case ISD::FMUL:               return visitFMUL(N);
1373   case ISD::FMA:                return visitFMA(N);
1374   case ISD::FDIV:               return visitFDIV(N);
1375   case ISD::FREM:               return visitFREM(N);
1376   case ISD::FSQRT:              return visitFSQRT(N);
1377   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1378   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1379   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1380   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1381   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1382   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1383   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1384   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1385   case ISD::FNEG:               return visitFNEG(N);
1386   case ISD::FABS:               return visitFABS(N);
1387   case ISD::FFLOOR:             return visitFFLOOR(N);
1388   case ISD::FMINNUM:            return visitFMINNUM(N);
1389   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1390   case ISD::FCEIL:              return visitFCEIL(N);
1391   case ISD::FTRUNC:             return visitFTRUNC(N);
1392   case ISD::BRCOND:             return visitBRCOND(N);
1393   case ISD::BR_CC:              return visitBR_CC(N);
1394   case ISD::LOAD:               return visitLOAD(N);
1395   case ISD::STORE:              return visitSTORE(N);
1396   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1397   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1398   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1399   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1400   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1401   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1402   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1403   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1404   case ISD::MGATHER:            return visitMGATHER(N);
1405   case ISD::MLOAD:              return visitMLOAD(N);
1406   case ISD::MSCATTER:           return visitMSCATTER(N);
1407   case ISD::MSTORE:             return visitMSTORE(N);
1408   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1409   }
1410   return SDValue();
1411 }
1412
1413 SDValue DAGCombiner::combine(SDNode *N) {
1414   SDValue RV = visit(N);
1415
1416   // If nothing happened, try a target-specific DAG combine.
1417   if (!RV.getNode()) {
1418     assert(N->getOpcode() != ISD::DELETED_NODE &&
1419            "Node was deleted but visit returned NULL!");
1420
1421     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1422         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1423
1424       // Expose the DAG combiner to the target combiner impls.
1425       TargetLowering::DAGCombinerInfo
1426         DagCombineInfo(DAG, Level, false, this);
1427
1428       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1429     }
1430   }
1431
1432   // If nothing happened still, try promoting the operation.
1433   if (!RV.getNode()) {
1434     switch (N->getOpcode()) {
1435     default: break;
1436     case ISD::ADD:
1437     case ISD::SUB:
1438     case ISD::MUL:
1439     case ISD::AND:
1440     case ISD::OR:
1441     case ISD::XOR:
1442       RV = PromoteIntBinOp(SDValue(N, 0));
1443       break;
1444     case ISD::SHL:
1445     case ISD::SRA:
1446     case ISD::SRL:
1447       RV = PromoteIntShiftOp(SDValue(N, 0));
1448       break;
1449     case ISD::SIGN_EXTEND:
1450     case ISD::ZERO_EXTEND:
1451     case ISD::ANY_EXTEND:
1452       RV = PromoteExtend(SDValue(N, 0));
1453       break;
1454     case ISD::LOAD:
1455       if (PromoteLoad(SDValue(N, 0)))
1456         RV = SDValue(N, 0);
1457       break;
1458     }
1459   }
1460
1461   // If N is a commutative binary node, try commuting it to enable more
1462   // sdisel CSE.
1463   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1464       N->getNumValues() == 1) {
1465     SDValue N0 = N->getOperand(0);
1466     SDValue N1 = N->getOperand(1);
1467
1468     // Constant operands are canonicalized to RHS.
1469     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1470       SDValue Ops[] = {N1, N0};
1471       SDNode *CSENode;
1472       if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1473         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1474                                       &BinNode->Flags);
1475       } else {
1476         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1477       }
1478       if (CSENode)
1479         return SDValue(CSENode, 0);
1480     }
1481   }
1482
1483   return RV;
1484 }
1485
1486 /// Given a node, return its input chain if it has one, otherwise return a null
1487 /// sd operand.
1488 static SDValue getInputChainForNode(SDNode *N) {
1489   if (unsigned NumOps = N->getNumOperands()) {
1490     if (N->getOperand(0).getValueType() == MVT::Other)
1491       return N->getOperand(0);
1492     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1493       return N->getOperand(NumOps-1);
1494     for (unsigned i = 1; i < NumOps-1; ++i)
1495       if (N->getOperand(i).getValueType() == MVT::Other)
1496         return N->getOperand(i);
1497   }
1498   return SDValue();
1499 }
1500
1501 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1502   // If N has two operands, where one has an input chain equal to the other,
1503   // the 'other' chain is redundant.
1504   if (N->getNumOperands() == 2) {
1505     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1506       return N->getOperand(0);
1507     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1508       return N->getOperand(1);
1509   }
1510
1511   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1512   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1513   SmallPtrSet<SDNode*, 16> SeenOps;
1514   bool Changed = false;             // If we should replace this token factor.
1515
1516   // Start out with this token factor.
1517   TFs.push_back(N);
1518
1519   // Iterate through token factors.  The TFs grows when new token factors are
1520   // encountered.
1521   for (unsigned i = 0; i < TFs.size(); ++i) {
1522     SDNode *TF = TFs[i];
1523
1524     // Check each of the operands.
1525     for (const SDValue &Op : TF->op_values()) {
1526
1527       switch (Op.getOpcode()) {
1528       case ISD::EntryToken:
1529         // Entry tokens don't need to be added to the list. They are
1530         // redundant.
1531         Changed = true;
1532         break;
1533
1534       case ISD::TokenFactor:
1535         if (Op.hasOneUse() &&
1536             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1537           // Queue up for processing.
1538           TFs.push_back(Op.getNode());
1539           // Clean up in case the token factor is removed.
1540           AddToWorklist(Op.getNode());
1541           Changed = true;
1542           break;
1543         }
1544         // Fall thru
1545
1546       default:
1547         // Only add if it isn't already in the list.
1548         if (SeenOps.insert(Op.getNode()).second)
1549           Ops.push_back(Op);
1550         else
1551           Changed = true;
1552         break;
1553       }
1554     }
1555   }
1556
1557   SDValue Result;
1558
1559   // If we've changed things around then replace token factor.
1560   if (Changed) {
1561     if (Ops.empty()) {
1562       // The entry token is the only possible outcome.
1563       Result = DAG.getEntryNode();
1564     } else {
1565       // New and improved token factor.
1566       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1567     }
1568
1569     // Add users to worklist if AA is enabled, since it may introduce
1570     // a lot of new chained token factors while removing memory deps.
1571     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1572       : DAG.getSubtarget().useAA();
1573     return CombineTo(N, Result, UseAA /*add to worklist*/);
1574   }
1575
1576   return Result;
1577 }
1578
1579 /// MERGE_VALUES can always be eliminated.
1580 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1581   WorklistRemover DeadNodes(*this);
1582   // Replacing results may cause a different MERGE_VALUES to suddenly
1583   // be CSE'd with N, and carry its uses with it. Iterate until no
1584   // uses remain, to ensure that the node can be safely deleted.
1585   // First add the users of this node to the work list so that they
1586   // can be tried again once they have new operands.
1587   AddUsersToWorklist(N);
1588   do {
1589     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1590       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1591   } while (!N->use_empty());
1592   deleteAndRecombine(N);
1593   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1594 }
1595
1596 static bool isNullConstant(SDValue V) {
1597   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1598   return Const != nullptr && Const->isNullValue();
1599 }
1600
1601 static bool isNullFPConstant(SDValue V) {
1602   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1603   return Const != nullptr && Const->isZero() && !Const->isNegative();
1604 }
1605
1606 static bool isAllOnesConstant(SDValue V) {
1607   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1608   return Const != nullptr && Const->isAllOnesValue();
1609 }
1610
1611 static bool isOneConstant(SDValue V) {
1612   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1613   return Const != nullptr && Const->isOne();
1614 }
1615
1616 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1617 /// ContantSDNode pointer else nullptr.
1618 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1619   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1620   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1621 }
1622
1623 SDValue DAGCombiner::visitADD(SDNode *N) {
1624   SDValue N0 = N->getOperand(0);
1625   SDValue N1 = N->getOperand(1);
1626   EVT VT = N0.getValueType();
1627
1628   // fold vector ops
1629   if (VT.isVector()) {
1630     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1631       return FoldedVOp;
1632
1633     // fold (add x, 0) -> x, vector edition
1634     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1635       return N0;
1636     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1637       return N1;
1638   }
1639
1640   // fold (add x, undef) -> undef
1641   if (N0.getOpcode() == ISD::UNDEF)
1642     return N0;
1643   if (N1.getOpcode() == ISD::UNDEF)
1644     return N1;
1645   // fold (add c1, c2) -> c1+c2
1646   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1647   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1648   if (N0C && N1C)
1649     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1650   // canonicalize constant to RHS
1651   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1652      !isConstantIntBuildVectorOrConstantInt(N1))
1653     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1654   // fold (add x, 0) -> x
1655   if (isNullConstant(N1))
1656     return N0;
1657   // fold (add Sym, c) -> Sym+c
1658   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1659     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1660         GA->getOpcode() == ISD::GlobalAddress)
1661       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1662                                   GA->getOffset() +
1663                                     (uint64_t)N1C->getSExtValue());
1664   // fold ((c1-A)+c2) -> (c1+c2)-A
1665   if (N1C && N0.getOpcode() == ISD::SUB)
1666     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1667       SDLoc DL(N);
1668       return DAG.getNode(ISD::SUB, DL, VT,
1669                          DAG.getConstant(N1C->getAPIntValue()+
1670                                          N0C->getAPIntValue(), DL, VT),
1671                          N0.getOperand(1));
1672     }
1673   // reassociate add
1674   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1675     return RADD;
1676   // fold ((0-A) + B) -> B-A
1677   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1678     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1679   // fold (A + (0-B)) -> A-B
1680   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1681     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1682   // fold (A+(B-A)) -> B
1683   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1684     return N1.getOperand(0);
1685   // fold ((B-A)+A) -> B
1686   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1687     return N0.getOperand(0);
1688   // fold (A+(B-(A+C))) to (B-C)
1689   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1690       N0 == N1.getOperand(1).getOperand(0))
1691     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1692                        N1.getOperand(1).getOperand(1));
1693   // fold (A+(B-(C+A))) to (B-C)
1694   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1695       N0 == N1.getOperand(1).getOperand(1))
1696     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1697                        N1.getOperand(1).getOperand(0));
1698   // fold (A+((B-A)+or-C)) to (B+or-C)
1699   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1700       N1.getOperand(0).getOpcode() == ISD::SUB &&
1701       N0 == N1.getOperand(0).getOperand(1))
1702     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1703                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1704
1705   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1706   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1707     SDValue N00 = N0.getOperand(0);
1708     SDValue N01 = N0.getOperand(1);
1709     SDValue N10 = N1.getOperand(0);
1710     SDValue N11 = N1.getOperand(1);
1711
1712     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1713       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1714                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1715                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1716   }
1717
1718   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1719     return SDValue(N, 0);
1720
1721   // fold (a+b) -> (a|b) iff a and b share no bits.
1722   if (VT.isInteger() && !VT.isVector()) {
1723     APInt LHSZero, LHSOne;
1724     APInt RHSZero, RHSOne;
1725     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1726
1727     if (LHSZero.getBoolValue()) {
1728       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1729
1730       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1731       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1732       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1733         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1734           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1735       }
1736     }
1737   }
1738
1739   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1740   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1741       isNullConstant(N1.getOperand(0).getOperand(0)))
1742     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1743                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1744                                    N1.getOperand(0).getOperand(1),
1745                                    N1.getOperand(1)));
1746   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1747       isNullConstant(N0.getOperand(0).getOperand(0)))
1748     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1749                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1750                                    N0.getOperand(0).getOperand(1),
1751                                    N0.getOperand(1)));
1752
1753   if (N1.getOpcode() == ISD::AND) {
1754     SDValue AndOp0 = N1.getOperand(0);
1755     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1756     unsigned DestBits = VT.getScalarType().getSizeInBits();
1757
1758     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1759     // and similar xforms where the inner op is either ~0 or 0.
1760     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1761       SDLoc DL(N);
1762       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1763     }
1764   }
1765
1766   // add (sext i1), X -> sub X, (zext i1)
1767   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1768       N0.getOperand(0).getValueType() == MVT::i1 &&
1769       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1770     SDLoc DL(N);
1771     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1772     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1773   }
1774
1775   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1776   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1777     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1778     if (TN->getVT() == MVT::i1) {
1779       SDLoc DL(N);
1780       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1781                                  DAG.getConstant(1, DL, VT));
1782       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1783     }
1784   }
1785
1786   return SDValue();
1787 }
1788
1789 SDValue DAGCombiner::visitADDC(SDNode *N) {
1790   SDValue N0 = N->getOperand(0);
1791   SDValue N1 = N->getOperand(1);
1792   EVT VT = N0.getValueType();
1793
1794   // If the flag result is dead, turn this into an ADD.
1795   if (!N->hasAnyUseOfValue(1))
1796     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1797                      DAG.getNode(ISD::CARRY_FALSE,
1798                                  SDLoc(N), MVT::Glue));
1799
1800   // canonicalize constant to RHS.
1801   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1802   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1803   if (N0C && !N1C)
1804     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1805
1806   // fold (addc x, 0) -> x + no carry out
1807   if (isNullConstant(N1))
1808     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1809                                         SDLoc(N), MVT::Glue));
1810
1811   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1812   APInt LHSZero, LHSOne;
1813   APInt RHSZero, RHSOne;
1814   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1815
1816   if (LHSZero.getBoolValue()) {
1817     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1818
1819     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1820     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1821     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1822       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1823                        DAG.getNode(ISD::CARRY_FALSE,
1824                                    SDLoc(N), MVT::Glue));
1825   }
1826
1827   return SDValue();
1828 }
1829
1830 SDValue DAGCombiner::visitADDE(SDNode *N) {
1831   SDValue N0 = N->getOperand(0);
1832   SDValue N1 = N->getOperand(1);
1833   SDValue CarryIn = N->getOperand(2);
1834
1835   // canonicalize constant to RHS
1836   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1837   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1838   if (N0C && !N1C)
1839     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1840                        N1, N0, CarryIn);
1841
1842   // fold (adde x, y, false) -> (addc x, y)
1843   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1844     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1845
1846   return SDValue();
1847 }
1848
1849 // Since it may not be valid to emit a fold to zero for vector initializers
1850 // check if we can before folding.
1851 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1852                              SelectionDAG &DAG,
1853                              bool LegalOperations, bool LegalTypes) {
1854   if (!VT.isVector())
1855     return DAG.getConstant(0, DL, VT);
1856   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1857     return DAG.getConstant(0, DL, VT);
1858   return SDValue();
1859 }
1860
1861 SDValue DAGCombiner::visitSUB(SDNode *N) {
1862   SDValue N0 = N->getOperand(0);
1863   SDValue N1 = N->getOperand(1);
1864   EVT VT = N0.getValueType();
1865
1866   // fold vector ops
1867   if (VT.isVector()) {
1868     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1869       return FoldedVOp;
1870
1871     // fold (sub x, 0) -> x, vector edition
1872     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1873       return N0;
1874   }
1875
1876   // fold (sub x, x) -> 0
1877   // FIXME: Refactor this and xor and other similar operations together.
1878   if (N0 == N1)
1879     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1880   // fold (sub c1, c2) -> c1-c2
1881   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1882   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1883   if (N0C && N1C)
1884     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1885   // fold (sub x, c) -> (add x, -c)
1886   if (N1C) {
1887     SDLoc DL(N);
1888     return DAG.getNode(ISD::ADD, DL, VT, N0,
1889                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1890   }
1891   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1892   if (isAllOnesConstant(N0))
1893     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1894   // fold A-(A-B) -> B
1895   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1896     return N1.getOperand(1);
1897   // fold (A+B)-A -> B
1898   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1899     return N0.getOperand(1);
1900   // fold (A+B)-B -> A
1901   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1902     return N0.getOperand(0);
1903   // fold C2-(A+C1) -> (C2-C1)-A
1904   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1905     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1906   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1907     SDLoc DL(N);
1908     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1909                                    DL, VT);
1910     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1911                        N1.getOperand(0));
1912   }
1913   // fold ((A+(B+or-C))-B) -> A+or-C
1914   if (N0.getOpcode() == ISD::ADD &&
1915       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1916        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1917       N0.getOperand(1).getOperand(0) == N1)
1918     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1919                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1920   // fold ((A+(C+B))-B) -> A+C
1921   if (N0.getOpcode() == ISD::ADD &&
1922       N0.getOperand(1).getOpcode() == ISD::ADD &&
1923       N0.getOperand(1).getOperand(1) == N1)
1924     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1925                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1926   // fold ((A-(B-C))-C) -> A-B
1927   if (N0.getOpcode() == ISD::SUB &&
1928       N0.getOperand(1).getOpcode() == ISD::SUB &&
1929       N0.getOperand(1).getOperand(1) == N1)
1930     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1931                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1932
1933   // If either operand of a sub is undef, the result is undef
1934   if (N0.getOpcode() == ISD::UNDEF)
1935     return N0;
1936   if (N1.getOpcode() == ISD::UNDEF)
1937     return N1;
1938
1939   // If the relocation model supports it, consider symbol offsets.
1940   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1941     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1942       // fold (sub Sym, c) -> Sym-c
1943       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1944         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1945                                     GA->getOffset() -
1946                                       (uint64_t)N1C->getSExtValue());
1947       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1948       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1949         if (GA->getGlobal() == GB->getGlobal())
1950           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1951                                  SDLoc(N), VT);
1952     }
1953
1954   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1955   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1956     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1957     if (TN->getVT() == MVT::i1) {
1958       SDLoc DL(N);
1959       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1960                                  DAG.getConstant(1, DL, VT));
1961       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1962     }
1963   }
1964
1965   return SDValue();
1966 }
1967
1968 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1969   SDValue N0 = N->getOperand(0);
1970   SDValue N1 = N->getOperand(1);
1971   EVT VT = N0.getValueType();
1972
1973   // If the flag result is dead, turn this into an SUB.
1974   if (!N->hasAnyUseOfValue(1))
1975     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1976                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1977                                  MVT::Glue));
1978
1979   // fold (subc x, x) -> 0 + no borrow
1980   if (N0 == N1) {
1981     SDLoc DL(N);
1982     return CombineTo(N, DAG.getConstant(0, DL, VT),
1983                      DAG.getNode(ISD::CARRY_FALSE, DL,
1984                                  MVT::Glue));
1985   }
1986
1987   // fold (subc x, 0) -> x + no borrow
1988   if (isNullConstant(N1))
1989     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1990                                         MVT::Glue));
1991
1992   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1993   if (isAllOnesConstant(N0))
1994     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1995                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1996                                  MVT::Glue));
1997
1998   return SDValue();
1999 }
2000
2001 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2002   SDValue N0 = N->getOperand(0);
2003   SDValue N1 = N->getOperand(1);
2004   SDValue CarryIn = N->getOperand(2);
2005
2006   // fold (sube x, y, false) -> (subc x, y)
2007   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2008     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2009
2010   return SDValue();
2011 }
2012
2013 SDValue DAGCombiner::visitMUL(SDNode *N) {
2014   SDValue N0 = N->getOperand(0);
2015   SDValue N1 = N->getOperand(1);
2016   EVT VT = N0.getValueType();
2017
2018   // fold (mul x, undef) -> 0
2019   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2020     return DAG.getConstant(0, SDLoc(N), VT);
2021
2022   bool N0IsConst = false;
2023   bool N1IsConst = false;
2024   bool N1IsOpaqueConst = false;
2025   bool N0IsOpaqueConst = false;
2026   APInt ConstValue0, ConstValue1;
2027   // fold vector ops
2028   if (VT.isVector()) {
2029     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2030       return FoldedVOp;
2031
2032     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2033     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2034   } else {
2035     N0IsConst = isa<ConstantSDNode>(N0);
2036     if (N0IsConst) {
2037       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2038       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2039     }
2040     N1IsConst = isa<ConstantSDNode>(N1);
2041     if (N1IsConst) {
2042       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2043       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2044     }
2045   }
2046
2047   // fold (mul c1, c2) -> c1*c2
2048   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2049     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2050                                       N0.getNode(), N1.getNode());
2051
2052   // canonicalize constant to RHS (vector doesn't have to splat)
2053   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2054      !isConstantIntBuildVectorOrConstantInt(N1))
2055     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2056   // fold (mul x, 0) -> 0
2057   if (N1IsConst && ConstValue1 == 0)
2058     return N1;
2059   // We require a splat of the entire scalar bit width for non-contiguous
2060   // bit patterns.
2061   bool IsFullSplat =
2062     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2063   // fold (mul x, 1) -> x
2064   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2065     return N0;
2066   // fold (mul x, -1) -> 0-x
2067   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2068     SDLoc DL(N);
2069     return DAG.getNode(ISD::SUB, DL, VT,
2070                        DAG.getConstant(0, DL, VT), N0);
2071   }
2072   // fold (mul x, (1 << c)) -> x << c
2073   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2074       IsFullSplat) {
2075     SDLoc DL(N);
2076     return DAG.getNode(ISD::SHL, DL, VT, N0,
2077                        DAG.getConstant(ConstValue1.logBase2(), DL,
2078                                        getShiftAmountTy(N0.getValueType())));
2079   }
2080   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2081   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2082       IsFullSplat) {
2083     unsigned Log2Val = (-ConstValue1).logBase2();
2084     SDLoc DL(N);
2085     // FIXME: If the input is something that is easily negated (e.g. a
2086     // single-use add), we should put the negate there.
2087     return DAG.getNode(ISD::SUB, DL, VT,
2088                        DAG.getConstant(0, DL, VT),
2089                        DAG.getNode(ISD::SHL, DL, VT, N0,
2090                             DAG.getConstant(Log2Val, DL,
2091                                       getShiftAmountTy(N0.getValueType()))));
2092   }
2093
2094   APInt Val;
2095   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2096   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2097       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2098                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2099     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2100                              N1, N0.getOperand(1));
2101     AddToWorklist(C3.getNode());
2102     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2103                        N0.getOperand(0), C3);
2104   }
2105
2106   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2107   // use.
2108   {
2109     SDValue Sh(nullptr,0), Y(nullptr,0);
2110     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2111     if (N0.getOpcode() == ISD::SHL &&
2112         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2113                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2114         N0.getNode()->hasOneUse()) {
2115       Sh = N0; Y = N1;
2116     } else if (N1.getOpcode() == ISD::SHL &&
2117                isa<ConstantSDNode>(N1.getOperand(1)) &&
2118                N1.getNode()->hasOneUse()) {
2119       Sh = N1; Y = N0;
2120     }
2121
2122     if (Sh.getNode()) {
2123       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2124                                 Sh.getOperand(0), Y);
2125       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2126                          Mul, Sh.getOperand(1));
2127     }
2128   }
2129
2130   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2131   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2132       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2133                      isa<ConstantSDNode>(N0.getOperand(1))))
2134     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2135                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2136                                    N0.getOperand(0), N1),
2137                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2138                                    N0.getOperand(1), N1));
2139
2140   // reassociate mul
2141   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2142     return RMUL;
2143
2144   return SDValue();
2145 }
2146
2147 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2148   SDValue N0 = N->getOperand(0);
2149   SDValue N1 = N->getOperand(1);
2150   EVT VT = N->getValueType(0);
2151
2152   // fold vector ops
2153   if (VT.isVector())
2154     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2155       return FoldedVOp;
2156
2157   // fold (sdiv c1, c2) -> c1/c2
2158   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2159   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2160   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2161     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2162   // fold (sdiv X, 1) -> X
2163   if (N1C && N1C->isOne())
2164     return N0;
2165   // fold (sdiv X, -1) -> 0-X
2166   if (N1C && N1C->isAllOnesValue()) {
2167     SDLoc DL(N);
2168     return DAG.getNode(ISD::SUB, DL, VT,
2169                        DAG.getConstant(0, DL, VT), N0);
2170   }
2171   // If we know the sign bits of both operands are zero, strength reduce to a
2172   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2173   if (!VT.isVector()) {
2174     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2175       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2176                          N0, N1);
2177   }
2178
2179   // fold (sdiv X, pow2) -> simple ops after legalize
2180   // FIXME: We check for the exact bit here because the generic lowering gives
2181   // better results in that case. The target-specific lowering should learn how
2182   // to handle exact sdivs efficiently.
2183   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2184       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2185       (N1C->getAPIntValue().isPowerOf2() ||
2186        (-N1C->getAPIntValue()).isPowerOf2())) {
2187     // If dividing by powers of two is cheap, then don't perform the following
2188     // fold.
2189     if (TLI.isPow2SDivCheap())
2190       return SDValue();
2191
2192     // Target-specific implementation of sdiv x, pow2.
2193     if (SDValue Res = BuildSDIVPow2(N))
2194       return Res;
2195
2196     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2197     SDLoc DL(N);
2198
2199     // Splat the sign bit into the register
2200     SDValue SGN =
2201         DAG.getNode(ISD::SRA, DL, VT, N0,
2202                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2203                                     getShiftAmountTy(N0.getValueType())));
2204     AddToWorklist(SGN.getNode());
2205
2206     // Add (N0 < 0) ? abs2 - 1 : 0;
2207     SDValue SRL =
2208         DAG.getNode(ISD::SRL, DL, VT, SGN,
2209                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2210                                     getShiftAmountTy(SGN.getValueType())));
2211     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2212     AddToWorklist(SRL.getNode());
2213     AddToWorklist(ADD.getNode());    // Divide by pow2
2214     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2215                   DAG.getConstant(lg2, DL,
2216                                   getShiftAmountTy(ADD.getValueType())));
2217
2218     // If we're dividing by a positive value, we're done.  Otherwise, we must
2219     // negate the result.
2220     if (N1C->getAPIntValue().isNonNegative())
2221       return SRA;
2222
2223     AddToWorklist(SRA.getNode());
2224     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2225   }
2226
2227   // If integer divide is expensive and we satisfy the requirements, emit an
2228   // alternate sequence.
2229   if (N1C && !TLI.isIntDivCheap())
2230     if (SDValue Op = BuildSDIV(N))
2231       return Op;
2232
2233   // undef / X -> 0
2234   if (N0.getOpcode() == ISD::UNDEF)
2235     return DAG.getConstant(0, SDLoc(N), VT);
2236   // X / undef -> undef
2237   if (N1.getOpcode() == ISD::UNDEF)
2238     return N1;
2239
2240   return SDValue();
2241 }
2242
2243 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2244   SDValue N0 = N->getOperand(0);
2245   SDValue N1 = N->getOperand(1);
2246   EVT VT = N->getValueType(0);
2247
2248   // fold vector ops
2249   if (VT.isVector())
2250     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2251       return FoldedVOp;
2252
2253   // fold (udiv c1, c2) -> c1/c2
2254   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2255   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2256   if (N0C && N1C)
2257     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2258                                                     N0C, N1C))
2259       return Folded;
2260   // fold (udiv x, (1 << c)) -> x >>u c
2261   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2262     SDLoc DL(N);
2263     return DAG.getNode(ISD::SRL, DL, VT, N0,
2264                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2265                                        getShiftAmountTy(N0.getValueType())));
2266   }
2267   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2268   if (N1.getOpcode() == ISD::SHL) {
2269     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2270       if (SHC->getAPIntValue().isPowerOf2()) {
2271         EVT ADDVT = N1.getOperand(1).getValueType();
2272         SDLoc DL(N);
2273         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2274                                   N1.getOperand(1),
2275                                   DAG.getConstant(SHC->getAPIntValue()
2276                                                                   .logBase2(),
2277                                                   DL, ADDVT));
2278         AddToWorklist(Add.getNode());
2279         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2280       }
2281     }
2282   }
2283   // fold (udiv x, c) -> alternate
2284   if (N1C && !TLI.isIntDivCheap())
2285     if (SDValue Op = BuildUDIV(N))
2286       return Op;
2287
2288   // undef / X -> 0
2289   if (N0.getOpcode() == ISD::UNDEF)
2290     return DAG.getConstant(0, SDLoc(N), VT);
2291   // X / undef -> undef
2292   if (N1.getOpcode() == ISD::UNDEF)
2293     return N1;
2294
2295   return SDValue();
2296 }
2297
2298 SDValue DAGCombiner::visitSREM(SDNode *N) {
2299   SDValue N0 = N->getOperand(0);
2300   SDValue N1 = N->getOperand(1);
2301   EVT VT = N->getValueType(0);
2302
2303   // fold (srem c1, c2) -> c1%c2
2304   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2305   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2306   if (N0C && N1C)
2307     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2308                                                     N0C, N1C))
2309       return Folded;
2310   // If we know the sign bits of both operands are zero, strength reduce to a
2311   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2312   if (!VT.isVector()) {
2313     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2314       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2315   }
2316
2317   // If X/C can be simplified by the division-by-constant logic, lower
2318   // X%C to the equivalent of X-X/C*C.
2319   if (N1C && !N1C->isNullValue()) {
2320     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2321     AddToWorklist(Div.getNode());
2322     SDValue OptimizedDiv = combine(Div.getNode());
2323     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2324       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2325                                 OptimizedDiv, N1);
2326       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2327       AddToWorklist(Mul.getNode());
2328       return Sub;
2329     }
2330   }
2331
2332   // undef % X -> 0
2333   if (N0.getOpcode() == ISD::UNDEF)
2334     return DAG.getConstant(0, SDLoc(N), VT);
2335   // X % undef -> undef
2336   if (N1.getOpcode() == ISD::UNDEF)
2337     return N1;
2338
2339   return SDValue();
2340 }
2341
2342 SDValue DAGCombiner::visitUREM(SDNode *N) {
2343   SDValue N0 = N->getOperand(0);
2344   SDValue N1 = N->getOperand(1);
2345   EVT VT = N->getValueType(0);
2346
2347   // fold (urem c1, c2) -> c1%c2
2348   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2349   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2350   if (N0C && N1C)
2351     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2352                                                     N0C, N1C))
2353       return Folded;
2354   // fold (urem x, pow2) -> (and x, pow2-1)
2355   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2356       N1C->getAPIntValue().isPowerOf2()) {
2357     SDLoc DL(N);
2358     return DAG.getNode(ISD::AND, DL, VT, N0,
2359                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2360   }
2361   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2362   if (N1.getOpcode() == ISD::SHL) {
2363     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2364       if (SHC->getAPIntValue().isPowerOf2()) {
2365         SDLoc DL(N);
2366         SDValue Add =
2367           DAG.getNode(ISD::ADD, DL, VT, N1,
2368                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2369                                  VT));
2370         AddToWorklist(Add.getNode());
2371         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2372       }
2373     }
2374   }
2375
2376   // If X/C can be simplified by the division-by-constant logic, lower
2377   // X%C to the equivalent of X-X/C*C.
2378   if (N1C && !N1C->isNullValue()) {
2379     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2380     AddToWorklist(Div.getNode());
2381     SDValue OptimizedDiv = combine(Div.getNode());
2382     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2383       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2384                                 OptimizedDiv, N1);
2385       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2386       AddToWorklist(Mul.getNode());
2387       return Sub;
2388     }
2389   }
2390
2391   // undef % X -> 0
2392   if (N0.getOpcode() == ISD::UNDEF)
2393     return DAG.getConstant(0, SDLoc(N), VT);
2394   // X % undef -> undef
2395   if (N1.getOpcode() == ISD::UNDEF)
2396     return N1;
2397
2398   return SDValue();
2399 }
2400
2401 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2402   SDValue N0 = N->getOperand(0);
2403   SDValue N1 = N->getOperand(1);
2404   EVT VT = N->getValueType(0);
2405   SDLoc DL(N);
2406
2407   // fold (mulhs x, 0) -> 0
2408   if (isNullConstant(N1))
2409     return N1;
2410   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2411   if (isOneConstant(N1)) {
2412     SDLoc DL(N);
2413     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2414                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2415                                        DL,
2416                                        getShiftAmountTy(N0.getValueType())));
2417   }
2418   // fold (mulhs x, undef) -> 0
2419   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2420     return DAG.getConstant(0, SDLoc(N), VT);
2421
2422   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2423   // plus a shift.
2424   if (VT.isSimple() && !VT.isVector()) {
2425     MVT Simple = VT.getSimpleVT();
2426     unsigned SimpleSize = Simple.getSizeInBits();
2427     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2428     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2429       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2430       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2431       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2432       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2433             DAG.getConstant(SimpleSize, DL,
2434                             getShiftAmountTy(N1.getValueType())));
2435       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2436     }
2437   }
2438
2439   return SDValue();
2440 }
2441
2442 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2443   SDValue N0 = N->getOperand(0);
2444   SDValue N1 = N->getOperand(1);
2445   EVT VT = N->getValueType(0);
2446   SDLoc DL(N);
2447
2448   // fold (mulhu x, 0) -> 0
2449   if (isNullConstant(N1))
2450     return N1;
2451   // fold (mulhu x, 1) -> 0
2452   if (isOneConstant(N1))
2453     return DAG.getConstant(0, DL, N0.getValueType());
2454   // fold (mulhu x, undef) -> 0
2455   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2456     return DAG.getConstant(0, DL, VT);
2457
2458   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2459   // plus a shift.
2460   if (VT.isSimple() && !VT.isVector()) {
2461     MVT Simple = VT.getSimpleVT();
2462     unsigned SimpleSize = Simple.getSizeInBits();
2463     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2466       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2467       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2468       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2469             DAG.getConstant(SimpleSize, DL,
2470                             getShiftAmountTy(N1.getValueType())));
2471       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2472     }
2473   }
2474
2475   return SDValue();
2476 }
2477
2478 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2479 /// give the opcodes for the two computations that are being performed. Return
2480 /// true if a simplification was made.
2481 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2482                                                 unsigned HiOp) {
2483   // If the high half is not needed, just compute the low half.
2484   bool HiExists = N->hasAnyUseOfValue(1);
2485   if (!HiExists &&
2486       (!LegalOperations ||
2487        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2488     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2489     return CombineTo(N, Res, Res);
2490   }
2491
2492   // If the low half is not needed, just compute the high half.
2493   bool LoExists = N->hasAnyUseOfValue(0);
2494   if (!LoExists &&
2495       (!LegalOperations ||
2496        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2497     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2498     return CombineTo(N, Res, Res);
2499   }
2500
2501   // If both halves are used, return as it is.
2502   if (LoExists && HiExists)
2503     return SDValue();
2504
2505   // If the two computed results can be simplified separately, separate them.
2506   if (LoExists) {
2507     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2508     AddToWorklist(Lo.getNode());
2509     SDValue LoOpt = combine(Lo.getNode());
2510     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2511         (!LegalOperations ||
2512          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2513       return CombineTo(N, LoOpt, LoOpt);
2514   }
2515
2516   if (HiExists) {
2517     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2518     AddToWorklist(Hi.getNode());
2519     SDValue HiOpt = combine(Hi.getNode());
2520     if (HiOpt.getNode() && HiOpt != Hi &&
2521         (!LegalOperations ||
2522          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2523       return CombineTo(N, HiOpt, HiOpt);
2524   }
2525
2526   return SDValue();
2527 }
2528
2529 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2530   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2531     return Res;
2532
2533   EVT VT = N->getValueType(0);
2534   SDLoc DL(N);
2535
2536   // If the type is twice as wide is legal, transform the mulhu to a wider
2537   // multiply plus a shift.
2538   if (VT.isSimple() && !VT.isVector()) {
2539     MVT Simple = VT.getSimpleVT();
2540     unsigned SimpleSize = Simple.getSizeInBits();
2541     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2542     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2543       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2544       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2545       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2546       // Compute the high part as N1.
2547       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2548             DAG.getConstant(SimpleSize, DL,
2549                             getShiftAmountTy(Lo.getValueType())));
2550       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2551       // Compute the low part as N0.
2552       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2553       return CombineTo(N, Lo, Hi);
2554     }
2555   }
2556
2557   return SDValue();
2558 }
2559
2560 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2561   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2562     return Res;
2563
2564   EVT VT = N->getValueType(0);
2565   SDLoc DL(N);
2566
2567   // If the type is twice as wide is legal, transform the mulhu to a wider
2568   // multiply plus a shift.
2569   if (VT.isSimple() && !VT.isVector()) {
2570     MVT Simple = VT.getSimpleVT();
2571     unsigned SimpleSize = Simple.getSizeInBits();
2572     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2573     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2574       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2575       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2576       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2577       // Compute the high part as N1.
2578       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2579             DAG.getConstant(SimpleSize, DL,
2580                             getShiftAmountTy(Lo.getValueType())));
2581       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2582       // Compute the low part as N0.
2583       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2584       return CombineTo(N, Lo, Hi);
2585     }
2586   }
2587
2588   return SDValue();
2589 }
2590
2591 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2592   // (smulo x, 2) -> (saddo x, x)
2593   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2594     if (C2->getAPIntValue() == 2)
2595       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2596                          N->getOperand(0), N->getOperand(0));
2597
2598   return SDValue();
2599 }
2600
2601 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2602   // (umulo x, 2) -> (uaddo x, x)
2603   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2604     if (C2->getAPIntValue() == 2)
2605       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2606                          N->getOperand(0), N->getOperand(0));
2607
2608   return SDValue();
2609 }
2610
2611 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2612   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2613     return Res;
2614
2615   return SDValue();
2616 }
2617
2618 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2619   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2620     return Res;
2621
2622   return SDValue();
2623 }
2624
2625 /// If this is a binary operator with two operands of the same opcode, try to
2626 /// simplify it.
2627 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2628   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2629   EVT VT = N0.getValueType();
2630   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2631
2632   // Bail early if none of these transforms apply.
2633   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2634
2635   // For each of OP in AND/OR/XOR:
2636   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2637   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2638   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2639   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2640   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2641   //
2642   // do not sink logical op inside of a vector extend, since it may combine
2643   // into a vsetcc.
2644   EVT Op0VT = N0.getOperand(0).getValueType();
2645   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2646        N0.getOpcode() == ISD::SIGN_EXTEND ||
2647        N0.getOpcode() == ISD::BSWAP ||
2648        // Avoid infinite looping with PromoteIntBinOp.
2649        (N0.getOpcode() == ISD::ANY_EXTEND &&
2650         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2651        (N0.getOpcode() == ISD::TRUNCATE &&
2652         (!TLI.isZExtFree(VT, Op0VT) ||
2653          !TLI.isTruncateFree(Op0VT, VT)) &&
2654         TLI.isTypeLegal(Op0VT))) &&
2655       !VT.isVector() &&
2656       Op0VT == N1.getOperand(0).getValueType() &&
2657       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2658     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2659                                  N0.getOperand(0).getValueType(),
2660                                  N0.getOperand(0), N1.getOperand(0));
2661     AddToWorklist(ORNode.getNode());
2662     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2663   }
2664
2665   // For each of OP in SHL/SRL/SRA/AND...
2666   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2667   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2668   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2669   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2670        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2671       N0.getOperand(1) == N1.getOperand(1)) {
2672     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2673                                  N0.getOperand(0).getValueType(),
2674                                  N0.getOperand(0), N1.getOperand(0));
2675     AddToWorklist(ORNode.getNode());
2676     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2677                        ORNode, N0.getOperand(1));
2678   }
2679
2680   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2681   // Only perform this optimization after type legalization and before
2682   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2683   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2684   // we don't want to undo this promotion.
2685   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2686   // on scalars.
2687   if ((N0.getOpcode() == ISD::BITCAST ||
2688        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2689       Level == AfterLegalizeTypes) {
2690     SDValue In0 = N0.getOperand(0);
2691     SDValue In1 = N1.getOperand(0);
2692     EVT In0Ty = In0.getValueType();
2693     EVT In1Ty = In1.getValueType();
2694     SDLoc DL(N);
2695     // If both incoming values are integers, and the original types are the
2696     // same.
2697     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2698       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2699       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2700       AddToWorklist(Op.getNode());
2701       return BC;
2702     }
2703   }
2704
2705   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2706   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2707   // If both shuffles use the same mask, and both shuffle within a single
2708   // vector, then it is worthwhile to move the swizzle after the operation.
2709   // The type-legalizer generates this pattern when loading illegal
2710   // vector types from memory. In many cases this allows additional shuffle
2711   // optimizations.
2712   // There are other cases where moving the shuffle after the xor/and/or
2713   // is profitable even if shuffles don't perform a swizzle.
2714   // If both shuffles use the same mask, and both shuffles have the same first
2715   // or second operand, then it might still be profitable to move the shuffle
2716   // after the xor/and/or operation.
2717   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2718     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2719     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2720
2721     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2722            "Inputs to shuffles are not the same type");
2723
2724     // Check that both shuffles use the same mask. The masks are known to be of
2725     // the same length because the result vector type is the same.
2726     // Check also that shuffles have only one use to avoid introducing extra
2727     // instructions.
2728     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2729         SVN0->getMask().equals(SVN1->getMask())) {
2730       SDValue ShOp = N0->getOperand(1);
2731
2732       // Don't try to fold this node if it requires introducing a
2733       // build vector of all zeros that might be illegal at this stage.
2734       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2735         if (!LegalTypes)
2736           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2737         else
2738           ShOp = SDValue();
2739       }
2740
2741       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2742       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2743       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2744       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2745         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2746                                       N0->getOperand(0), N1->getOperand(0));
2747         AddToWorklist(NewNode.getNode());
2748         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2749                                     &SVN0->getMask()[0]);
2750       }
2751
2752       // Don't try to fold this node if it requires introducing a
2753       // build vector of all zeros that might be illegal at this stage.
2754       ShOp = N0->getOperand(0);
2755       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2756         if (!LegalTypes)
2757           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2758         else
2759           ShOp = SDValue();
2760       }
2761
2762       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2763       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2764       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2765       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2766         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2767                                       N0->getOperand(1), N1->getOperand(1));
2768         AddToWorklist(NewNode.getNode());
2769         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2770                                     &SVN0->getMask()[0]);
2771       }
2772     }
2773   }
2774
2775   return SDValue();
2776 }
2777
2778 /// This contains all DAGCombine rules which reduce two values combined by
2779 /// an And operation to a single value. This makes them reusable in the context
2780 /// of visitSELECT(). Rules involving constants are not included as
2781 /// visitSELECT() already handles those cases.
2782 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2783                                   SDNode *LocReference) {
2784   EVT VT = N1.getValueType();
2785
2786   // fold (and x, undef) -> 0
2787   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2788     return DAG.getConstant(0, SDLoc(LocReference), VT);
2789   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2790   SDValue LL, LR, RL, RR, CC0, CC1;
2791   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2792     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2793     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2794
2795     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2796         LL.getValueType().isInteger()) {
2797       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2798       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2799         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2800                                      LR.getValueType(), LL, RL);
2801         AddToWorklist(ORNode.getNode());
2802         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2803       }
2804       if (isAllOnesConstant(LR)) {
2805         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2806         if (Op1 == ISD::SETEQ) {
2807           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2808                                         LR.getValueType(), LL, RL);
2809           AddToWorklist(ANDNode.getNode());
2810           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2811         }
2812         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2813         if (Op1 == ISD::SETGT) {
2814           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2815                                        LR.getValueType(), LL, RL);
2816           AddToWorklist(ORNode.getNode());
2817           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2818         }
2819       }
2820     }
2821     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2822     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2823         Op0 == Op1 && LL.getValueType().isInteger() &&
2824       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2825                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2826       SDLoc DL(N0);
2827       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2828                                     LL, DAG.getConstant(1, DL,
2829                                                         LL.getValueType()));
2830       AddToWorklist(ADDNode.getNode());
2831       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2832                           DAG.getConstant(2, DL, LL.getValueType()),
2833                           ISD::SETUGE);
2834     }
2835     // canonicalize equivalent to ll == rl
2836     if (LL == RR && LR == RL) {
2837       Op1 = ISD::getSetCCSwappedOperands(Op1);
2838       std::swap(RL, RR);
2839     }
2840     if (LL == RL && LR == RR) {
2841       bool isInteger = LL.getValueType().isInteger();
2842       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2843       if (Result != ISD::SETCC_INVALID &&
2844           (!LegalOperations ||
2845            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2846             TLI.isOperationLegal(ISD::SETCC,
2847                             getSetCCResultType(N0.getSimpleValueType())))))
2848         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2849                             LL, LR, Result);
2850     }
2851   }
2852
2853   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2854       VT.getSizeInBits() <= 64) {
2855     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2856       APInt ADDC = ADDI->getAPIntValue();
2857       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2858         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2859         // immediate for an add, but it is legal if its top c2 bits are set,
2860         // transform the ADD so the immediate doesn't need to be materialized
2861         // in a register.
2862         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2863           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2864                                              SRLI->getZExtValue());
2865           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2866             ADDC |= Mask;
2867             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2868               SDLoc DL(N0);
2869               SDValue NewAdd =
2870                 DAG.getNode(ISD::ADD, DL, VT,
2871                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2872               CombineTo(N0.getNode(), NewAdd);
2873               // Return N so it doesn't get rechecked!
2874               return SDValue(LocReference, 0);
2875             }
2876           }
2877         }
2878       }
2879     }
2880   }
2881
2882   return SDValue();
2883 }
2884
2885 SDValue DAGCombiner::visitAND(SDNode *N) {
2886   SDValue N0 = N->getOperand(0);
2887   SDValue N1 = N->getOperand(1);
2888   EVT VT = N1.getValueType();
2889
2890   // fold vector ops
2891   if (VT.isVector()) {
2892     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2893       return FoldedVOp;
2894
2895     // fold (and x, 0) -> 0, vector edition
2896     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2897       // do not return N0, because undef node may exist in N0
2898       return DAG.getConstant(
2899           APInt::getNullValue(
2900               N0.getValueType().getScalarType().getSizeInBits()),
2901           SDLoc(N), N0.getValueType());
2902     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2903       // do not return N1, because undef node may exist in N1
2904       return DAG.getConstant(
2905           APInt::getNullValue(
2906               N1.getValueType().getScalarType().getSizeInBits()),
2907           SDLoc(N), N1.getValueType());
2908
2909     // fold (and x, -1) -> x, vector edition
2910     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2911       return N1;
2912     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2913       return N0;
2914   }
2915
2916   // fold (and c1, c2) -> c1&c2
2917   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2918   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2919   if (N0C && N1C && !N1C->isOpaque())
2920     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2921   // canonicalize constant to RHS
2922   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2923      !isConstantIntBuildVectorOrConstantInt(N1))
2924     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2925   // fold (and x, -1) -> x
2926   if (isAllOnesConstant(N1))
2927     return N0;
2928   // if (and x, c) is known to be zero, return 0
2929   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2930   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2931                                    APInt::getAllOnesValue(BitWidth)))
2932     return DAG.getConstant(0, SDLoc(N), VT);
2933   // reassociate and
2934   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2935     return RAND;
2936   // fold (and (or x, C), D) -> D if (C & D) == D
2937   if (N1C && N0.getOpcode() == ISD::OR)
2938     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2939       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2940         return N1;
2941   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2942   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2943     SDValue N0Op0 = N0.getOperand(0);
2944     APInt Mask = ~N1C->getAPIntValue();
2945     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2946     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2947       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2948                                  N0.getValueType(), N0Op0);
2949
2950       // Replace uses of the AND with uses of the Zero extend node.
2951       CombineTo(N, Zext);
2952
2953       // We actually want to replace all uses of the any_extend with the
2954       // zero_extend, to avoid duplicating things.  This will later cause this
2955       // AND to be folded.
2956       CombineTo(N0.getNode(), Zext);
2957       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2958     }
2959   }
2960   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2961   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2962   // already be zero by virtue of the width of the base type of the load.
2963   //
2964   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2965   // more cases.
2966   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2967        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2968       N0.getOpcode() == ISD::LOAD) {
2969     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2970                                          N0 : N0.getOperand(0) );
2971
2972     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2973     // This can be a pure constant or a vector splat, in which case we treat the
2974     // vector as a scalar and use the splat value.
2975     APInt Constant = APInt::getNullValue(1);
2976     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2977       Constant = C->getAPIntValue();
2978     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2979       APInt SplatValue, SplatUndef;
2980       unsigned SplatBitSize;
2981       bool HasAnyUndefs;
2982       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2983                                              SplatBitSize, HasAnyUndefs);
2984       if (IsSplat) {
2985         // Undef bits can contribute to a possible optimisation if set, so
2986         // set them.
2987         SplatValue |= SplatUndef;
2988
2989         // The splat value may be something like "0x00FFFFFF", which means 0 for
2990         // the first vector value and FF for the rest, repeating. We need a mask
2991         // that will apply equally to all members of the vector, so AND all the
2992         // lanes of the constant together.
2993         EVT VT = Vector->getValueType(0);
2994         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2995
2996         // If the splat value has been compressed to a bitlength lower
2997         // than the size of the vector lane, we need to re-expand it to
2998         // the lane size.
2999         if (BitWidth > SplatBitSize)
3000           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3001                SplatBitSize < BitWidth;
3002                SplatBitSize = SplatBitSize * 2)
3003             SplatValue |= SplatValue.shl(SplatBitSize);
3004
3005         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3006         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3007         if (SplatBitSize % BitWidth == 0) {
3008           Constant = APInt::getAllOnesValue(BitWidth);
3009           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3010             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3011         }
3012       }
3013     }
3014
3015     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3016     // actually legal and isn't going to get expanded, else this is a false
3017     // optimisation.
3018     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3019                                                     Load->getValueType(0),
3020                                                     Load->getMemoryVT());
3021
3022     // Resize the constant to the same size as the original memory access before
3023     // extension. If it is still the AllOnesValue then this AND is completely
3024     // unneeded.
3025     Constant =
3026       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3027
3028     bool B;
3029     switch (Load->getExtensionType()) {
3030     default: B = false; break;
3031     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3032     case ISD::ZEXTLOAD:
3033     case ISD::NON_EXTLOAD: B = true; break;
3034     }
3035
3036     if (B && Constant.isAllOnesValue()) {
3037       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3038       // preserve semantics once we get rid of the AND.
3039       SDValue NewLoad(Load, 0);
3040       if (Load->getExtensionType() == ISD::EXTLOAD) {
3041         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3042                               Load->getValueType(0), SDLoc(Load),
3043                               Load->getChain(), Load->getBasePtr(),
3044                               Load->getOffset(), Load->getMemoryVT(),
3045                               Load->getMemOperand());
3046         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3047         if (Load->getNumValues() == 3) {
3048           // PRE/POST_INC loads have 3 values.
3049           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3050                            NewLoad.getValue(2) };
3051           CombineTo(Load, To, 3, true);
3052         } else {
3053           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3054         }
3055       }
3056
3057       // Fold the AND away, taking care not to fold to the old load node if we
3058       // replaced it.
3059       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3060
3061       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3062     }
3063   }
3064
3065   // fold (and (load x), 255) -> (zextload x, i8)
3066   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3067   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3068   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3069               (N0.getOpcode() == ISD::ANY_EXTEND &&
3070                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3071     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3072     LoadSDNode *LN0 = HasAnyExt
3073       ? cast<LoadSDNode>(N0.getOperand(0))
3074       : cast<LoadSDNode>(N0);
3075     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3076         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3077       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3078       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3079         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3080         EVT LoadedVT = LN0->getMemoryVT();
3081         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3082
3083         if (ExtVT == LoadedVT &&
3084             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3085                                                     ExtVT))) {
3086
3087           SDValue NewLoad =
3088             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3089                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3090                            LN0->getMemOperand());
3091           AddToWorklist(N);
3092           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3093           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3094         }
3095
3096         // Do not change the width of a volatile load.
3097         // Do not generate loads of non-round integer types since these can
3098         // be expensive (and would be wrong if the type is not byte sized).
3099         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3100             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3101                                                     ExtVT))) {
3102           EVT PtrType = LN0->getOperand(1).getValueType();
3103
3104           unsigned Alignment = LN0->getAlignment();
3105           SDValue NewPtr = LN0->getBasePtr();
3106
3107           // For big endian targets, we need to add an offset to the pointer
3108           // to load the correct bytes.  For little endian systems, we merely
3109           // need to read fewer bytes from the same pointer.
3110           if (DAG.getDataLayout().isBigEndian()) {
3111             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3112             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3113             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3114             SDLoc DL(LN0);
3115             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3116                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3117             Alignment = MinAlign(Alignment, PtrOff);
3118           }
3119
3120           AddToWorklist(NewPtr.getNode());
3121
3122           SDValue Load =
3123             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3124                            LN0->getChain(), NewPtr,
3125                            LN0->getPointerInfo(),
3126                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3127                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3128           AddToWorklist(N);
3129           CombineTo(LN0, Load, Load.getValue(1));
3130           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3131         }
3132       }
3133     }
3134   }
3135
3136   if (SDValue Combined = visitANDLike(N0, N1, N))
3137     return Combined;
3138
3139   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3140   if (N0.getOpcode() == N1.getOpcode())
3141     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3142       return Tmp;
3143
3144   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3145   // fold (and (sra)) -> (and (srl)) when possible.
3146   if (!VT.isVector() &&
3147       SimplifyDemandedBits(SDValue(N, 0)))
3148     return SDValue(N, 0);
3149
3150   // fold (zext_inreg (extload x)) -> (zextload x)
3151   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3152     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3153     EVT MemVT = LN0->getMemoryVT();
3154     // If we zero all the possible extended bits, then we can turn this into
3155     // a zextload if we are running before legalize or the operation is legal.
3156     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3157     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3158                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3159         ((!LegalOperations && !LN0->isVolatile()) ||
3160          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3161       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3162                                        LN0->getChain(), LN0->getBasePtr(),
3163                                        MemVT, LN0->getMemOperand());
3164       AddToWorklist(N);
3165       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3166       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3167     }
3168   }
3169   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3170   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3171       N0.hasOneUse()) {
3172     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3173     EVT MemVT = LN0->getMemoryVT();
3174     // If we zero all the possible extended bits, then we can turn this into
3175     // a zextload if we are running before legalize or the operation is legal.
3176     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3177     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3178                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3179         ((!LegalOperations && !LN0->isVolatile()) ||
3180          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3181       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3182                                        LN0->getChain(), LN0->getBasePtr(),
3183                                        MemVT, LN0->getMemOperand());
3184       AddToWorklist(N);
3185       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3186       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3187     }
3188   }
3189   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3190   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3191     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3192                                        N0.getOperand(1), false);
3193     if (BSwap.getNode())
3194       return BSwap;
3195   }
3196
3197   return SDValue();
3198 }
3199
3200 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3201 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3202                                         bool DemandHighBits) {
3203   if (!LegalOperations)
3204     return SDValue();
3205
3206   EVT VT = N->getValueType(0);
3207   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3208     return SDValue();
3209   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3210     return SDValue();
3211
3212   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3213   bool LookPassAnd0 = false;
3214   bool LookPassAnd1 = false;
3215   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3216       std::swap(N0, N1);
3217   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3218       std::swap(N0, N1);
3219   if (N0.getOpcode() == ISD::AND) {
3220     if (!N0.getNode()->hasOneUse())
3221       return SDValue();
3222     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3223     if (!N01C || N01C->getZExtValue() != 0xFF00)
3224       return SDValue();
3225     N0 = N0.getOperand(0);
3226     LookPassAnd0 = true;
3227   }
3228
3229   if (N1.getOpcode() == ISD::AND) {
3230     if (!N1.getNode()->hasOneUse())
3231       return SDValue();
3232     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3233     if (!N11C || N11C->getZExtValue() != 0xFF)
3234       return SDValue();
3235     N1 = N1.getOperand(0);
3236     LookPassAnd1 = true;
3237   }
3238
3239   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3240     std::swap(N0, N1);
3241   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3242     return SDValue();
3243   if (!N0.getNode()->hasOneUse() ||
3244       !N1.getNode()->hasOneUse())
3245     return SDValue();
3246
3247   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3248   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3249   if (!N01C || !N11C)
3250     return SDValue();
3251   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3252     return SDValue();
3253
3254   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3255   SDValue N00 = N0->getOperand(0);
3256   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3257     if (!N00.getNode()->hasOneUse())
3258       return SDValue();
3259     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3260     if (!N001C || N001C->getZExtValue() != 0xFF)
3261       return SDValue();
3262     N00 = N00.getOperand(0);
3263     LookPassAnd0 = true;
3264   }
3265
3266   SDValue N10 = N1->getOperand(0);
3267   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3268     if (!N10.getNode()->hasOneUse())
3269       return SDValue();
3270     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3271     if (!N101C || N101C->getZExtValue() != 0xFF00)
3272       return SDValue();
3273     N10 = N10.getOperand(0);
3274     LookPassAnd1 = true;
3275   }
3276
3277   if (N00 != N10)
3278     return SDValue();
3279
3280   // Make sure everything beyond the low halfword gets set to zero since the SRL
3281   // 16 will clear the top bits.
3282   unsigned OpSizeInBits = VT.getSizeInBits();
3283   if (DemandHighBits && OpSizeInBits > 16) {
3284     // If the left-shift isn't masked out then the only way this is a bswap is
3285     // if all bits beyond the low 8 are 0. In that case the entire pattern
3286     // reduces to a left shift anyway: leave it for other parts of the combiner.
3287     if (!LookPassAnd0)
3288       return SDValue();
3289
3290     // However, if the right shift isn't masked out then it might be because
3291     // it's not needed. See if we can spot that too.
3292     if (!LookPassAnd1 &&
3293         !DAG.MaskedValueIsZero(
3294             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3295       return SDValue();
3296   }
3297
3298   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3299   if (OpSizeInBits > 16) {
3300     SDLoc DL(N);
3301     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3302                       DAG.getConstant(OpSizeInBits - 16, DL,
3303                                       getShiftAmountTy(VT)));
3304   }
3305   return Res;
3306 }
3307
3308 /// Return true if the specified node is an element that makes up a 32-bit
3309 /// packed halfword byteswap.
3310 /// ((x & 0x000000ff) << 8) |
3311 /// ((x & 0x0000ff00) >> 8) |
3312 /// ((x & 0x00ff0000) << 8) |
3313 /// ((x & 0xff000000) >> 8)
3314 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3315   if (!N.getNode()->hasOneUse())
3316     return false;
3317
3318   unsigned Opc = N.getOpcode();
3319   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3320     return false;
3321
3322   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3323   if (!N1C)
3324     return false;
3325
3326   unsigned Num;
3327   switch (N1C->getZExtValue()) {
3328   default:
3329     return false;
3330   case 0xFF:       Num = 0; break;
3331   case 0xFF00:     Num = 1; break;
3332   case 0xFF0000:   Num = 2; break;
3333   case 0xFF000000: Num = 3; break;
3334   }
3335
3336   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3337   SDValue N0 = N.getOperand(0);
3338   if (Opc == ISD::AND) {
3339     if (Num == 0 || Num == 2) {
3340       // (x >> 8) & 0xff
3341       // (x >> 8) & 0xff0000
3342       if (N0.getOpcode() != ISD::SRL)
3343         return false;
3344       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3345       if (!C || C->getZExtValue() != 8)
3346         return false;
3347     } else {
3348       // (x << 8) & 0xff00
3349       // (x << 8) & 0xff000000
3350       if (N0.getOpcode() != ISD::SHL)
3351         return false;
3352       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3353       if (!C || C->getZExtValue() != 8)
3354         return false;
3355     }
3356   } else if (Opc == ISD::SHL) {
3357     // (x & 0xff) << 8
3358     // (x & 0xff0000) << 8
3359     if (Num != 0 && Num != 2)
3360       return false;
3361     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3362     if (!C || C->getZExtValue() != 8)
3363       return false;
3364   } else { // Opc == ISD::SRL
3365     // (x & 0xff00) >> 8
3366     // (x & 0xff000000) >> 8
3367     if (Num != 1 && Num != 3)
3368       return false;
3369     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3370     if (!C || C->getZExtValue() != 8)
3371       return false;
3372   }
3373
3374   if (Parts[Num])
3375     return false;
3376
3377   Parts[Num] = N0.getOperand(0).getNode();
3378   return true;
3379 }
3380
3381 /// Match a 32-bit packed halfword bswap. That is
3382 /// ((x & 0x000000ff) << 8) |
3383 /// ((x & 0x0000ff00) >> 8) |
3384 /// ((x & 0x00ff0000) << 8) |
3385 /// ((x & 0xff000000) >> 8)
3386 /// => (rotl (bswap x), 16)
3387 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3388   if (!LegalOperations)
3389     return SDValue();
3390
3391   EVT VT = N->getValueType(0);
3392   if (VT != MVT::i32)
3393     return SDValue();
3394   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3395     return SDValue();
3396
3397   // Look for either
3398   // (or (or (and), (and)), (or (and), (and)))
3399   // (or (or (or (and), (and)), (and)), (and))
3400   if (N0.getOpcode() != ISD::OR)
3401     return SDValue();
3402   SDValue N00 = N0.getOperand(0);
3403   SDValue N01 = N0.getOperand(1);
3404   SDNode *Parts[4] = {};
3405
3406   if (N1.getOpcode() == ISD::OR &&
3407       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3408     // (or (or (and), (and)), (or (and), (and)))
3409     SDValue N000 = N00.getOperand(0);
3410     if (!isBSwapHWordElement(N000, Parts))
3411       return SDValue();
3412
3413     SDValue N001 = N00.getOperand(1);
3414     if (!isBSwapHWordElement(N001, Parts))
3415       return SDValue();
3416     SDValue N010 = N01.getOperand(0);
3417     if (!isBSwapHWordElement(N010, Parts))
3418       return SDValue();
3419     SDValue N011 = N01.getOperand(1);
3420     if (!isBSwapHWordElement(N011, Parts))
3421       return SDValue();
3422   } else {
3423     // (or (or (or (and), (and)), (and)), (and))
3424     if (!isBSwapHWordElement(N1, Parts))
3425       return SDValue();
3426     if (!isBSwapHWordElement(N01, Parts))
3427       return SDValue();
3428     if (N00.getOpcode() != ISD::OR)
3429       return SDValue();
3430     SDValue N000 = N00.getOperand(0);
3431     if (!isBSwapHWordElement(N000, Parts))
3432       return SDValue();
3433     SDValue N001 = N00.getOperand(1);
3434     if (!isBSwapHWordElement(N001, Parts))
3435       return SDValue();
3436   }
3437
3438   // Make sure the parts are all coming from the same node.
3439   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3440     return SDValue();
3441
3442   SDLoc DL(N);
3443   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3444                               SDValue(Parts[0], 0));
3445
3446   // Result of the bswap should be rotated by 16. If it's not legal, then
3447   // do  (x << 16) | (x >> 16).
3448   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3449   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3450     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3451   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3452     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3453   return DAG.getNode(ISD::OR, DL, VT,
3454                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3455                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3456 }
3457
3458 /// This contains all DAGCombine rules which reduce two values combined by
3459 /// an Or operation to a single value \see visitANDLike().
3460 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3461   EVT VT = N1.getValueType();
3462   // fold (or x, undef) -> -1
3463   if (!LegalOperations &&
3464       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3465     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3466     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3467                            SDLoc(LocReference), VT);
3468   }
3469   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3470   SDValue LL, LR, RL, RR, CC0, CC1;
3471   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3472     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3473     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3474
3475     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3476       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3477       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3478       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3479         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3480                                      LR.getValueType(), LL, RL);
3481         AddToWorklist(ORNode.getNode());
3482         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3483       }
3484       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3485       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3486       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3487         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3488                                       LR.getValueType(), LL, RL);
3489         AddToWorklist(ANDNode.getNode());
3490         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3491       }
3492     }
3493     // canonicalize equivalent to ll == rl
3494     if (LL == RR && LR == RL) {
3495       Op1 = ISD::getSetCCSwappedOperands(Op1);
3496       std::swap(RL, RR);
3497     }
3498     if (LL == RL && LR == RR) {
3499       bool isInteger = LL.getValueType().isInteger();
3500       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3501       if (Result != ISD::SETCC_INVALID &&
3502           (!LegalOperations ||
3503            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3504             TLI.isOperationLegal(ISD::SETCC,
3505               getSetCCResultType(N0.getValueType())))))
3506         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3507                             LL, LR, Result);
3508     }
3509   }
3510
3511   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3512   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3513       // Don't increase # computations.
3514       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3515     // We can only do this xform if we know that bits from X that are set in C2
3516     // but not in C1 are already zero.  Likewise for Y.
3517     if (const ConstantSDNode *N0O1C =
3518         getAsNonOpaqueConstant(N0.getOperand(1))) {
3519       if (const ConstantSDNode *N1O1C =
3520           getAsNonOpaqueConstant(N1.getOperand(1))) {
3521         // We can only do this xform if we know that bits from X that are set in
3522         // C2 but not in C1 are already zero.  Likewise for Y.
3523         const APInt &LHSMask = N0O1C->getAPIntValue();
3524         const APInt &RHSMask = N1O1C->getAPIntValue();
3525
3526         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3527             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3528           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3529                                   N0.getOperand(0), N1.getOperand(0));
3530           SDLoc DL(LocReference);
3531           return DAG.getNode(ISD::AND, DL, VT, X,
3532                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3533         }
3534       }
3535     }
3536   }
3537
3538   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3539   if (N0.getOpcode() == ISD::AND &&
3540       N1.getOpcode() == ISD::AND &&
3541       N0.getOperand(0) == N1.getOperand(0) &&
3542       // Don't increase # computations.
3543       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3544     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3545                             N0.getOperand(1), N1.getOperand(1));
3546     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3547   }
3548
3549   return SDValue();
3550 }
3551
3552 SDValue DAGCombiner::visitOR(SDNode *N) {
3553   SDValue N0 = N->getOperand(0);
3554   SDValue N1 = N->getOperand(1);
3555   EVT VT = N1.getValueType();
3556
3557   // fold vector ops
3558   if (VT.isVector()) {
3559     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3560       return FoldedVOp;
3561
3562     // fold (or x, 0) -> x, vector edition
3563     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3564       return N1;
3565     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3566       return N0;
3567
3568     // fold (or x, -1) -> -1, vector edition
3569     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3570       // do not return N0, because undef node may exist in N0
3571       return DAG.getConstant(
3572           APInt::getAllOnesValue(
3573               N0.getValueType().getScalarType().getSizeInBits()),
3574           SDLoc(N), N0.getValueType());
3575     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3576       // do not return N1, because undef node may exist in N1
3577       return DAG.getConstant(
3578           APInt::getAllOnesValue(
3579               N1.getValueType().getScalarType().getSizeInBits()),
3580           SDLoc(N), N1.getValueType());
3581
3582     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3583     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3584     // Do this only if the resulting shuffle is legal.
3585     if (isa<ShuffleVectorSDNode>(N0) &&
3586         isa<ShuffleVectorSDNode>(N1) &&
3587         // Avoid folding a node with illegal type.
3588         TLI.isTypeLegal(VT) &&
3589         N0->getOperand(1) == N1->getOperand(1) &&
3590         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3591       bool CanFold = true;
3592       unsigned NumElts = VT.getVectorNumElements();
3593       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3594       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3595       // We construct two shuffle masks:
3596       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3597       // and N1 as the second operand.
3598       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3599       // and N0 as the second operand.
3600       // We do this because OR is commutable and therefore there might be
3601       // two ways to fold this node into a shuffle.
3602       SmallVector<int,4> Mask1;
3603       SmallVector<int,4> Mask2;
3604
3605       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3606         int M0 = SV0->getMaskElt(i);
3607         int M1 = SV1->getMaskElt(i);
3608
3609         // Both shuffle indexes are undef. Propagate Undef.
3610         if (M0 < 0 && M1 < 0) {
3611           Mask1.push_back(M0);
3612           Mask2.push_back(M0);
3613           continue;
3614         }
3615
3616         if (M0 < 0 || M1 < 0 ||
3617             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3618             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3619           CanFold = false;
3620           break;
3621         }
3622
3623         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3624         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3625       }
3626
3627       if (CanFold) {
3628         // Fold this sequence only if the resulting shuffle is 'legal'.
3629         if (TLI.isShuffleMaskLegal(Mask1, VT))
3630           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3631                                       N1->getOperand(0), &Mask1[0]);
3632         if (TLI.isShuffleMaskLegal(Mask2, VT))
3633           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3634                                       N0->getOperand(0), &Mask2[0]);
3635       }
3636     }
3637   }
3638
3639   // fold (or c1, c2) -> c1|c2
3640   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3642   if (N0C && N1C && !N1C->isOpaque())
3643     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3644   // canonicalize constant to RHS
3645   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3646      !isConstantIntBuildVectorOrConstantInt(N1))
3647     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3648   // fold (or x, 0) -> x
3649   if (isNullConstant(N1))
3650     return N0;
3651   // fold (or x, -1) -> -1
3652   if (isAllOnesConstant(N1))
3653     return N1;
3654   // fold (or x, c) -> c iff (x & ~c) == 0
3655   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3656     return N1;
3657
3658   if (SDValue Combined = visitORLike(N0, N1, N))
3659     return Combined;
3660
3661   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3662   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3663     return BSwap;
3664   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3665     return BSwap;
3666
3667   // reassociate or
3668   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3669     return ROR;
3670   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3671   // iff (c1 & c2) == 0.
3672   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3673              isa<ConstantSDNode>(N0.getOperand(1))) {
3674     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3675     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3676       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3677                                                    N1C, C1))
3678         return DAG.getNode(
3679             ISD::AND, SDLoc(N), VT,
3680             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3681       return SDValue();
3682     }
3683   }
3684   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3685   if (N0.getOpcode() == N1.getOpcode())
3686     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3687       return Tmp;
3688
3689   // See if this is some rotate idiom.
3690   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3691     return SDValue(Rot, 0);
3692
3693   // Simplify the operands using demanded-bits information.
3694   if (!VT.isVector() &&
3695       SimplifyDemandedBits(SDValue(N, 0)))
3696     return SDValue(N, 0);
3697
3698   return SDValue();
3699 }
3700
3701 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3702 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3703   if (Op.getOpcode() == ISD::AND) {
3704     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3705       Mask = Op.getOperand(1);
3706       Op = Op.getOperand(0);
3707     } else {
3708       return false;
3709     }
3710   }
3711
3712   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3713     Shift = Op;
3714     return true;
3715   }
3716
3717   return false;
3718 }
3719
3720 // Return true if we can prove that, whenever Neg and Pos are both in the
3721 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3722 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3723 //
3724 //     (or (shift1 X, Neg), (shift2 X, Pos))
3725 //
3726 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3727 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3728 // to consider shift amounts with defined behavior.
3729 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3730   // If OpSize is a power of 2 then:
3731   //
3732   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3733   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3734   //
3735   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3736   // for the stronger condition:
3737   //
3738   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3739   //
3740   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3741   // we can just replace Neg with Neg' for the rest of the function.
3742   //
3743   // In other cases we check for the even stronger condition:
3744   //
3745   //     Neg == OpSize - Pos                                    [B]
3746   //
3747   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3748   // behavior if Pos == 0 (and consequently Neg == OpSize).
3749   //
3750   // We could actually use [A] whenever OpSize is a power of 2, but the
3751   // only extra cases that it would match are those uninteresting ones
3752   // where Neg and Pos are never in range at the same time.  E.g. for
3753   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3754   // as well as (sub 32, Pos), but:
3755   //
3756   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3757   //
3758   // always invokes undefined behavior for 32-bit X.
3759   //
3760   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3761   unsigned MaskLoBits = 0;
3762   if (Neg.getOpcode() == ISD::AND &&
3763       isPowerOf2_64(OpSize) &&
3764       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3765       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3766     Neg = Neg.getOperand(0);
3767     MaskLoBits = Log2_64(OpSize);
3768   }
3769
3770   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3771   if (Neg.getOpcode() != ISD::SUB)
3772     return 0;
3773   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3774   if (!NegC)
3775     return 0;
3776   SDValue NegOp1 = Neg.getOperand(1);
3777
3778   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3779   // Pos'.  The truncation is redundant for the purpose of the equality.
3780   if (MaskLoBits &&
3781       Pos.getOpcode() == ISD::AND &&
3782       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3783       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3784     Pos = Pos.getOperand(0);
3785
3786   // The condition we need is now:
3787   //
3788   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3789   //
3790   // If NegOp1 == Pos then we need:
3791   //
3792   //              OpSize & Mask == NegC & Mask
3793   //
3794   // (because "x & Mask" is a truncation and distributes through subtraction).
3795   APInt Width;
3796   if (Pos == NegOp1)
3797     Width = NegC->getAPIntValue();
3798   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3799   // Then the condition we want to prove becomes:
3800   //
3801   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3802   //
3803   // which, again because "x & Mask" is a truncation, becomes:
3804   //
3805   //                NegC & Mask == (OpSize - PosC) & Mask
3806   //              OpSize & Mask == (NegC + PosC) & Mask
3807   else if (Pos.getOpcode() == ISD::ADD &&
3808            Pos.getOperand(0) == NegOp1 &&
3809            Pos.getOperand(1).getOpcode() == ISD::Constant)
3810     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3811              NegC->getAPIntValue());
3812   else
3813     return false;
3814
3815   // Now we just need to check that OpSize & Mask == Width & Mask.
3816   if (MaskLoBits)
3817     // Opsize & Mask is 0 since Mask is Opsize - 1.
3818     return Width.getLoBits(MaskLoBits) == 0;
3819   return Width == OpSize;
3820 }
3821
3822 // A subroutine of MatchRotate used once we have found an OR of two opposite
3823 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3824 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3825 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3826 // Neg with outer conversions stripped away.
3827 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3828                                        SDValue Neg, SDValue InnerPos,
3829                                        SDValue InnerNeg, unsigned PosOpcode,
3830                                        unsigned NegOpcode, SDLoc DL) {
3831   // fold (or (shl x, (*ext y)),
3832   //          (srl x, (*ext (sub 32, y)))) ->
3833   //   (rotl x, y) or (rotr x, (sub 32, y))
3834   //
3835   // fold (or (shl x, (*ext (sub 32, y))),
3836   //          (srl x, (*ext y))) ->
3837   //   (rotr x, y) or (rotl x, (sub 32, y))
3838   EVT VT = Shifted.getValueType();
3839   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3840     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3841     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3842                        HasPos ? Pos : Neg).getNode();
3843   }
3844
3845   return nullptr;
3846 }
3847
3848 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3849 // idioms for rotate, and if the target supports rotation instructions, generate
3850 // a rot[lr].
3851 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3852   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3853   EVT VT = LHS.getValueType();
3854   if (!TLI.isTypeLegal(VT)) return nullptr;
3855
3856   // The target must have at least one rotate flavor.
3857   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3858   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3859   if (!HasROTL && !HasROTR) return nullptr;
3860
3861   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3862   SDValue LHSShift;   // The shift.
3863   SDValue LHSMask;    // AND value if any.
3864   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3865     return nullptr; // Not part of a rotate.
3866
3867   SDValue RHSShift;   // The shift.
3868   SDValue RHSMask;    // AND value if any.
3869   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3870     return nullptr; // Not part of a rotate.
3871
3872   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3873     return nullptr;   // Not shifting the same value.
3874
3875   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3876     return nullptr;   // Shifts must disagree.
3877
3878   // Canonicalize shl to left side in a shl/srl pair.
3879   if (RHSShift.getOpcode() == ISD::SHL) {
3880     std::swap(LHS, RHS);
3881     std::swap(LHSShift, RHSShift);
3882     std::swap(LHSMask , RHSMask );
3883   }
3884
3885   unsigned OpSizeInBits = VT.getSizeInBits();
3886   SDValue LHSShiftArg = LHSShift.getOperand(0);
3887   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3888   SDValue RHSShiftArg = RHSShift.getOperand(0);
3889   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3890
3891   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3892   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3893   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3894       RHSShiftAmt.getOpcode() == ISD::Constant) {
3895     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3896     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3897     if ((LShVal + RShVal) != OpSizeInBits)
3898       return nullptr;
3899
3900     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3901                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3902
3903     // If there is an AND of either shifted operand, apply it to the result.
3904     if (LHSMask.getNode() || RHSMask.getNode()) {
3905       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3906
3907       if (LHSMask.getNode()) {
3908         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3909         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3910       }
3911       if (RHSMask.getNode()) {
3912         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3913         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3914       }
3915
3916       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3917     }
3918
3919     return Rot.getNode();
3920   }
3921
3922   // If there is a mask here, and we have a variable shift, we can't be sure
3923   // that we're masking out the right stuff.
3924   if (LHSMask.getNode() || RHSMask.getNode())
3925     return nullptr;
3926
3927   // If the shift amount is sign/zext/any-extended just peel it off.
3928   SDValue LExtOp0 = LHSShiftAmt;
3929   SDValue RExtOp0 = RHSShiftAmt;
3930   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3931        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3932        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3933        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3934       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3935        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3936        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3937        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3938     LExtOp0 = LHSShiftAmt.getOperand(0);
3939     RExtOp0 = RHSShiftAmt.getOperand(0);
3940   }
3941
3942   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3943                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3944   if (TryL)
3945     return TryL;
3946
3947   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3948                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3949   if (TryR)
3950     return TryR;
3951
3952   return nullptr;
3953 }
3954
3955 SDValue DAGCombiner::visitXOR(SDNode *N) {
3956   SDValue N0 = N->getOperand(0);
3957   SDValue N1 = N->getOperand(1);
3958   EVT VT = N0.getValueType();
3959
3960   // fold vector ops
3961   if (VT.isVector()) {
3962     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3963       return FoldedVOp;
3964
3965     // fold (xor x, 0) -> x, vector edition
3966     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3967       return N1;
3968     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3969       return N0;
3970   }
3971
3972   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3973   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3974     return DAG.getConstant(0, SDLoc(N), VT);
3975   // fold (xor x, undef) -> undef
3976   if (N0.getOpcode() == ISD::UNDEF)
3977     return N0;
3978   if (N1.getOpcode() == ISD::UNDEF)
3979     return N1;
3980   // fold (xor c1, c2) -> c1^c2
3981   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3982   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3983   if (N0C && N1C)
3984     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3985   // canonicalize constant to RHS
3986   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3987      !isConstantIntBuildVectorOrConstantInt(N1))
3988     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3989   // fold (xor x, 0) -> x
3990   if (isNullConstant(N1))
3991     return N0;
3992   // reassociate xor
3993   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3994     return RXOR;
3995
3996   // fold !(x cc y) -> (x !cc y)
3997   SDValue LHS, RHS, CC;
3998   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3999     bool isInt = LHS.getValueType().isInteger();
4000     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4001                                                isInt);
4002
4003     if (!LegalOperations ||
4004         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4005       switch (N0.getOpcode()) {
4006       default:
4007         llvm_unreachable("Unhandled SetCC Equivalent!");
4008       case ISD::SETCC:
4009         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4010       case ISD::SELECT_CC:
4011         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4012                                N0.getOperand(3), NotCC);
4013       }
4014     }
4015   }
4016
4017   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4018   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4019       N0.getNode()->hasOneUse() &&
4020       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4021     SDValue V = N0.getOperand(0);
4022     SDLoc DL(N0);
4023     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4024                     DAG.getConstant(1, DL, V.getValueType()));
4025     AddToWorklist(V.getNode());
4026     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4027   }
4028
4029   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4030   if (isOneConstant(N1) && VT == MVT::i1 &&
4031       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4032     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4033     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4034       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4035       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4036       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4037       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4038       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4039     }
4040   }
4041   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4042   if (isAllOnesConstant(N1) &&
4043       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4044     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4045     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4046       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4047       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4048       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4049       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4050       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4051     }
4052   }
4053   // fold (xor (and x, y), y) -> (and (not x), y)
4054   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4055       N0->getOperand(1) == N1) {
4056     SDValue X = N0->getOperand(0);
4057     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4058     AddToWorklist(NotX.getNode());
4059     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4060   }
4061   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4062   if (N1C && N0.getOpcode() == ISD::XOR) {
4063     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4064       SDLoc DL(N);
4065       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4066                          DAG.getConstant(N1C->getAPIntValue() ^
4067                                          N00C->getAPIntValue(), DL, VT));
4068     }
4069     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4070       SDLoc DL(N);
4071       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4072                          DAG.getConstant(N1C->getAPIntValue() ^
4073                                          N01C->getAPIntValue(), DL, VT));
4074     }
4075   }
4076   // fold (xor x, x) -> 0
4077   if (N0 == N1)
4078     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4079
4080   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4081   // Here is a concrete example of this equivalence:
4082   // i16   x ==  14
4083   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4084   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4085   //
4086   // =>
4087   //
4088   // i16     ~1      == 0b1111111111111110
4089   // i16 rol(~1, 14) == 0b1011111111111111
4090   //
4091   // Some additional tips to help conceptualize this transform:
4092   // - Try to see the operation as placing a single zero in a value of all ones.
4093   // - There exists no value for x which would allow the result to contain zero.
4094   // - Values of x larger than the bitwidth are undefined and do not require a
4095   //   consistent result.
4096   // - Pushing the zero left requires shifting one bits in from the right.
4097   // A rotate left of ~1 is a nice way of achieving the desired result.
4098   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4099       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4100     SDLoc DL(N);
4101     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4102                        N0.getOperand(1));
4103   }
4104
4105   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4106   if (N0.getOpcode() == N1.getOpcode())
4107     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4108       return Tmp;
4109
4110   // Simplify the expression using non-local knowledge.
4111   if (!VT.isVector() &&
4112       SimplifyDemandedBits(SDValue(N, 0)))
4113     return SDValue(N, 0);
4114
4115   return SDValue();
4116 }
4117
4118 /// Handle transforms common to the three shifts, when the shift amount is a
4119 /// constant.
4120 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4121   SDNode *LHS = N->getOperand(0).getNode();
4122   if (!LHS->hasOneUse()) return SDValue();
4123
4124   // We want to pull some binops through shifts, so that we have (and (shift))
4125   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4126   // thing happens with address calculations, so it's important to canonicalize
4127   // it.
4128   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4129
4130   switch (LHS->getOpcode()) {
4131   default: return SDValue();
4132   case ISD::OR:
4133   case ISD::XOR:
4134     HighBitSet = false; // We can only transform sra if the high bit is clear.
4135     break;
4136   case ISD::AND:
4137     HighBitSet = true;  // We can only transform sra if the high bit is set.
4138     break;
4139   case ISD::ADD:
4140     if (N->getOpcode() != ISD::SHL)
4141       return SDValue(); // only shl(add) not sr[al](add).
4142     HighBitSet = false; // We can only transform sra if the high bit is clear.
4143     break;
4144   }
4145
4146   // We require the RHS of the binop to be a constant and not opaque as well.
4147   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4148   if (!BinOpCst) return SDValue();
4149
4150   // FIXME: disable this unless the input to the binop is a shift by a constant.
4151   // If it is not a shift, it pessimizes some common cases like:
4152   //
4153   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4154   //    int bar(int *X, int i) { return X[i & 255]; }
4155   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4156   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4157        BinOpLHSVal->getOpcode() != ISD::SRA &&
4158        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4159       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4160     return SDValue();
4161
4162   EVT VT = N->getValueType(0);
4163
4164   // If this is a signed shift right, and the high bit is modified by the
4165   // logical operation, do not perform the transformation. The highBitSet
4166   // boolean indicates the value of the high bit of the constant which would
4167   // cause it to be modified for this operation.
4168   if (N->getOpcode() == ISD::SRA) {
4169     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4170     if (BinOpRHSSignSet != HighBitSet)
4171       return SDValue();
4172   }
4173
4174   if (!TLI.isDesirableToCommuteWithShift(LHS))
4175     return SDValue();
4176
4177   // Fold the constants, shifting the binop RHS by the shift amount.
4178   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4179                                N->getValueType(0),
4180                                LHS->getOperand(1), N->getOperand(1));
4181   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4182
4183   // Create the new shift.
4184   SDValue NewShift = DAG.getNode(N->getOpcode(),
4185                                  SDLoc(LHS->getOperand(0)),
4186                                  VT, LHS->getOperand(0), N->getOperand(1));
4187
4188   // Create the new binop.
4189   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4190 }
4191
4192 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4193   assert(N->getOpcode() == ISD::TRUNCATE);
4194   assert(N->getOperand(0).getOpcode() == ISD::AND);
4195
4196   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4197   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4198     SDValue N01 = N->getOperand(0).getOperand(1);
4199
4200     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4201       if (!N01C->isOpaque()) {
4202         EVT TruncVT = N->getValueType(0);
4203         SDValue N00 = N->getOperand(0).getOperand(0);
4204         APInt TruncC = N01C->getAPIntValue();
4205         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4206         SDLoc DL(N);
4207
4208         return DAG.getNode(ISD::AND, DL, TruncVT,
4209                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4210                            DAG.getConstant(TruncC, DL, TruncVT));
4211       }
4212     }
4213   }
4214
4215   return SDValue();
4216 }
4217
4218 SDValue DAGCombiner::visitRotate(SDNode *N) {
4219   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4220   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4221       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4222     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4223     if (NewOp1.getNode())
4224       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4225                          N->getOperand(0), NewOp1);
4226   }
4227   return SDValue();
4228 }
4229
4230 SDValue DAGCombiner::visitSHL(SDNode *N) {
4231   SDValue N0 = N->getOperand(0);
4232   SDValue N1 = N->getOperand(1);
4233   EVT VT = N0.getValueType();
4234   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4235
4236   // fold vector ops
4237   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4238   if (VT.isVector()) {
4239     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4240       return FoldedVOp;
4241
4242     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4243     // If setcc produces all-one true value then:
4244     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4245     if (N1CV && N1CV->isConstant()) {
4246       if (N0.getOpcode() == ISD::AND) {
4247         SDValue N00 = N0->getOperand(0);
4248         SDValue N01 = N0->getOperand(1);
4249         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4250
4251         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4252             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4253                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4254           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4255                                                      N01CV, N1CV))
4256             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4257         }
4258       } else {
4259         N1C = isConstOrConstSplat(N1);
4260       }
4261     }
4262   }
4263
4264   // fold (shl c1, c2) -> c1<<c2
4265   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4266   if (N0C && N1C && !N1C->isOpaque())
4267     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4268   // fold (shl 0, x) -> 0
4269   if (isNullConstant(N0))
4270     return N0;
4271   // fold (shl x, c >= size(x)) -> undef
4272   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4273     return DAG.getUNDEF(VT);
4274   // fold (shl x, 0) -> x
4275   if (N1C && N1C->isNullValue())
4276     return N0;
4277   // fold (shl undef, x) -> 0
4278   if (N0.getOpcode() == ISD::UNDEF)
4279     return DAG.getConstant(0, SDLoc(N), VT);
4280   // if (shl x, c) is known to be zero, return 0
4281   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4282                             APInt::getAllOnesValue(OpSizeInBits)))
4283     return DAG.getConstant(0, SDLoc(N), VT);
4284   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4285   if (N1.getOpcode() == ISD::TRUNCATE &&
4286       N1.getOperand(0).getOpcode() == ISD::AND) {
4287     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4288     if (NewOp1.getNode())
4289       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4290   }
4291
4292   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4293     return SDValue(N, 0);
4294
4295   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4296   if (N1C && N0.getOpcode() == ISD::SHL) {
4297     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4298       uint64_t c1 = N0C1->getZExtValue();
4299       uint64_t c2 = N1C->getZExtValue();
4300       SDLoc DL(N);
4301       if (c1 + c2 >= OpSizeInBits)
4302         return DAG.getConstant(0, DL, VT);
4303       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4304                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4305     }
4306   }
4307
4308   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4309   // For this to be valid, the second form must not preserve any of the bits
4310   // that are shifted out by the inner shift in the first form.  This means
4311   // the outer shift size must be >= the number of bits added by the ext.
4312   // As a corollary, we don't care what kind of ext it is.
4313   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4314               N0.getOpcode() == ISD::ANY_EXTEND ||
4315               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4316       N0.getOperand(0).getOpcode() == ISD::SHL) {
4317     SDValue N0Op0 = N0.getOperand(0);
4318     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4319       uint64_t c1 = N0Op0C1->getZExtValue();
4320       uint64_t c2 = N1C->getZExtValue();
4321       EVT InnerShiftVT = N0Op0.getValueType();
4322       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4323       if (c2 >= OpSizeInBits - InnerShiftSize) {
4324         SDLoc DL(N0);
4325         if (c1 + c2 >= OpSizeInBits)
4326           return DAG.getConstant(0, DL, VT);
4327         return DAG.getNode(ISD::SHL, DL, VT,
4328                            DAG.getNode(N0.getOpcode(), DL, VT,
4329                                        N0Op0->getOperand(0)),
4330                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4331       }
4332     }
4333   }
4334
4335   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4336   // Only fold this if the inner zext has no other uses to avoid increasing
4337   // the total number of instructions.
4338   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4339       N0.getOperand(0).getOpcode() == ISD::SRL) {
4340     SDValue N0Op0 = N0.getOperand(0);
4341     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4342       uint64_t c1 = N0Op0C1->getZExtValue();
4343       if (c1 < VT.getScalarSizeInBits()) {
4344         uint64_t c2 = N1C->getZExtValue();
4345         if (c1 == c2) {
4346           SDValue NewOp0 = N0.getOperand(0);
4347           EVT CountVT = NewOp0.getOperand(1).getValueType();
4348           SDLoc DL(N);
4349           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4350                                        NewOp0,
4351                                        DAG.getConstant(c2, DL, CountVT));
4352           AddToWorklist(NewSHL.getNode());
4353           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4354         }
4355       }
4356     }
4357   }
4358
4359   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4360   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4361   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4362       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4363     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4364       uint64_t C1 = N0C1->getZExtValue();
4365       uint64_t C2 = N1C->getZExtValue();
4366       SDLoc DL(N);
4367       if (C1 <= C2)
4368         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4369                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4370       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4371                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4372     }
4373   }
4374
4375   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4376   //                               (and (srl x, (sub c1, c2), MASK)
4377   // Only fold this if the inner shift has no other uses -- if it does, folding
4378   // this will increase the total number of instructions.
4379   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4380     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4381       uint64_t c1 = N0C1->getZExtValue();
4382       if (c1 < OpSizeInBits) {
4383         uint64_t c2 = N1C->getZExtValue();
4384         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4385         SDValue Shift;
4386         if (c2 > c1) {
4387           Mask = Mask.shl(c2 - c1);
4388           SDLoc DL(N);
4389           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4390                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4391         } else {
4392           Mask = Mask.lshr(c1 - c2);
4393           SDLoc DL(N);
4394           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4395                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4396         }
4397         SDLoc DL(N0);
4398         return DAG.getNode(ISD::AND, DL, VT, Shift,
4399                            DAG.getConstant(Mask, DL, VT));
4400       }
4401     }
4402   }
4403   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4404   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4405     unsigned BitSize = VT.getScalarSizeInBits();
4406     SDLoc DL(N);
4407     SDValue HiBitsMask =
4408       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4409                                             BitSize - N1C->getZExtValue()),
4410                       DL, VT);
4411     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4412                        HiBitsMask);
4413   }
4414
4415   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4416   // Variant of version done on multiply, except mul by a power of 2 is turned
4417   // into a shift.
4418   APInt Val;
4419   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4420       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4421        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4422     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4423     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4424     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4425   }
4426
4427   if (N1C && !N1C->isOpaque())
4428     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4429       return NewSHL;
4430
4431   return SDValue();
4432 }
4433
4434 SDValue DAGCombiner::visitSRA(SDNode *N) {
4435   SDValue N0 = N->getOperand(0);
4436   SDValue N1 = N->getOperand(1);
4437   EVT VT = N0.getValueType();
4438   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4439
4440   // fold vector ops
4441   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4442   if (VT.isVector()) {
4443     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4444       return FoldedVOp;
4445
4446     N1C = isConstOrConstSplat(N1);
4447   }
4448
4449   // fold (sra c1, c2) -> (sra c1, c2)
4450   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4451   if (N0C && N1C && !N1C->isOpaque())
4452     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4453   // fold (sra 0, x) -> 0
4454   if (isNullConstant(N0))
4455     return N0;
4456   // fold (sra -1, x) -> -1
4457   if (isAllOnesConstant(N0))
4458     return N0;
4459   // fold (sra x, (setge c, size(x))) -> undef
4460   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4461     return DAG.getUNDEF(VT);
4462   // fold (sra x, 0) -> x
4463   if (N1C && N1C->isNullValue())
4464     return N0;
4465   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4466   // sext_inreg.
4467   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4468     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4469     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4470     if (VT.isVector())
4471       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4472                                ExtVT, VT.getVectorNumElements());
4473     if ((!LegalOperations ||
4474          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4475       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4476                          N0.getOperand(0), DAG.getValueType(ExtVT));
4477   }
4478
4479   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4480   if (N1C && N0.getOpcode() == ISD::SRA) {
4481     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4482       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4483       if (Sum >= OpSizeInBits)
4484         Sum = OpSizeInBits - 1;
4485       SDLoc DL(N);
4486       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4487                          DAG.getConstant(Sum, DL, N1.getValueType()));
4488     }
4489   }
4490
4491   // fold (sra (shl X, m), (sub result_size, n))
4492   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4493   // result_size - n != m.
4494   // If truncate is free for the target sext(shl) is likely to result in better
4495   // code.
4496   if (N0.getOpcode() == ISD::SHL && N1C) {
4497     // Get the two constanst of the shifts, CN0 = m, CN = n.
4498     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4499     if (N01C) {
4500       LLVMContext &Ctx = *DAG.getContext();
4501       // Determine what the truncate's result bitsize and type would be.
4502       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4503
4504       if (VT.isVector())
4505         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4506
4507       // Determine the residual right-shift amount.
4508       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4509
4510       // If the shift is not a no-op (in which case this should be just a sign
4511       // extend already), the truncated to type is legal, sign_extend is legal
4512       // on that type, and the truncate to that type is both legal and free,
4513       // perform the transform.
4514       if ((ShiftAmt > 0) &&
4515           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4516           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4517           TLI.isTruncateFree(VT, TruncVT)) {
4518
4519         SDLoc DL(N);
4520         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4521             getShiftAmountTy(N0.getOperand(0).getValueType()));
4522         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4523                                     N0.getOperand(0), Amt);
4524         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4525                                     Shift);
4526         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4527                            N->getValueType(0), Trunc);
4528       }
4529     }
4530   }
4531
4532   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4533   if (N1.getOpcode() == ISD::TRUNCATE &&
4534       N1.getOperand(0).getOpcode() == ISD::AND) {
4535     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4536     if (NewOp1.getNode())
4537       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4538   }
4539
4540   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4541   //      if c1 is equal to the number of bits the trunc removes
4542   if (N0.getOpcode() == ISD::TRUNCATE &&
4543       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4544        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4545       N0.getOperand(0).hasOneUse() &&
4546       N0.getOperand(0).getOperand(1).hasOneUse() &&
4547       N1C) {
4548     SDValue N0Op0 = N0.getOperand(0);
4549     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4550       unsigned LargeShiftVal = LargeShift->getZExtValue();
4551       EVT LargeVT = N0Op0.getValueType();
4552
4553       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4554         SDLoc DL(N);
4555         SDValue Amt =
4556           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4557                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4558         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4559                                   N0Op0.getOperand(0), Amt);
4560         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4561       }
4562     }
4563   }
4564
4565   // Simplify, based on bits shifted out of the LHS.
4566   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4567     return SDValue(N, 0);
4568
4569
4570   // If the sign bit is known to be zero, switch this to a SRL.
4571   if (DAG.SignBitIsZero(N0))
4572     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4573
4574   if (N1C && !N1C->isOpaque())
4575     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4576       return NewSRA;
4577
4578   return SDValue();
4579 }
4580
4581 SDValue DAGCombiner::visitSRL(SDNode *N) {
4582   SDValue N0 = N->getOperand(0);
4583   SDValue N1 = N->getOperand(1);
4584   EVT VT = N0.getValueType();
4585   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4586
4587   // fold vector ops
4588   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4589   if (VT.isVector()) {
4590     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4591       return FoldedVOp;
4592
4593     N1C = isConstOrConstSplat(N1);
4594   }
4595
4596   // fold (srl c1, c2) -> c1 >>u c2
4597   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4598   if (N0C && N1C && !N1C->isOpaque())
4599     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4600   // fold (srl 0, x) -> 0
4601   if (isNullConstant(N0))
4602     return N0;
4603   // fold (srl x, c >= size(x)) -> undef
4604   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4605     return DAG.getUNDEF(VT);
4606   // fold (srl x, 0) -> x
4607   if (N1C && N1C->isNullValue())
4608     return N0;
4609   // if (srl x, c) is known to be zero, return 0
4610   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4611                                    APInt::getAllOnesValue(OpSizeInBits)))
4612     return DAG.getConstant(0, SDLoc(N), VT);
4613
4614   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4615   if (N1C && N0.getOpcode() == ISD::SRL) {
4616     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4617       uint64_t c1 = N01C->getZExtValue();
4618       uint64_t c2 = N1C->getZExtValue();
4619       SDLoc DL(N);
4620       if (c1 + c2 >= OpSizeInBits)
4621         return DAG.getConstant(0, DL, VT);
4622       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4623                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4624     }
4625   }
4626
4627   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4628   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4629       N0.getOperand(0).getOpcode() == ISD::SRL &&
4630       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4631     uint64_t c1 =
4632       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4633     uint64_t c2 = N1C->getZExtValue();
4634     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4635     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4636     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4637     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4638     if (c1 + OpSizeInBits == InnerShiftSize) {
4639       SDLoc DL(N0);
4640       if (c1 + c2 >= InnerShiftSize)
4641         return DAG.getConstant(0, DL, VT);
4642       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4643                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4644                                      N0.getOperand(0)->getOperand(0),
4645                                      DAG.getConstant(c1 + c2, DL,
4646                                                      ShiftCountVT)));
4647     }
4648   }
4649
4650   // fold (srl (shl x, c), c) -> (and x, cst2)
4651   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4652     unsigned BitSize = N0.getScalarValueSizeInBits();
4653     if (BitSize <= 64) {
4654       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4655       SDLoc DL(N);
4656       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4657                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4658     }
4659   }
4660
4661   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4662   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4663     // Shifting in all undef bits?
4664     EVT SmallVT = N0.getOperand(0).getValueType();
4665     unsigned BitSize = SmallVT.getScalarSizeInBits();
4666     if (N1C->getZExtValue() >= BitSize)
4667       return DAG.getUNDEF(VT);
4668
4669     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4670       uint64_t ShiftAmt = N1C->getZExtValue();
4671       SDLoc DL0(N0);
4672       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4673                                        N0.getOperand(0),
4674                           DAG.getConstant(ShiftAmt, DL0,
4675                                           getShiftAmountTy(SmallVT)));
4676       AddToWorklist(SmallShift.getNode());
4677       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4678       SDLoc DL(N);
4679       return DAG.getNode(ISD::AND, DL, VT,
4680                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4681                          DAG.getConstant(Mask, DL, VT));
4682     }
4683   }
4684
4685   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4686   // bit, which is unmodified by sra.
4687   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4688     if (N0.getOpcode() == ISD::SRA)
4689       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4690   }
4691
4692   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4693   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4694       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4695     APInt KnownZero, KnownOne;
4696     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4697
4698     // If any of the input bits are KnownOne, then the input couldn't be all
4699     // zeros, thus the result of the srl will always be zero.
4700     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4701
4702     // If all of the bits input the to ctlz node are known to be zero, then
4703     // the result of the ctlz is "32" and the result of the shift is one.
4704     APInt UnknownBits = ~KnownZero;
4705     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4706
4707     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4708     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4709       // Okay, we know that only that the single bit specified by UnknownBits
4710       // could be set on input to the CTLZ node. If this bit is set, the SRL
4711       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4712       // to an SRL/XOR pair, which is likely to simplify more.
4713       unsigned ShAmt = UnknownBits.countTrailingZeros();
4714       SDValue Op = N0.getOperand(0);
4715
4716       if (ShAmt) {
4717         SDLoc DL(N0);
4718         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4719                   DAG.getConstant(ShAmt, DL,
4720                                   getShiftAmountTy(Op.getValueType())));
4721         AddToWorklist(Op.getNode());
4722       }
4723
4724       SDLoc DL(N);
4725       return DAG.getNode(ISD::XOR, DL, VT,
4726                          Op, DAG.getConstant(1, DL, VT));
4727     }
4728   }
4729
4730   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4731   if (N1.getOpcode() == ISD::TRUNCATE &&
4732       N1.getOperand(0).getOpcode() == ISD::AND) {
4733     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4734       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4735   }
4736
4737   // fold operands of srl based on knowledge that the low bits are not
4738   // demanded.
4739   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4740     return SDValue(N, 0);
4741
4742   if (N1C && !N1C->isOpaque())
4743     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4744       return NewSRL;
4745
4746   // Attempt to convert a srl of a load into a narrower zero-extending load.
4747   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4748     return NarrowLoad;
4749
4750   // Here is a common situation. We want to optimize:
4751   //
4752   //   %a = ...
4753   //   %b = and i32 %a, 2
4754   //   %c = srl i32 %b, 1
4755   //   brcond i32 %c ...
4756   //
4757   // into
4758   //
4759   //   %a = ...
4760   //   %b = and %a, 2
4761   //   %c = setcc eq %b, 0
4762   //   brcond %c ...
4763   //
4764   // However when after the source operand of SRL is optimized into AND, the SRL
4765   // itself may not be optimized further. Look for it and add the BRCOND into
4766   // the worklist.
4767   if (N->hasOneUse()) {
4768     SDNode *Use = *N->use_begin();
4769     if (Use->getOpcode() == ISD::BRCOND)
4770       AddToWorklist(Use);
4771     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4772       // Also look pass the truncate.
4773       Use = *Use->use_begin();
4774       if (Use->getOpcode() == ISD::BRCOND)
4775         AddToWorklist(Use);
4776     }
4777   }
4778
4779   return SDValue();
4780 }
4781
4782 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4783   SDValue N0 = N->getOperand(0);
4784   EVT VT = N->getValueType(0);
4785
4786   // fold (bswap c1) -> c2
4787   if (isConstantIntBuildVectorOrConstantInt(N0))
4788     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4789   // fold (bswap (bswap x)) -> x
4790   if (N0.getOpcode() == ISD::BSWAP)
4791     return N0->getOperand(0);
4792   return SDValue();
4793 }
4794
4795 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4796   SDValue N0 = N->getOperand(0);
4797   EVT VT = N->getValueType(0);
4798
4799   // fold (ctlz c1) -> c2
4800   if (isConstantIntBuildVectorOrConstantInt(N0))
4801     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4802   return SDValue();
4803 }
4804
4805 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4806   SDValue N0 = N->getOperand(0);
4807   EVT VT = N->getValueType(0);
4808
4809   // fold (ctlz_zero_undef c1) -> c2
4810   if (isConstantIntBuildVectorOrConstantInt(N0))
4811     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4812   return SDValue();
4813 }
4814
4815 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4816   SDValue N0 = N->getOperand(0);
4817   EVT VT = N->getValueType(0);
4818
4819   // fold (cttz c1) -> c2
4820   if (isConstantIntBuildVectorOrConstantInt(N0))
4821     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4822   return SDValue();
4823 }
4824
4825 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4826   SDValue N0 = N->getOperand(0);
4827   EVT VT = N->getValueType(0);
4828
4829   // fold (cttz_zero_undef c1) -> c2
4830   if (isConstantIntBuildVectorOrConstantInt(N0))
4831     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4832   return SDValue();
4833 }
4834
4835 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4836   SDValue N0 = N->getOperand(0);
4837   EVT VT = N->getValueType(0);
4838
4839   // fold (ctpop c1) -> c2
4840   if (isConstantIntBuildVectorOrConstantInt(N0))
4841     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4842   return SDValue();
4843 }
4844
4845
4846 /// \brief Generate Min/Max node
4847 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4848                                    SDValue True, SDValue False,
4849                                    ISD::CondCode CC, const TargetLowering &TLI,
4850                                    SelectionDAG &DAG) {
4851   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4852     return SDValue();
4853
4854   switch (CC) {
4855   case ISD::SETOLT:
4856   case ISD::SETOLE:
4857   case ISD::SETLT:
4858   case ISD::SETLE:
4859   case ISD::SETULT:
4860   case ISD::SETULE: {
4861     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4862     if (TLI.isOperationLegal(Opcode, VT))
4863       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4864     return SDValue();
4865   }
4866   case ISD::SETOGT:
4867   case ISD::SETOGE:
4868   case ISD::SETGT:
4869   case ISD::SETGE:
4870   case ISD::SETUGT:
4871   case ISD::SETUGE: {
4872     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4873     if (TLI.isOperationLegal(Opcode, VT))
4874       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4875     return SDValue();
4876   }
4877   default:
4878     return SDValue();
4879   }
4880 }
4881
4882 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4883   SDValue N0 = N->getOperand(0);
4884   SDValue N1 = N->getOperand(1);
4885   SDValue N2 = N->getOperand(2);
4886   EVT VT = N->getValueType(0);
4887   EVT VT0 = N0.getValueType();
4888
4889   // fold (select C, X, X) -> X
4890   if (N1 == N2)
4891     return N1;
4892   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4893     // fold (select true, X, Y) -> X
4894     // fold (select false, X, Y) -> Y
4895     return !N0C->isNullValue() ? N1 : N2;
4896   }
4897   // fold (select C, 1, X) -> (or C, X)
4898   if (VT == MVT::i1 && isOneConstant(N1))
4899     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4900   // fold (select C, 0, 1) -> (xor C, 1)
4901   // We can't do this reliably if integer based booleans have different contents
4902   // to floating point based booleans. This is because we can't tell whether we
4903   // have an integer-based boolean or a floating-point-based boolean unless we
4904   // can find the SETCC that produced it and inspect its operands. This is
4905   // fairly easy if C is the SETCC node, but it can potentially be
4906   // undiscoverable (or not reasonably discoverable). For example, it could be
4907   // in another basic block or it could require searching a complicated
4908   // expression.
4909   if (VT.isInteger() &&
4910       (VT0 == MVT::i1 || (VT0.isInteger() &&
4911                           TLI.getBooleanContents(false, false) ==
4912                               TLI.getBooleanContents(false, true) &&
4913                           TLI.getBooleanContents(false, false) ==
4914                               TargetLowering::ZeroOrOneBooleanContent)) &&
4915       isNullConstant(N1) && isOneConstant(N2)) {
4916     SDValue XORNode;
4917     if (VT == VT0) {
4918       SDLoc DL(N);
4919       return DAG.getNode(ISD::XOR, DL, VT0,
4920                          N0, DAG.getConstant(1, DL, VT0));
4921     }
4922     SDLoc DL0(N0);
4923     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4924                           N0, DAG.getConstant(1, DL0, VT0));
4925     AddToWorklist(XORNode.getNode());
4926     if (VT.bitsGT(VT0))
4927       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4928     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4929   }
4930   // fold (select C, 0, X) -> (and (not C), X)
4931   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4932     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4933     AddToWorklist(NOTNode.getNode());
4934     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4935   }
4936   // fold (select C, X, 1) -> (or (not C), X)
4937   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4938     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4939     AddToWorklist(NOTNode.getNode());
4940     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4941   }
4942   // fold (select C, X, 0) -> (and C, X)
4943   if (VT == MVT::i1 && isNullConstant(N2))
4944     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4945   // fold (select X, X, Y) -> (or X, Y)
4946   // fold (select X, 1, Y) -> (or X, Y)
4947   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4948     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4949   // fold (select X, Y, X) -> (and X, Y)
4950   // fold (select X, Y, 0) -> (and X, Y)
4951   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4952     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4953
4954   // If we can fold this based on the true/false value, do so.
4955   if (SimplifySelectOps(N, N1, N2))
4956     return SDValue(N, 0);  // Don't revisit N.
4957
4958   // fold selects based on a setcc into other things, such as min/max/abs
4959   if (N0.getOpcode() == ISD::SETCC) {
4960     // select x, y (fcmp lt x, y) -> fminnum x, y
4961     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4962     //
4963     // This is OK if we don't care about what happens if either operand is a
4964     // NaN.
4965     //
4966
4967     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4968     // no signed zeros as well as no nans.
4969     const TargetOptions &Options = DAG.getTarget().Options;
4970     if (Options.UnsafeFPMath &&
4971         VT.isFloatingPoint() && N0.hasOneUse() &&
4972         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4973       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4974
4975       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
4976                                                 N0.getOperand(1), N1, N2, CC,
4977                                                 TLI, DAG))
4978         return FMinMax;
4979     }
4980
4981     if ((!LegalOperations &&
4982          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4983         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4984       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4985                          N0.getOperand(0), N0.getOperand(1),
4986                          N1, N2, N0.getOperand(2));
4987     return SimplifySelect(SDLoc(N), N0, N1, N2);
4988   }
4989
4990   if (VT0 == MVT::i1) {
4991     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4992       // select (and Cond0, Cond1), X, Y
4993       //   -> select Cond0, (select Cond1, X, Y), Y
4994       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4995         SDValue Cond0 = N0->getOperand(0);
4996         SDValue Cond1 = N0->getOperand(1);
4997         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4998                                           N1.getValueType(), Cond1, N1, N2);
4999         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5000                            InnerSelect, N2);
5001       }
5002       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5003       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5004         SDValue Cond0 = N0->getOperand(0);
5005         SDValue Cond1 = N0->getOperand(1);
5006         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5007                                           N1.getValueType(), Cond1, N1, N2);
5008         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5009                            InnerSelect);
5010       }
5011     }
5012
5013     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5014     if (N1->getOpcode() == ISD::SELECT) {
5015       SDValue N1_0 = N1->getOperand(0);
5016       SDValue N1_1 = N1->getOperand(1);
5017       SDValue N1_2 = N1->getOperand(2);
5018       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5019         // Create the actual and node if we can generate good code for it.
5020         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5021           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5022                                     N0, N1_0);
5023           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5024                              N1_1, N2);
5025         }
5026         // Otherwise see if we can optimize the "and" to a better pattern.
5027         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5028           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5029                              N1_1, N2);
5030       }
5031     }
5032     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5033     if (N2->getOpcode() == ISD::SELECT) {
5034       SDValue N2_0 = N2->getOperand(0);
5035       SDValue N2_1 = N2->getOperand(1);
5036       SDValue N2_2 = N2->getOperand(2);
5037       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5038         // Create the actual or node if we can generate good code for it.
5039         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5040           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5041                                    N0, N2_0);
5042           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5043                              N1, N2_2);
5044         }
5045         // Otherwise see if we can optimize to a better pattern.
5046         if (SDValue Combined = visitORLike(N0, N2_0, N))
5047           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5048                              N1, N2_2);
5049       }
5050     }
5051   }
5052
5053   return SDValue();
5054 }
5055
5056 static
5057 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5058   SDLoc DL(N);
5059   EVT LoVT, HiVT;
5060   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5061
5062   // Split the inputs.
5063   SDValue Lo, Hi, LL, LH, RL, RH;
5064   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5065   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5066
5067   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5068   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5069
5070   return std::make_pair(Lo, Hi);
5071 }
5072
5073 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5074 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5075 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5076   SDLoc dl(N);
5077   SDValue Cond = N->getOperand(0);
5078   SDValue LHS = N->getOperand(1);
5079   SDValue RHS = N->getOperand(2);
5080   EVT VT = N->getValueType(0);
5081   int NumElems = VT.getVectorNumElements();
5082   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5083          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5084          Cond.getOpcode() == ISD::BUILD_VECTOR);
5085
5086   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5087   // binary ones here.
5088   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5089     return SDValue();
5090
5091   // We're sure we have an even number of elements due to the
5092   // concat_vectors we have as arguments to vselect.
5093   // Skip BV elements until we find one that's not an UNDEF
5094   // After we find an UNDEF element, keep looping until we get to half the
5095   // length of the BV and see if all the non-undef nodes are the same.
5096   ConstantSDNode *BottomHalf = nullptr;
5097   for (int i = 0; i < NumElems / 2; ++i) {
5098     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5099       continue;
5100
5101     if (BottomHalf == nullptr)
5102       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5103     else if (Cond->getOperand(i).getNode() != BottomHalf)
5104       return SDValue();
5105   }
5106
5107   // Do the same for the second half of the BuildVector
5108   ConstantSDNode *TopHalf = nullptr;
5109   for (int i = NumElems / 2; i < NumElems; ++i) {
5110     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5111       continue;
5112
5113     if (TopHalf == nullptr)
5114       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5115     else if (Cond->getOperand(i).getNode() != TopHalf)
5116       return SDValue();
5117   }
5118
5119   assert(TopHalf && BottomHalf &&
5120          "One half of the selector was all UNDEFs and the other was all the "
5121          "same value. This should have been addressed before this function.");
5122   return DAG.getNode(
5123       ISD::CONCAT_VECTORS, dl, VT,
5124       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5125       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5126 }
5127
5128 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5129
5130   if (Level >= AfterLegalizeTypes)
5131     return SDValue();
5132
5133   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5134   SDValue Mask = MSC->getMask();
5135   SDValue Data  = MSC->getValue();
5136   SDLoc DL(N);
5137
5138   // If the MSCATTER data type requires splitting and the mask is provided by a
5139   // SETCC, then split both nodes and its operands before legalization. This
5140   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5141   // and enables future optimizations (e.g. min/max pattern matching on X86).
5142   if (Mask.getOpcode() != ISD::SETCC)
5143     return SDValue();
5144
5145   // Check if any splitting is required.
5146   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5147       TargetLowering::TypeSplitVector)
5148     return SDValue();
5149   SDValue MaskLo, MaskHi, Lo, Hi;
5150   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5151
5152   EVT LoVT, HiVT;
5153   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5154
5155   SDValue Chain = MSC->getChain();
5156
5157   EVT MemoryVT = MSC->getMemoryVT();
5158   unsigned Alignment = MSC->getOriginalAlignment();
5159
5160   EVT LoMemVT, HiMemVT;
5161   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5162
5163   SDValue DataLo, DataHi;
5164   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5165
5166   SDValue BasePtr = MSC->getBasePtr();
5167   SDValue IndexLo, IndexHi;
5168   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5169
5170   MachineMemOperand *MMO = DAG.getMachineFunction().
5171     getMachineMemOperand(MSC->getPointerInfo(),
5172                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5173                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5174
5175   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5176   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5177                             DL, OpsLo, MMO);
5178
5179   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5180   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5181                             DL, OpsHi, MMO);
5182
5183   AddToWorklist(Lo.getNode());
5184   AddToWorklist(Hi.getNode());
5185
5186   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5187 }
5188
5189 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5190
5191   if (Level >= AfterLegalizeTypes)
5192     return SDValue();
5193
5194   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5195   SDValue Mask = MST->getMask();
5196   SDValue Data  = MST->getValue();
5197   SDLoc DL(N);
5198
5199   // If the MSTORE data type requires splitting and the mask is provided by a
5200   // SETCC, then split both nodes and its operands before legalization. This
5201   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5202   // and enables future optimizations (e.g. min/max pattern matching on X86).
5203   if (Mask.getOpcode() == ISD::SETCC) {
5204
5205     // Check if any splitting is required.
5206     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5207         TargetLowering::TypeSplitVector)
5208       return SDValue();
5209
5210     SDValue MaskLo, MaskHi, Lo, Hi;
5211     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5212
5213     EVT LoVT, HiVT;
5214     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5215
5216     SDValue Chain = MST->getChain();
5217     SDValue Ptr   = MST->getBasePtr();
5218
5219     EVT MemoryVT = MST->getMemoryVT();
5220     unsigned Alignment = MST->getOriginalAlignment();
5221
5222     // if Alignment is equal to the vector size,
5223     // take the half of it for the second part
5224     unsigned SecondHalfAlignment =
5225       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5226          Alignment/2 : Alignment;
5227
5228     EVT LoMemVT, HiMemVT;
5229     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5230
5231     SDValue DataLo, DataHi;
5232     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5233
5234     MachineMemOperand *MMO = DAG.getMachineFunction().
5235       getMachineMemOperand(MST->getPointerInfo(),
5236                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5237                            Alignment, MST->getAAInfo(), MST->getRanges());
5238
5239     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5240                             MST->isTruncatingStore());
5241
5242     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5243     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5244                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5245
5246     MMO = DAG.getMachineFunction().
5247       getMachineMemOperand(MST->getPointerInfo(),
5248                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5249                            SecondHalfAlignment, MST->getAAInfo(),
5250                            MST->getRanges());
5251
5252     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5253                             MST->isTruncatingStore());
5254
5255     AddToWorklist(Lo.getNode());
5256     AddToWorklist(Hi.getNode());
5257
5258     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5259   }
5260   return SDValue();
5261 }
5262
5263 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5264
5265   if (Level >= AfterLegalizeTypes)
5266     return SDValue();
5267
5268   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5269   SDValue Mask = MGT->getMask();
5270   SDLoc DL(N);
5271
5272   // If the MGATHER result requires splitting and the mask is provided by a
5273   // SETCC, then split both nodes and its operands before legalization. This
5274   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5275   // and enables future optimizations (e.g. min/max pattern matching on X86).
5276
5277   if (Mask.getOpcode() != ISD::SETCC)
5278     return SDValue();
5279
5280   EVT VT = N->getValueType(0);
5281
5282   // Check if any splitting is required.
5283   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5284       TargetLowering::TypeSplitVector)
5285     return SDValue();
5286
5287   SDValue MaskLo, MaskHi, Lo, Hi;
5288   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5289
5290   SDValue Src0 = MGT->getValue();
5291   SDValue Src0Lo, Src0Hi;
5292   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5293
5294   EVT LoVT, HiVT;
5295   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5296
5297   SDValue Chain = MGT->getChain();
5298   EVT MemoryVT = MGT->getMemoryVT();
5299   unsigned Alignment = MGT->getOriginalAlignment();
5300
5301   EVT LoMemVT, HiMemVT;
5302   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5303
5304   SDValue BasePtr = MGT->getBasePtr();
5305   SDValue Index = MGT->getIndex();
5306   SDValue IndexLo, IndexHi;
5307   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5308
5309   MachineMemOperand *MMO = DAG.getMachineFunction().
5310     getMachineMemOperand(MGT->getPointerInfo(),
5311                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5312                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5313
5314   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5315   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5316                             MMO);
5317
5318   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5319   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5320                             MMO);
5321
5322   AddToWorklist(Lo.getNode());
5323   AddToWorklist(Hi.getNode());
5324
5325   // Build a factor node to remember that this load is independent of the
5326   // other one.
5327   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5328                       Hi.getValue(1));
5329
5330   // Legalized the chain result - switch anything that used the old chain to
5331   // use the new one.
5332   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5333
5334   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5335
5336   SDValue RetOps[] = { GatherRes, Chain };
5337   return DAG.getMergeValues(RetOps, DL);
5338 }
5339
5340 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5341
5342   if (Level >= AfterLegalizeTypes)
5343     return SDValue();
5344
5345   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5346   SDValue Mask = MLD->getMask();
5347   SDLoc DL(N);
5348
5349   // If the MLOAD result requires splitting and the mask is provided by a
5350   // SETCC, then split both nodes and its operands before legalization. This
5351   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5352   // and enables future optimizations (e.g. min/max pattern matching on X86).
5353
5354   if (Mask.getOpcode() == ISD::SETCC) {
5355     EVT VT = N->getValueType(0);
5356
5357     // Check if any splitting is required.
5358     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5359         TargetLowering::TypeSplitVector)
5360       return SDValue();
5361
5362     SDValue MaskLo, MaskHi, Lo, Hi;
5363     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5364
5365     SDValue Src0 = MLD->getSrc0();
5366     SDValue Src0Lo, Src0Hi;
5367     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5368
5369     EVT LoVT, HiVT;
5370     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5371
5372     SDValue Chain = MLD->getChain();
5373     SDValue Ptr   = MLD->getBasePtr();
5374     EVT MemoryVT = MLD->getMemoryVT();
5375     unsigned Alignment = MLD->getOriginalAlignment();
5376
5377     // if Alignment is equal to the vector size,
5378     // take the half of it for the second part
5379     unsigned SecondHalfAlignment =
5380       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5381          Alignment/2 : Alignment;
5382
5383     EVT LoMemVT, HiMemVT;
5384     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5385
5386     MachineMemOperand *MMO = DAG.getMachineFunction().
5387     getMachineMemOperand(MLD->getPointerInfo(),
5388                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5389                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5390
5391     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5392                            ISD::NON_EXTLOAD);
5393
5394     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5395     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5396                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5397
5398     MMO = DAG.getMachineFunction().
5399     getMachineMemOperand(MLD->getPointerInfo(),
5400                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5401                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5402
5403     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5404                            ISD::NON_EXTLOAD);
5405
5406     AddToWorklist(Lo.getNode());
5407     AddToWorklist(Hi.getNode());
5408
5409     // Build a factor node to remember that this load is independent of the
5410     // other one.
5411     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5412                         Hi.getValue(1));
5413
5414     // Legalized the chain result - switch anything that used the old chain to
5415     // use the new one.
5416     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5417
5418     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5419
5420     SDValue RetOps[] = { LoadRes, Chain };
5421     return DAG.getMergeValues(RetOps, DL);
5422   }
5423   return SDValue();
5424 }
5425
5426 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5427   SDValue N0 = N->getOperand(0);
5428   SDValue N1 = N->getOperand(1);
5429   SDValue N2 = N->getOperand(2);
5430   SDLoc DL(N);
5431
5432   // Canonicalize integer abs.
5433   // vselect (setg[te] X,  0),  X, -X ->
5434   // vselect (setgt    X, -1),  X, -X ->
5435   // vselect (setl[te] X,  0), -X,  X ->
5436   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5437   if (N0.getOpcode() == ISD::SETCC) {
5438     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5439     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5440     bool isAbs = false;
5441     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5442
5443     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5444          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5445         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5446       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5447     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5448              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5449       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5450
5451     if (isAbs) {
5452       EVT VT = LHS.getValueType();
5453       SDValue Shift = DAG.getNode(
5454           ISD::SRA, DL, VT, LHS,
5455           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5456       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5457       AddToWorklist(Shift.getNode());
5458       AddToWorklist(Add.getNode());
5459       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5460     }
5461   }
5462
5463   if (SimplifySelectOps(N, N1, N2))
5464     return SDValue(N, 0);  // Don't revisit N.
5465
5466   // If the VSELECT result requires splitting and the mask is provided by a
5467   // SETCC, then split both nodes and its operands before legalization. This
5468   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5469   // and enables future optimizations (e.g. min/max pattern matching on X86).
5470   if (N0.getOpcode() == ISD::SETCC) {
5471     EVT VT = N->getValueType(0);
5472
5473     // Check if any splitting is required.
5474     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5475         TargetLowering::TypeSplitVector)
5476       return SDValue();
5477
5478     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5479     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5480     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5481     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5482
5483     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5484     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5485
5486     // Add the new VSELECT nodes to the work list in case they need to be split
5487     // again.
5488     AddToWorklist(Lo.getNode());
5489     AddToWorklist(Hi.getNode());
5490
5491     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5492   }
5493
5494   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5495   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5496     return N1;
5497   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5498   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5499     return N2;
5500
5501   // The ConvertSelectToConcatVector function is assuming both the above
5502   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5503   // and addressed.
5504   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5505       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5506       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5507     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5508       return CV;
5509   }
5510
5511   return SDValue();
5512 }
5513
5514 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5515   SDValue N0 = N->getOperand(0);
5516   SDValue N1 = N->getOperand(1);
5517   SDValue N2 = N->getOperand(2);
5518   SDValue N3 = N->getOperand(3);
5519   SDValue N4 = N->getOperand(4);
5520   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5521
5522   // fold select_cc lhs, rhs, x, x, cc -> x
5523   if (N2 == N3)
5524     return N2;
5525
5526   // Determine if the condition we're dealing with is constant
5527   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5528                               N0, N1, CC, SDLoc(N), false);
5529   if (SCC.getNode()) {
5530     AddToWorklist(SCC.getNode());
5531
5532     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5533       if (!SCCC->isNullValue())
5534         return N2;    // cond always true -> true val
5535       else
5536         return N3;    // cond always false -> false val
5537     } else if (SCC->getOpcode() == ISD::UNDEF) {
5538       // When the condition is UNDEF, just return the first operand. This is
5539       // coherent the DAG creation, no setcc node is created in this case
5540       return N2;
5541     } else if (SCC.getOpcode() == ISD::SETCC) {
5542       // Fold to a simpler select_cc
5543       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5544                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5545                          SCC.getOperand(2));
5546     }
5547   }
5548
5549   // If we can fold this based on the true/false value, do so.
5550   if (SimplifySelectOps(N, N2, N3))
5551     return SDValue(N, 0);  // Don't revisit N.
5552
5553   // fold select_cc into other things, such as min/max/abs
5554   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5555 }
5556
5557 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5558   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5559                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5560                        SDLoc(N));
5561 }
5562
5563 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5564 /// a build_vector of constants.
5565 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5566 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5567 /// Vector extends are not folded if operations are legal; this is to
5568 /// avoid introducing illegal build_vector dag nodes.
5569 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5570                                          SelectionDAG &DAG, bool LegalTypes,
5571                                          bool LegalOperations) {
5572   unsigned Opcode = N->getOpcode();
5573   SDValue N0 = N->getOperand(0);
5574   EVT VT = N->getValueType(0);
5575
5576   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5577          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5578          && "Expected EXTEND dag node in input!");
5579
5580   // fold (sext c1) -> c1
5581   // fold (zext c1) -> c1
5582   // fold (aext c1) -> c1
5583   if (isa<ConstantSDNode>(N0))
5584     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5585
5586   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5587   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5588   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5589   EVT SVT = VT.getScalarType();
5590   if (!(VT.isVector() &&
5591       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5592       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5593     return nullptr;
5594
5595   // We can fold this node into a build_vector.
5596   unsigned VTBits = SVT.getSizeInBits();
5597   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5598   SmallVector<SDValue, 8> Elts;
5599   unsigned NumElts = VT.getVectorNumElements();
5600   SDLoc DL(N);
5601
5602   for (unsigned i=0; i != NumElts; ++i) {
5603     SDValue Op = N0->getOperand(i);
5604     if (Op->getOpcode() == ISD::UNDEF) {
5605       Elts.push_back(DAG.getUNDEF(SVT));
5606       continue;
5607     }
5608
5609     SDLoc DL(Op);
5610     // Get the constant value and if needed trunc it to the size of the type.
5611     // Nodes like build_vector might have constants wider than the scalar type.
5612     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5613     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5614       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5615     else
5616       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5617   }
5618
5619   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5620 }
5621
5622 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5623 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5624 // transformation. Returns true if extension are possible and the above
5625 // mentioned transformation is profitable.
5626 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5627                                     unsigned ExtOpc,
5628                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5629                                     const TargetLowering &TLI) {
5630   bool HasCopyToRegUses = false;
5631   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5632   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5633                             UE = N0.getNode()->use_end();
5634        UI != UE; ++UI) {
5635     SDNode *User = *UI;
5636     if (User == N)
5637       continue;
5638     if (UI.getUse().getResNo() != N0.getResNo())
5639       continue;
5640     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5641     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5642       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5643       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5644         // Sign bits will be lost after a zext.
5645         return false;
5646       bool Add = false;
5647       for (unsigned i = 0; i != 2; ++i) {
5648         SDValue UseOp = User->getOperand(i);
5649         if (UseOp == N0)
5650           continue;
5651         if (!isa<ConstantSDNode>(UseOp))
5652           return false;
5653         Add = true;
5654       }
5655       if (Add)
5656         ExtendNodes.push_back(User);
5657       continue;
5658     }
5659     // If truncates aren't free and there are users we can't
5660     // extend, it isn't worthwhile.
5661     if (!isTruncFree)
5662       return false;
5663     // Remember if this value is live-out.
5664     if (User->getOpcode() == ISD::CopyToReg)
5665       HasCopyToRegUses = true;
5666   }
5667
5668   if (HasCopyToRegUses) {
5669     bool BothLiveOut = false;
5670     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5671          UI != UE; ++UI) {
5672       SDUse &Use = UI.getUse();
5673       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5674         BothLiveOut = true;
5675         break;
5676       }
5677     }
5678     if (BothLiveOut)
5679       // Both unextended and extended values are live out. There had better be
5680       // a good reason for the transformation.
5681       return ExtendNodes.size();
5682   }
5683   return true;
5684 }
5685
5686 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5687                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5688                                   ISD::NodeType ExtType) {
5689   // Extend SetCC uses if necessary.
5690   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5691     SDNode *SetCC = SetCCs[i];
5692     SmallVector<SDValue, 4> Ops;
5693
5694     for (unsigned j = 0; j != 2; ++j) {
5695       SDValue SOp = SetCC->getOperand(j);
5696       if (SOp == Trunc)
5697         Ops.push_back(ExtLoad);
5698       else
5699         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5700     }
5701
5702     Ops.push_back(SetCC->getOperand(2));
5703     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5704   }
5705 }
5706
5707 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5708 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5709   SDValue N0 = N->getOperand(0);
5710   EVT DstVT = N->getValueType(0);
5711   EVT SrcVT = N0.getValueType();
5712
5713   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5714           N->getOpcode() == ISD::ZERO_EXTEND) &&
5715          "Unexpected node type (not an extend)!");
5716
5717   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5718   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5719   //   (v8i32 (sext (v8i16 (load x))))
5720   // into:
5721   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5722   //                          (v4i32 (sextload (x + 16)))))
5723   // Where uses of the original load, i.e.:
5724   //   (v8i16 (load x))
5725   // are replaced with:
5726   //   (v8i16 (truncate
5727   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5728   //                            (v4i32 (sextload (x + 16)))))))
5729   //
5730   // This combine is only applicable to illegal, but splittable, vectors.
5731   // All legal types, and illegal non-vector types, are handled elsewhere.
5732   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5733   //
5734   if (N0->getOpcode() != ISD::LOAD)
5735     return SDValue();
5736
5737   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5738
5739   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5740       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5741       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5742     return SDValue();
5743
5744   SmallVector<SDNode *, 4> SetCCs;
5745   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5746     return SDValue();
5747
5748   ISD::LoadExtType ExtType =
5749       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5750
5751   // Try to split the vector types to get down to legal types.
5752   EVT SplitSrcVT = SrcVT;
5753   EVT SplitDstVT = DstVT;
5754   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5755          SplitSrcVT.getVectorNumElements() > 1) {
5756     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5757     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5758   }
5759
5760   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5761     return SDValue();
5762
5763   SDLoc DL(N);
5764   const unsigned NumSplits =
5765       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5766   const unsigned Stride = SplitSrcVT.getStoreSize();
5767   SmallVector<SDValue, 4> Loads;
5768   SmallVector<SDValue, 4> Chains;
5769
5770   SDValue BasePtr = LN0->getBasePtr();
5771   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5772     const unsigned Offset = Idx * Stride;
5773     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5774
5775     SDValue SplitLoad = DAG.getExtLoad(
5776         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5777         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5778         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5779         Align, LN0->getAAInfo());
5780
5781     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5782                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5783
5784     Loads.push_back(SplitLoad.getValue(0));
5785     Chains.push_back(SplitLoad.getValue(1));
5786   }
5787
5788   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5789   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5790
5791   CombineTo(N, NewValue);
5792
5793   // Replace uses of the original load (before extension)
5794   // with a truncate of the concatenated sextloaded vectors.
5795   SDValue Trunc =
5796       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5797   CombineTo(N0.getNode(), Trunc, NewChain);
5798   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5799                   (ISD::NodeType)N->getOpcode());
5800   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5801 }
5802
5803 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5804   SDValue N0 = N->getOperand(0);
5805   EVT VT = N->getValueType(0);
5806
5807   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5808                                               LegalOperations))
5809     return SDValue(Res, 0);
5810
5811   // fold (sext (sext x)) -> (sext x)
5812   // fold (sext (aext x)) -> (sext x)
5813   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5814     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5815                        N0.getOperand(0));
5816
5817   if (N0.getOpcode() == ISD::TRUNCATE) {
5818     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5819     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5820     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5821       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5822       if (NarrowLoad.getNode() != N0.getNode()) {
5823         CombineTo(N0.getNode(), NarrowLoad);
5824         // CombineTo deleted the truncate, if needed, but not what's under it.
5825         AddToWorklist(oye);
5826       }
5827       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5828     }
5829
5830     // See if the value being truncated is already sign extended.  If so, just
5831     // eliminate the trunc/sext pair.
5832     SDValue Op = N0.getOperand(0);
5833     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5834     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5835     unsigned DestBits = VT.getScalarType().getSizeInBits();
5836     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5837
5838     if (OpBits == DestBits) {
5839       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5840       // bits, it is already ready.
5841       if (NumSignBits > DestBits-MidBits)
5842         return Op;
5843     } else if (OpBits < DestBits) {
5844       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5845       // bits, just sext from i32.
5846       if (NumSignBits > OpBits-MidBits)
5847         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5848     } else {
5849       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5850       // bits, just truncate to i32.
5851       if (NumSignBits > OpBits-MidBits)
5852         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5853     }
5854
5855     // fold (sext (truncate x)) -> (sextinreg x).
5856     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5857                                                  N0.getValueType())) {
5858       if (OpBits < DestBits)
5859         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5860       else if (OpBits > DestBits)
5861         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5862       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5863                          DAG.getValueType(N0.getValueType()));
5864     }
5865   }
5866
5867   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5868   // Only generate vector extloads when 1) they're legal, and 2) they are
5869   // deemed desirable by the target.
5870   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5871       ((!LegalOperations && !VT.isVector() &&
5872         !cast<LoadSDNode>(N0)->isVolatile()) ||
5873        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5874     bool DoXform = true;
5875     SmallVector<SDNode*, 4> SetCCs;
5876     if (!N0.hasOneUse())
5877       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5878     if (VT.isVector())
5879       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5880     if (DoXform) {
5881       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5882       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5883                                        LN0->getChain(),
5884                                        LN0->getBasePtr(), N0.getValueType(),
5885                                        LN0->getMemOperand());
5886       CombineTo(N, ExtLoad);
5887       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5888                                   N0.getValueType(), ExtLoad);
5889       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5890       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5891                       ISD::SIGN_EXTEND);
5892       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5893     }
5894   }
5895
5896   // fold (sext (load x)) to multiple smaller sextloads.
5897   // Only on illegal but splittable vectors.
5898   if (SDValue ExtLoad = CombineExtLoad(N))
5899     return ExtLoad;
5900
5901   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5902   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5903   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5904       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5905     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5906     EVT MemVT = LN0->getMemoryVT();
5907     if ((!LegalOperations && !LN0->isVolatile()) ||
5908         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5909       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5910                                        LN0->getChain(),
5911                                        LN0->getBasePtr(), MemVT,
5912                                        LN0->getMemOperand());
5913       CombineTo(N, ExtLoad);
5914       CombineTo(N0.getNode(),
5915                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5916                             N0.getValueType(), ExtLoad),
5917                 ExtLoad.getValue(1));
5918       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5919     }
5920   }
5921
5922   // fold (sext (and/or/xor (load x), cst)) ->
5923   //      (and/or/xor (sextload x), (sext cst))
5924   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5925        N0.getOpcode() == ISD::XOR) &&
5926       isa<LoadSDNode>(N0.getOperand(0)) &&
5927       N0.getOperand(1).getOpcode() == ISD::Constant &&
5928       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5929       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5930     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5931     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5932       bool DoXform = true;
5933       SmallVector<SDNode*, 4> SetCCs;
5934       if (!N0.hasOneUse())
5935         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5936                                           SetCCs, TLI);
5937       if (DoXform) {
5938         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5939                                          LN0->getChain(), LN0->getBasePtr(),
5940                                          LN0->getMemoryVT(),
5941                                          LN0->getMemOperand());
5942         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5943         Mask = Mask.sext(VT.getSizeInBits());
5944         SDLoc DL(N);
5945         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5946                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5947         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5948                                     SDLoc(N0.getOperand(0)),
5949                                     N0.getOperand(0).getValueType(), ExtLoad);
5950         CombineTo(N, And);
5951         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5952         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5953                         ISD::SIGN_EXTEND);
5954         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5955       }
5956     }
5957   }
5958
5959   if (N0.getOpcode() == ISD::SETCC) {
5960     EVT N0VT = N0.getOperand(0).getValueType();
5961     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5962     // Only do this before legalize for now.
5963     if (VT.isVector() && !LegalOperations &&
5964         TLI.getBooleanContents(N0VT) ==
5965             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5966       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5967       // of the same size as the compared operands. Only optimize sext(setcc())
5968       // if this is the case.
5969       EVT SVT = getSetCCResultType(N0VT);
5970
5971       // We know that the # elements of the results is the same as the
5972       // # elements of the compare (and the # elements of the compare result
5973       // for that matter).  Check to see that they are the same size.  If so,
5974       // we know that the element size of the sext'd result matches the
5975       // element size of the compare operands.
5976       if (VT.getSizeInBits() == SVT.getSizeInBits())
5977         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5978                              N0.getOperand(1),
5979                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5980
5981       // If the desired elements are smaller or larger than the source
5982       // elements we can use a matching integer vector type and then
5983       // truncate/sign extend
5984       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5985       if (SVT == MatchingVectorType) {
5986         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5987                                N0.getOperand(0), N0.getOperand(1),
5988                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5989         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5990       }
5991     }
5992
5993     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5994     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5995     SDLoc DL(N);
5996     SDValue NegOne =
5997       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5998     SDValue SCC =
5999       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6000                        NegOne, DAG.getConstant(0, DL, VT),
6001                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6002     if (SCC.getNode()) return SCC;
6003
6004     if (!VT.isVector()) {
6005       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6006       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6007         SDLoc DL(N);
6008         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6009         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6010                                      N0.getOperand(0), N0.getOperand(1), CC);
6011         return DAG.getSelect(DL, VT, SetCC,
6012                              NegOne, DAG.getConstant(0, DL, VT));
6013       }
6014     }
6015   }
6016
6017   // fold (sext x) -> (zext x) if the sign bit is known zero.
6018   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6019       DAG.SignBitIsZero(N0))
6020     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6021
6022   return SDValue();
6023 }
6024
6025 // isTruncateOf - If N is a truncate of some other value, return true, record
6026 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6027 // This function computes KnownZero to avoid a duplicated call to
6028 // computeKnownBits in the caller.
6029 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6030                          APInt &KnownZero) {
6031   APInt KnownOne;
6032   if (N->getOpcode() == ISD::TRUNCATE) {
6033     Op = N->getOperand(0);
6034     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6035     return true;
6036   }
6037
6038   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6039       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6040     return false;
6041
6042   SDValue Op0 = N->getOperand(0);
6043   SDValue Op1 = N->getOperand(1);
6044   assert(Op0.getValueType() == Op1.getValueType());
6045
6046   if (isNullConstant(Op0))
6047     Op = Op1;
6048   else if (isNullConstant(Op1))
6049     Op = Op0;
6050   else
6051     return false;
6052
6053   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6054
6055   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6056     return false;
6057
6058   return true;
6059 }
6060
6061 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6062   SDValue N0 = N->getOperand(0);
6063   EVT VT = N->getValueType(0);
6064
6065   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6066                                               LegalOperations))
6067     return SDValue(Res, 0);
6068
6069   // fold (zext (zext x)) -> (zext x)
6070   // fold (zext (aext x)) -> (zext x)
6071   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6072     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6073                        N0.getOperand(0));
6074
6075   // fold (zext (truncate x)) -> (zext x) or
6076   //      (zext (truncate x)) -> (truncate x)
6077   // This is valid when the truncated bits of x are already zero.
6078   // FIXME: We should extend this to work for vectors too.
6079   SDValue Op;
6080   APInt KnownZero;
6081   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6082     APInt TruncatedBits =
6083       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6084       APInt(Op.getValueSizeInBits(), 0) :
6085       APInt::getBitsSet(Op.getValueSizeInBits(),
6086                         N0.getValueSizeInBits(),
6087                         std::min(Op.getValueSizeInBits(),
6088                                  VT.getSizeInBits()));
6089     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6090       if (VT.bitsGT(Op.getValueType()))
6091         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6092       if (VT.bitsLT(Op.getValueType()))
6093         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6094
6095       return Op;
6096     }
6097   }
6098
6099   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6100   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6101   if (N0.getOpcode() == ISD::TRUNCATE) {
6102     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6103       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6104       if (NarrowLoad.getNode() != N0.getNode()) {
6105         CombineTo(N0.getNode(), NarrowLoad);
6106         // CombineTo deleted the truncate, if needed, but not what's under it.
6107         AddToWorklist(oye);
6108       }
6109       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6110     }
6111   }
6112
6113   // fold (zext (truncate x)) -> (and x, mask)
6114   if (N0.getOpcode() == ISD::TRUNCATE) {
6115     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6116     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6117     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6118       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6119       if (NarrowLoad.getNode() != N0.getNode()) {
6120         CombineTo(N0.getNode(), NarrowLoad);
6121         // CombineTo deleted the truncate, if needed, but not what's under it.
6122         AddToWorklist(oye);
6123       }
6124       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6125     }
6126
6127     EVT SrcVT = N0.getOperand(0).getValueType();
6128     EVT MinVT = N0.getValueType();
6129
6130     // Try to mask before the extension to avoid having to generate a larger mask,
6131     // possibly over several sub-vectors.
6132     if (SrcVT.bitsLT(VT)) {
6133       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6134                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6135         SDValue Op = N0.getOperand(0);
6136         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6137         AddToWorklist(Op.getNode());
6138         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6139       }
6140     }
6141
6142     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6143       SDValue Op = N0.getOperand(0);
6144       if (SrcVT.bitsLT(VT)) {
6145         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6146         AddToWorklist(Op.getNode());
6147       } else if (SrcVT.bitsGT(VT)) {
6148         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6149         AddToWorklist(Op.getNode());
6150       }
6151       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6152     }
6153   }
6154
6155   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6156   // if either of the casts is not free.
6157   if (N0.getOpcode() == ISD::AND &&
6158       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6159       N0.getOperand(1).getOpcode() == ISD::Constant &&
6160       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6161                            N0.getValueType()) ||
6162        !TLI.isZExtFree(N0.getValueType(), VT))) {
6163     SDValue X = N0.getOperand(0).getOperand(0);
6164     if (X.getValueType().bitsLT(VT)) {
6165       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6166     } else if (X.getValueType().bitsGT(VT)) {
6167       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6168     }
6169     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6170     Mask = Mask.zext(VT.getSizeInBits());
6171     SDLoc DL(N);
6172     return DAG.getNode(ISD::AND, DL, VT,
6173                        X, DAG.getConstant(Mask, DL, VT));
6174   }
6175
6176   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6177   // Only generate vector extloads when 1) they're legal, and 2) they are
6178   // deemed desirable by the target.
6179   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6180       ((!LegalOperations && !VT.isVector() &&
6181         !cast<LoadSDNode>(N0)->isVolatile()) ||
6182        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6183     bool DoXform = true;
6184     SmallVector<SDNode*, 4> SetCCs;
6185     if (!N0.hasOneUse())
6186       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6187     if (VT.isVector())
6188       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6189     if (DoXform) {
6190       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6191       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6192                                        LN0->getChain(),
6193                                        LN0->getBasePtr(), N0.getValueType(),
6194                                        LN0->getMemOperand());
6195       CombineTo(N, ExtLoad);
6196       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6197                                   N0.getValueType(), ExtLoad);
6198       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6199
6200       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6201                       ISD::ZERO_EXTEND);
6202       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6203     }
6204   }
6205
6206   // fold (zext (load x)) to multiple smaller zextloads.
6207   // Only on illegal but splittable vectors.
6208   if (SDValue ExtLoad = CombineExtLoad(N))
6209     return ExtLoad;
6210
6211   // fold (zext (and/or/xor (load x), cst)) ->
6212   //      (and/or/xor (zextload x), (zext cst))
6213   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6214        N0.getOpcode() == ISD::XOR) &&
6215       isa<LoadSDNode>(N0.getOperand(0)) &&
6216       N0.getOperand(1).getOpcode() == ISD::Constant &&
6217       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6218       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6219     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6220     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6221       bool DoXform = true;
6222       SmallVector<SDNode*, 4> SetCCs;
6223       if (!N0.hasOneUse())
6224         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6225                                           SetCCs, TLI);
6226       if (DoXform) {
6227         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6228                                          LN0->getChain(), LN0->getBasePtr(),
6229                                          LN0->getMemoryVT(),
6230                                          LN0->getMemOperand());
6231         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6232         Mask = Mask.zext(VT.getSizeInBits());
6233         SDLoc DL(N);
6234         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6235                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6236         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6237                                     SDLoc(N0.getOperand(0)),
6238                                     N0.getOperand(0).getValueType(), ExtLoad);
6239         CombineTo(N, And);
6240         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6241         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6242                         ISD::ZERO_EXTEND);
6243         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6244       }
6245     }
6246   }
6247
6248   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6249   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6250   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6251       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6252     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6253     EVT MemVT = LN0->getMemoryVT();
6254     if ((!LegalOperations && !LN0->isVolatile()) ||
6255         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6256       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6257                                        LN0->getChain(),
6258                                        LN0->getBasePtr(), MemVT,
6259                                        LN0->getMemOperand());
6260       CombineTo(N, ExtLoad);
6261       CombineTo(N0.getNode(),
6262                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6263                             ExtLoad),
6264                 ExtLoad.getValue(1));
6265       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6266     }
6267   }
6268
6269   if (N0.getOpcode() == ISD::SETCC) {
6270     if (!LegalOperations && VT.isVector() &&
6271         N0.getValueType().getVectorElementType() == MVT::i1) {
6272       EVT N0VT = N0.getOperand(0).getValueType();
6273       if (getSetCCResultType(N0VT) == N0.getValueType())
6274         return SDValue();
6275
6276       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6277       // Only do this before legalize for now.
6278       EVT EltVT = VT.getVectorElementType();
6279       SDLoc DL(N);
6280       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6281                                     DAG.getConstant(1, DL, EltVT));
6282       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6283         // We know that the # elements of the results is the same as the
6284         // # elements of the compare (and the # elements of the compare result
6285         // for that matter).  Check to see that they are the same size.  If so,
6286         // we know that the element size of the sext'd result matches the
6287         // element size of the compare operands.
6288         return DAG.getNode(ISD::AND, DL, VT,
6289                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6290                                          N0.getOperand(1),
6291                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6292                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6293                                        OneOps));
6294
6295       // If the desired elements are smaller or larger than the source
6296       // elements we can use a matching integer vector type and then
6297       // truncate/sign extend
6298       EVT MatchingElementType =
6299         EVT::getIntegerVT(*DAG.getContext(),
6300                           N0VT.getScalarType().getSizeInBits());
6301       EVT MatchingVectorType =
6302         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6303                          N0VT.getVectorNumElements());
6304       SDValue VsetCC =
6305         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6306                       N0.getOperand(1),
6307                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6308       return DAG.getNode(ISD::AND, DL, VT,
6309                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6310                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6311     }
6312
6313     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6314     SDLoc DL(N);
6315     SDValue SCC =
6316       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6317                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6318                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6319     if (SCC.getNode()) return SCC;
6320   }
6321
6322   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6323   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6324       isa<ConstantSDNode>(N0.getOperand(1)) &&
6325       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6326       N0.hasOneUse()) {
6327     SDValue ShAmt = N0.getOperand(1);
6328     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6329     if (N0.getOpcode() == ISD::SHL) {
6330       SDValue InnerZExt = N0.getOperand(0);
6331       // If the original shl may be shifting out bits, do not perform this
6332       // transformation.
6333       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6334         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6335       if (ShAmtVal > KnownZeroBits)
6336         return SDValue();
6337     }
6338
6339     SDLoc DL(N);
6340
6341     // Ensure that the shift amount is wide enough for the shifted value.
6342     if (VT.getSizeInBits() >= 256)
6343       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6344
6345     return DAG.getNode(N0.getOpcode(), DL, VT,
6346                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6347                        ShAmt);
6348   }
6349
6350   return SDValue();
6351 }
6352
6353 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6354   SDValue N0 = N->getOperand(0);
6355   EVT VT = N->getValueType(0);
6356
6357   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6358                                               LegalOperations))
6359     return SDValue(Res, 0);
6360
6361   // fold (aext (aext x)) -> (aext x)
6362   // fold (aext (zext x)) -> (zext x)
6363   // fold (aext (sext x)) -> (sext x)
6364   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6365       N0.getOpcode() == ISD::ZERO_EXTEND ||
6366       N0.getOpcode() == ISD::SIGN_EXTEND)
6367     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6368
6369   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6370   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6371   if (N0.getOpcode() == ISD::TRUNCATE) {
6372     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6373       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6374       if (NarrowLoad.getNode() != N0.getNode()) {
6375         CombineTo(N0.getNode(), NarrowLoad);
6376         // CombineTo deleted the truncate, if needed, but not what's under it.
6377         AddToWorklist(oye);
6378       }
6379       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6380     }
6381   }
6382
6383   // fold (aext (truncate x))
6384   if (N0.getOpcode() == ISD::TRUNCATE) {
6385     SDValue TruncOp = N0.getOperand(0);
6386     if (TruncOp.getValueType() == VT)
6387       return TruncOp; // x iff x size == zext size.
6388     if (TruncOp.getValueType().bitsGT(VT))
6389       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6390     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6391   }
6392
6393   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6394   // if the trunc is not free.
6395   if (N0.getOpcode() == ISD::AND &&
6396       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6397       N0.getOperand(1).getOpcode() == ISD::Constant &&
6398       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6399                           N0.getValueType())) {
6400     SDValue X = N0.getOperand(0).getOperand(0);
6401     if (X.getValueType().bitsLT(VT)) {
6402       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6403     } else if (X.getValueType().bitsGT(VT)) {
6404       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6405     }
6406     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6407     Mask = Mask.zext(VT.getSizeInBits());
6408     SDLoc DL(N);
6409     return DAG.getNode(ISD::AND, DL, VT,
6410                        X, DAG.getConstant(Mask, DL, VT));
6411   }
6412
6413   // fold (aext (load x)) -> (aext (truncate (extload x)))
6414   // None of the supported targets knows how to perform load and any_ext
6415   // on vectors in one instruction.  We only perform this transformation on
6416   // scalars.
6417   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6418       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6419       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6420     bool DoXform = true;
6421     SmallVector<SDNode*, 4> SetCCs;
6422     if (!N0.hasOneUse())
6423       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6424     if (DoXform) {
6425       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6426       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6427                                        LN0->getChain(),
6428                                        LN0->getBasePtr(), N0.getValueType(),
6429                                        LN0->getMemOperand());
6430       CombineTo(N, ExtLoad);
6431       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6432                                   N0.getValueType(), ExtLoad);
6433       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6434       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6435                       ISD::ANY_EXTEND);
6436       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6437     }
6438   }
6439
6440   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6441   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6442   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6443   if (N0.getOpcode() == ISD::LOAD &&
6444       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6445       N0.hasOneUse()) {
6446     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6447     ISD::LoadExtType ExtType = LN0->getExtensionType();
6448     EVT MemVT = LN0->getMemoryVT();
6449     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6450       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6451                                        VT, LN0->getChain(), LN0->getBasePtr(),
6452                                        MemVT, LN0->getMemOperand());
6453       CombineTo(N, ExtLoad);
6454       CombineTo(N0.getNode(),
6455                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6456                             N0.getValueType(), ExtLoad),
6457                 ExtLoad.getValue(1));
6458       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6459     }
6460   }
6461
6462   if (N0.getOpcode() == ISD::SETCC) {
6463     // For vectors:
6464     // aext(setcc) -> vsetcc
6465     // aext(setcc) -> truncate(vsetcc)
6466     // aext(setcc) -> aext(vsetcc)
6467     // Only do this before legalize for now.
6468     if (VT.isVector() && !LegalOperations) {
6469       EVT N0VT = N0.getOperand(0).getValueType();
6470         // We know that the # elements of the results is the same as the
6471         // # elements of the compare (and the # elements of the compare result
6472         // for that matter).  Check to see that they are the same size.  If so,
6473         // we know that the element size of the sext'd result matches the
6474         // element size of the compare operands.
6475       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6476         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6477                              N0.getOperand(1),
6478                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6479       // If the desired elements are smaller or larger than the source
6480       // elements we can use a matching integer vector type and then
6481       // truncate/any extend
6482       else {
6483         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6484         SDValue VsetCC =
6485           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6486                         N0.getOperand(1),
6487                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6488         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6489       }
6490     }
6491
6492     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6493     SDLoc DL(N);
6494     SDValue SCC =
6495       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6496                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6497                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6498     if (SCC.getNode())
6499       return SCC;
6500   }
6501
6502   return SDValue();
6503 }
6504
6505 /// See if the specified operand can be simplified with the knowledge that only
6506 /// the bits specified by Mask are used.  If so, return the simpler operand,
6507 /// otherwise return a null SDValue.
6508 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6509   switch (V.getOpcode()) {
6510   default: break;
6511   case ISD::Constant: {
6512     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6513     assert(CV && "Const value should be ConstSDNode.");
6514     const APInt &CVal = CV->getAPIntValue();
6515     APInt NewVal = CVal & Mask;
6516     if (NewVal != CVal)
6517       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6518     break;
6519   }
6520   case ISD::OR:
6521   case ISD::XOR:
6522     // If the LHS or RHS don't contribute bits to the or, drop them.
6523     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6524       return V.getOperand(1);
6525     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6526       return V.getOperand(0);
6527     break;
6528   case ISD::SRL:
6529     // Only look at single-use SRLs.
6530     if (!V.getNode()->hasOneUse())
6531       break;
6532     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6533       // See if we can recursively simplify the LHS.
6534       unsigned Amt = RHSC->getZExtValue();
6535
6536       // Watch out for shift count overflow though.
6537       if (Amt >= Mask.getBitWidth()) break;
6538       APInt NewMask = Mask << Amt;
6539       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6540         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6541                            SimplifyLHS, V.getOperand(1));
6542     }
6543   }
6544   return SDValue();
6545 }
6546
6547 /// If the result of a wider load is shifted to right of N  bits and then
6548 /// truncated to a narrower type and where N is a multiple of number of bits of
6549 /// the narrower type, transform it to a narrower load from address + N / num of
6550 /// bits of new type. If the result is to be extended, also fold the extension
6551 /// to form a extending load.
6552 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6553   unsigned Opc = N->getOpcode();
6554
6555   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6556   SDValue N0 = N->getOperand(0);
6557   EVT VT = N->getValueType(0);
6558   EVT ExtVT = VT;
6559
6560   // This transformation isn't valid for vector loads.
6561   if (VT.isVector())
6562     return SDValue();
6563
6564   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6565   // extended to VT.
6566   if (Opc == ISD::SIGN_EXTEND_INREG) {
6567     ExtType = ISD::SEXTLOAD;
6568     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6569   } else if (Opc == ISD::SRL) {
6570     // Another special-case: SRL is basically zero-extending a narrower value.
6571     ExtType = ISD::ZEXTLOAD;
6572     N0 = SDValue(N, 0);
6573     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6574     if (!N01) return SDValue();
6575     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6576                               VT.getSizeInBits() - N01->getZExtValue());
6577   }
6578   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6579     return SDValue();
6580
6581   unsigned EVTBits = ExtVT.getSizeInBits();
6582
6583   // Do not generate loads of non-round integer types since these can
6584   // be expensive (and would be wrong if the type is not byte sized).
6585   if (!ExtVT.isRound())
6586     return SDValue();
6587
6588   unsigned ShAmt = 0;
6589   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6590     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6591       ShAmt = N01->getZExtValue();
6592       // Is the shift amount a multiple of size of VT?
6593       if ((ShAmt & (EVTBits-1)) == 0) {
6594         N0 = N0.getOperand(0);
6595         // Is the load width a multiple of size of VT?
6596         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6597           return SDValue();
6598       }
6599
6600       // At this point, we must have a load or else we can't do the transform.
6601       if (!isa<LoadSDNode>(N0)) return SDValue();
6602
6603       // Because a SRL must be assumed to *need* to zero-extend the high bits
6604       // (as opposed to anyext the high bits), we can't combine the zextload
6605       // lowering of SRL and an sextload.
6606       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6607         return SDValue();
6608
6609       // If the shift amount is larger than the input type then we're not
6610       // accessing any of the loaded bytes.  If the load was a zextload/extload
6611       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6612       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6613         return SDValue();
6614     }
6615   }
6616
6617   // If the load is shifted left (and the result isn't shifted back right),
6618   // we can fold the truncate through the shift.
6619   unsigned ShLeftAmt = 0;
6620   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6621       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6622     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6623       ShLeftAmt = N01->getZExtValue();
6624       N0 = N0.getOperand(0);
6625     }
6626   }
6627
6628   // If we haven't found a load, we can't narrow it.  Don't transform one with
6629   // multiple uses, this would require adding a new load.
6630   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6631     return SDValue();
6632
6633   // Don't change the width of a volatile load.
6634   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6635   if (LN0->isVolatile())
6636     return SDValue();
6637
6638   // Verify that we are actually reducing a load width here.
6639   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6640     return SDValue();
6641
6642   // For the transform to be legal, the load must produce only two values
6643   // (the value loaded and the chain).  Don't transform a pre-increment
6644   // load, for example, which produces an extra value.  Otherwise the
6645   // transformation is not equivalent, and the downstream logic to replace
6646   // uses gets things wrong.
6647   if (LN0->getNumValues() > 2)
6648     return SDValue();
6649
6650   // If the load that we're shrinking is an extload and we're not just
6651   // discarding the extension we can't simply shrink the load. Bail.
6652   // TODO: It would be possible to merge the extensions in some cases.
6653   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6654       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6655     return SDValue();
6656
6657   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6658     return SDValue();
6659
6660   EVT PtrType = N0.getOperand(1).getValueType();
6661
6662   if (PtrType == MVT::Untyped || PtrType.isExtended())
6663     // It's not possible to generate a constant of extended or untyped type.
6664     return SDValue();
6665
6666   // For big endian targets, we need to adjust the offset to the pointer to
6667   // load the correct bytes.
6668   if (DAG.getDataLayout().isBigEndian()) {
6669     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6670     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6671     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6672   }
6673
6674   uint64_t PtrOff = ShAmt / 8;
6675   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6676   SDLoc DL(LN0);
6677   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6678                                PtrType, LN0->getBasePtr(),
6679                                DAG.getConstant(PtrOff, DL, PtrType));
6680   AddToWorklist(NewPtr.getNode());
6681
6682   SDValue Load;
6683   if (ExtType == ISD::NON_EXTLOAD)
6684     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6685                         LN0->getPointerInfo().getWithOffset(PtrOff),
6686                         LN0->isVolatile(), LN0->isNonTemporal(),
6687                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6688   else
6689     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6690                           LN0->getPointerInfo().getWithOffset(PtrOff),
6691                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6692                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6693
6694   // Replace the old load's chain with the new load's chain.
6695   WorklistRemover DeadNodes(*this);
6696   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6697
6698   // Shift the result left, if we've swallowed a left shift.
6699   SDValue Result = Load;
6700   if (ShLeftAmt != 0) {
6701     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6702     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6703       ShImmTy = VT;
6704     // If the shift amount is as large as the result size (but, presumably,
6705     // no larger than the source) then the useful bits of the result are
6706     // zero; we can't simply return the shortened shift, because the result
6707     // of that operation is undefined.
6708     SDLoc DL(N0);
6709     if (ShLeftAmt >= VT.getSizeInBits())
6710       Result = DAG.getConstant(0, DL, VT);
6711     else
6712       Result = DAG.getNode(ISD::SHL, DL, VT,
6713                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6714   }
6715
6716   // Return the new loaded value.
6717   return Result;
6718 }
6719
6720 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6721   SDValue N0 = N->getOperand(0);
6722   SDValue N1 = N->getOperand(1);
6723   EVT VT = N->getValueType(0);
6724   EVT EVT = cast<VTSDNode>(N1)->getVT();
6725   unsigned VTBits = VT.getScalarType().getSizeInBits();
6726   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6727
6728   // fold (sext_in_reg c1) -> c1
6729   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6730     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6731
6732   // If the input is already sign extended, just drop the extension.
6733   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6734     return N0;
6735
6736   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6737   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6738       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6739     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6740                        N0.getOperand(0), N1);
6741
6742   // fold (sext_in_reg (sext x)) -> (sext x)
6743   // fold (sext_in_reg (aext x)) -> (sext x)
6744   // if x is small enough.
6745   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6746     SDValue N00 = N0.getOperand(0);
6747     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6748         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6749       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6750   }
6751
6752   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6753   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6754     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6755
6756   // fold operands of sext_in_reg based on knowledge that the top bits are not
6757   // demanded.
6758   if (SimplifyDemandedBits(SDValue(N, 0)))
6759     return SDValue(N, 0);
6760
6761   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6762   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6763   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6764     return NarrowLoad;
6765
6766   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6767   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6768   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6769   if (N0.getOpcode() == ISD::SRL) {
6770     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6771       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6772         // We can turn this into an SRA iff the input to the SRL is already sign
6773         // extended enough.
6774         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6775         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6776           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6777                              N0.getOperand(0), N0.getOperand(1));
6778       }
6779   }
6780
6781   // fold (sext_inreg (extload x)) -> (sextload x)
6782   if (ISD::isEXTLoad(N0.getNode()) &&
6783       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6784       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6785       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6786        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6787     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6788     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6789                                      LN0->getChain(),
6790                                      LN0->getBasePtr(), EVT,
6791                                      LN0->getMemOperand());
6792     CombineTo(N, ExtLoad);
6793     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6794     AddToWorklist(ExtLoad.getNode());
6795     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6796   }
6797   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6798   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6799       N0.hasOneUse() &&
6800       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6801       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6802        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6803     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6804     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6805                                      LN0->getChain(),
6806                                      LN0->getBasePtr(), EVT,
6807                                      LN0->getMemOperand());
6808     CombineTo(N, ExtLoad);
6809     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6810     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6811   }
6812
6813   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6814   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6815     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6816                                        N0.getOperand(1), false);
6817     if (BSwap.getNode())
6818       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6819                          BSwap, N1);
6820   }
6821
6822   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6823   // into a build_vector.
6824   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6825     SmallVector<SDValue, 8> Elts;
6826     unsigned NumElts = N0->getNumOperands();
6827     unsigned ShAmt = VTBits - EVTBits;
6828
6829     for (unsigned i = 0; i != NumElts; ++i) {
6830       SDValue Op = N0->getOperand(i);
6831       if (Op->getOpcode() == ISD::UNDEF) {
6832         Elts.push_back(Op);
6833         continue;
6834       }
6835
6836       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6837       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6838       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6839                                      SDLoc(Op), Op.getValueType()));
6840     }
6841
6842     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6843   }
6844
6845   return SDValue();
6846 }
6847
6848 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6849   SDValue N0 = N->getOperand(0);
6850   EVT VT = N->getValueType(0);
6851
6852   if (N0.getOpcode() == ISD::UNDEF)
6853     return DAG.getUNDEF(VT);
6854
6855   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6856                                               LegalOperations))
6857     return SDValue(Res, 0);
6858
6859   return SDValue();
6860 }
6861
6862 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6863   SDValue N0 = N->getOperand(0);
6864   EVT VT = N->getValueType(0);
6865   bool isLE = DAG.getDataLayout().isLittleEndian();
6866
6867   // noop truncate
6868   if (N0.getValueType() == N->getValueType(0))
6869     return N0;
6870   // fold (truncate c1) -> c1
6871   if (isConstantIntBuildVectorOrConstantInt(N0))
6872     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6873   // fold (truncate (truncate x)) -> (truncate x)
6874   if (N0.getOpcode() == ISD::TRUNCATE)
6875     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6876   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6877   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6878       N0.getOpcode() == ISD::SIGN_EXTEND ||
6879       N0.getOpcode() == ISD::ANY_EXTEND) {
6880     if (N0.getOperand(0).getValueType().bitsLT(VT))
6881       // if the source is smaller than the dest, we still need an extend
6882       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6883                          N0.getOperand(0));
6884     if (N0.getOperand(0).getValueType().bitsGT(VT))
6885       // if the source is larger than the dest, than we just need the truncate
6886       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6887     // if the source and dest are the same type, we can drop both the extend
6888     // and the truncate.
6889     return N0.getOperand(0);
6890   }
6891
6892   // Fold extract-and-trunc into a narrow extract. For example:
6893   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6894   //   i32 y = TRUNCATE(i64 x)
6895   //        -- becomes --
6896   //   v16i8 b = BITCAST (v2i64 val)
6897   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6898   //
6899   // Note: We only run this optimization after type legalization (which often
6900   // creates this pattern) and before operation legalization after which
6901   // we need to be more careful about the vector instructions that we generate.
6902   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6903       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6904
6905     EVT VecTy = N0.getOperand(0).getValueType();
6906     EVT ExTy = N0.getValueType();
6907     EVT TrTy = N->getValueType(0);
6908
6909     unsigned NumElem = VecTy.getVectorNumElements();
6910     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6911
6912     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6913     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6914
6915     SDValue EltNo = N0->getOperand(1);
6916     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6917       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6918       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6919       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6920
6921       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6922                               NVT, N0.getOperand(0));
6923
6924       SDLoc DL(N);
6925       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6926                          DL, TrTy, V,
6927                          DAG.getConstant(Index, DL, IndexTy));
6928     }
6929   }
6930
6931   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6932   if (N0.getOpcode() == ISD::SELECT) {
6933     EVT SrcVT = N0.getValueType();
6934     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6935         TLI.isTruncateFree(SrcVT, VT)) {
6936       SDLoc SL(N0);
6937       SDValue Cond = N0.getOperand(0);
6938       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6939       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6940       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6941     }
6942   }
6943
6944   // Fold a series of buildvector, bitcast, and truncate if possible.
6945   // For example fold
6946   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6947   //   (2xi32 (buildvector x, y)).
6948   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6949       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6950       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6951       N0.getOperand(0).hasOneUse()) {
6952
6953     SDValue BuildVect = N0.getOperand(0);
6954     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6955     EVT TruncVecEltTy = VT.getVectorElementType();
6956
6957     // Check that the element types match.
6958     if (BuildVectEltTy == TruncVecEltTy) {
6959       // Now we only need to compute the offset of the truncated elements.
6960       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6961       unsigned TruncVecNumElts = VT.getVectorNumElements();
6962       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6963
6964       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6965              "Invalid number of elements");
6966
6967       SmallVector<SDValue, 8> Opnds;
6968       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6969         Opnds.push_back(BuildVect.getOperand(i));
6970
6971       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6972     }
6973   }
6974
6975   // See if we can simplify the input to this truncate through knowledge that
6976   // only the low bits are being used.
6977   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6978   // Currently we only perform this optimization on scalars because vectors
6979   // may have different active low bits.
6980   if (!VT.isVector()) {
6981     SDValue Shorter =
6982       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6983                                                VT.getSizeInBits()));
6984     if (Shorter.getNode())
6985       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6986   }
6987   // fold (truncate (load x)) -> (smaller load x)
6988   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6989   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6990     if (SDValue Reduced = ReduceLoadWidth(N))
6991       return Reduced;
6992
6993     // Handle the case where the load remains an extending load even
6994     // after truncation.
6995     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6996       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6997       if (!LN0->isVolatile() &&
6998           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6999         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7000                                          VT, LN0->getChain(), LN0->getBasePtr(),
7001                                          LN0->getMemoryVT(),
7002                                          LN0->getMemOperand());
7003         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7004         return NewLoad;
7005       }
7006     }
7007   }
7008   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7009   // where ... are all 'undef'.
7010   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7011     SmallVector<EVT, 8> VTs;
7012     SDValue V;
7013     unsigned Idx = 0;
7014     unsigned NumDefs = 0;
7015
7016     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7017       SDValue X = N0.getOperand(i);
7018       if (X.getOpcode() != ISD::UNDEF) {
7019         V = X;
7020         Idx = i;
7021         NumDefs++;
7022       }
7023       // Stop if more than one members are non-undef.
7024       if (NumDefs > 1)
7025         break;
7026       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7027                                      VT.getVectorElementType(),
7028                                      X.getValueType().getVectorNumElements()));
7029     }
7030
7031     if (NumDefs == 0)
7032       return DAG.getUNDEF(VT);
7033
7034     if (NumDefs == 1) {
7035       assert(V.getNode() && "The single defined operand is empty!");
7036       SmallVector<SDValue, 8> Opnds;
7037       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7038         if (i != Idx) {
7039           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7040           continue;
7041         }
7042         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7043         AddToWorklist(NV.getNode());
7044         Opnds.push_back(NV);
7045       }
7046       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7047     }
7048   }
7049
7050   // Simplify the operands using demanded-bits information.
7051   if (!VT.isVector() &&
7052       SimplifyDemandedBits(SDValue(N, 0)))
7053     return SDValue(N, 0);
7054
7055   return SDValue();
7056 }
7057
7058 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7059   SDValue Elt = N->getOperand(i);
7060   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7061     return Elt.getNode();
7062   return Elt.getOperand(Elt.getResNo()).getNode();
7063 }
7064
7065 /// build_pair (load, load) -> load
7066 /// if load locations are consecutive.
7067 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7068   assert(N->getOpcode() == ISD::BUILD_PAIR);
7069
7070   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7071   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7072   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7073       LD1->getAddressSpace() != LD2->getAddressSpace())
7074     return SDValue();
7075   EVT LD1VT = LD1->getValueType(0);
7076
7077   if (ISD::isNON_EXTLoad(LD2) &&
7078       LD2->hasOneUse() &&
7079       // If both are volatile this would reduce the number of volatile loads.
7080       // If one is volatile it might be ok, but play conservative and bail out.
7081       !LD1->isVolatile() &&
7082       !LD2->isVolatile() &&
7083       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7084     unsigned Align = LD1->getAlignment();
7085     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7086         VT.getTypeForEVT(*DAG.getContext()));
7087
7088     if (NewAlign <= Align &&
7089         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7090       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7091                          LD1->getBasePtr(), LD1->getPointerInfo(),
7092                          false, false, false, Align);
7093   }
7094
7095   return SDValue();
7096 }
7097
7098 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7099   SDValue N0 = N->getOperand(0);
7100   EVT VT = N->getValueType(0);
7101
7102   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7103   // Only do this before legalize, since afterward the target may be depending
7104   // on the bitconvert.
7105   // First check to see if this is all constant.
7106   if (!LegalTypes &&
7107       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7108       VT.isVector()) {
7109     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7110
7111     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7112     assert(!DestEltVT.isVector() &&
7113            "Element type of vector ValueType must not be vector!");
7114     if (isSimple)
7115       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7116   }
7117
7118   // If the input is a constant, let getNode fold it.
7119   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7120     // If we can't allow illegal operations, we need to check that this is just
7121     // a fp -> int or int -> conversion and that the resulting operation will
7122     // be legal.
7123     if (!LegalOperations ||
7124         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7125          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7126         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7127          TLI.isOperationLegal(ISD::Constant, VT)))
7128       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7129   }
7130
7131   // (conv (conv x, t1), t2) -> (conv x, t2)
7132   if (N0.getOpcode() == ISD::BITCAST)
7133     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7134                        N0.getOperand(0));
7135
7136   // fold (conv (load x)) -> (load (conv*)x)
7137   // If the resultant load doesn't need a higher alignment than the original!
7138   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7139       // Do not change the width of a volatile load.
7140       !cast<LoadSDNode>(N0)->isVolatile() &&
7141       // Do not remove the cast if the types differ in endian layout.
7142       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7143           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7144       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7145       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7146     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7147     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7148         VT.getTypeForEVT(*DAG.getContext()));
7149     unsigned OrigAlign = LN0->getAlignment();
7150
7151     if (Align <= OrigAlign) {
7152       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7153                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7154                                  LN0->isVolatile(), LN0->isNonTemporal(),
7155                                  LN0->isInvariant(), OrigAlign,
7156                                  LN0->getAAInfo());
7157       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7158       return Load;
7159     }
7160   }
7161
7162   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7163   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7164   // This often reduces constant pool loads.
7165   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7166        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7167       N0.getNode()->hasOneUse() && VT.isInteger() &&
7168       !VT.isVector() && !N0.getValueType().isVector()) {
7169     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7170                                   N0.getOperand(0));
7171     AddToWorklist(NewConv.getNode());
7172
7173     SDLoc DL(N);
7174     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7175     if (N0.getOpcode() == ISD::FNEG)
7176       return DAG.getNode(ISD::XOR, DL, VT,
7177                          NewConv, DAG.getConstant(SignBit, DL, VT));
7178     assert(N0.getOpcode() == ISD::FABS);
7179     return DAG.getNode(ISD::AND, DL, VT,
7180                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7181   }
7182
7183   // fold (bitconvert (fcopysign cst, x)) ->
7184   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7185   // Note that we don't handle (copysign x, cst) because this can always be
7186   // folded to an fneg or fabs.
7187   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7188       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7189       VT.isInteger() && !VT.isVector()) {
7190     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7191     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7192     if (isTypeLegal(IntXVT)) {
7193       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7194                               IntXVT, N0.getOperand(1));
7195       AddToWorklist(X.getNode());
7196
7197       // If X has a different width than the result/lhs, sext it or truncate it.
7198       unsigned VTWidth = VT.getSizeInBits();
7199       if (OrigXWidth < VTWidth) {
7200         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7201         AddToWorklist(X.getNode());
7202       } else if (OrigXWidth > VTWidth) {
7203         // To get the sign bit in the right place, we have to shift it right
7204         // before truncating.
7205         SDLoc DL(X);
7206         X = DAG.getNode(ISD::SRL, DL,
7207                         X.getValueType(), X,
7208                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7209                                         X.getValueType()));
7210         AddToWorklist(X.getNode());
7211         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7212         AddToWorklist(X.getNode());
7213       }
7214
7215       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7216       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7217                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7218       AddToWorklist(X.getNode());
7219
7220       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7221                                 VT, N0.getOperand(0));
7222       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7223                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7224       AddToWorklist(Cst.getNode());
7225
7226       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7227     }
7228   }
7229
7230   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7231   if (N0.getOpcode() == ISD::BUILD_PAIR)
7232     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7233       return CombineLD;
7234
7235   // Remove double bitcasts from shuffles - this is often a legacy of
7236   // XformToShuffleWithZero being used to combine bitmaskings (of
7237   // float vectors bitcast to integer vectors) into shuffles.
7238   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7239   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7240       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7241       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7242       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7243     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7244
7245     // If operands are a bitcast, peek through if it casts the original VT.
7246     // If operands are a constant, just bitcast back to original VT.
7247     auto PeekThroughBitcast = [&](SDValue Op) {
7248       if (Op.getOpcode() == ISD::BITCAST &&
7249           Op.getOperand(0).getValueType() == VT)
7250         return SDValue(Op.getOperand(0));
7251       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7252           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7253         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7254       return SDValue();
7255     };
7256
7257     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7258     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7259     if (!(SV0 && SV1))
7260       return SDValue();
7261
7262     int MaskScale =
7263         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7264     SmallVector<int, 8> NewMask;
7265     for (int M : SVN->getMask())
7266       for (int i = 0; i != MaskScale; ++i)
7267         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7268
7269     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7270     if (!LegalMask) {
7271       std::swap(SV0, SV1);
7272       ShuffleVectorSDNode::commuteMask(NewMask);
7273       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7274     }
7275
7276     if (LegalMask)
7277       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7278   }
7279
7280   return SDValue();
7281 }
7282
7283 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7284   EVT VT = N->getValueType(0);
7285   return CombineConsecutiveLoads(N, VT);
7286 }
7287
7288 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7289 /// operands. DstEltVT indicates the destination element value type.
7290 SDValue DAGCombiner::
7291 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7292   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7293
7294   // If this is already the right type, we're done.
7295   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7296
7297   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7298   unsigned DstBitSize = DstEltVT.getSizeInBits();
7299
7300   // If this is a conversion of N elements of one type to N elements of another
7301   // type, convert each element.  This handles FP<->INT cases.
7302   if (SrcBitSize == DstBitSize) {
7303     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7304                               BV->getValueType(0).getVectorNumElements());
7305
7306     // Due to the FP element handling below calling this routine recursively,
7307     // we can end up with a scalar-to-vector node here.
7308     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7309       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7310                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7311                                      DstEltVT, BV->getOperand(0)));
7312
7313     SmallVector<SDValue, 8> Ops;
7314     for (SDValue Op : BV->op_values()) {
7315       // If the vector element type is not legal, the BUILD_VECTOR operands
7316       // are promoted and implicitly truncated.  Make that explicit here.
7317       if (Op.getValueType() != SrcEltVT)
7318         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7319       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7320                                 DstEltVT, Op));
7321       AddToWorklist(Ops.back().getNode());
7322     }
7323     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7324   }
7325
7326   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7327   // handle annoying details of growing/shrinking FP values, we convert them to
7328   // int first.
7329   if (SrcEltVT.isFloatingPoint()) {
7330     // Convert the input float vector to a int vector where the elements are the
7331     // same sizes.
7332     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7333     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7334     SrcEltVT = IntVT;
7335   }
7336
7337   // Now we know the input is an integer vector.  If the output is a FP type,
7338   // convert to integer first, then to FP of the right size.
7339   if (DstEltVT.isFloatingPoint()) {
7340     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7341     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7342
7343     // Next, convert to FP elements of the same size.
7344     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7345   }
7346
7347   SDLoc DL(BV);
7348
7349   // Okay, we know the src/dst types are both integers of differing types.
7350   // Handling growing first.
7351   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7352   if (SrcBitSize < DstBitSize) {
7353     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7354
7355     SmallVector<SDValue, 8> Ops;
7356     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7357          i += NumInputsPerOutput) {
7358       bool isLE = DAG.getDataLayout().isLittleEndian();
7359       APInt NewBits = APInt(DstBitSize, 0);
7360       bool EltIsUndef = true;
7361       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7362         // Shift the previously computed bits over.
7363         NewBits <<= SrcBitSize;
7364         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7365         if (Op.getOpcode() == ISD::UNDEF) continue;
7366         EltIsUndef = false;
7367
7368         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7369                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7370       }
7371
7372       if (EltIsUndef)
7373         Ops.push_back(DAG.getUNDEF(DstEltVT));
7374       else
7375         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7376     }
7377
7378     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7379     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7380   }
7381
7382   // Finally, this must be the case where we are shrinking elements: each input
7383   // turns into multiple outputs.
7384   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7385   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7386                             NumOutputsPerInput*BV->getNumOperands());
7387   SmallVector<SDValue, 8> Ops;
7388
7389   for (const SDValue &Op : BV->op_values()) {
7390     if (Op.getOpcode() == ISD::UNDEF) {
7391       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7392       continue;
7393     }
7394
7395     APInt OpVal = cast<ConstantSDNode>(Op)->
7396                   getAPIntValue().zextOrTrunc(SrcBitSize);
7397
7398     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7399       APInt ThisVal = OpVal.trunc(DstBitSize);
7400       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7401       OpVal = OpVal.lshr(DstBitSize);
7402     }
7403
7404     // For big endian targets, swap the order of the pieces of each element.
7405     if (DAG.getDataLayout().isBigEndian())
7406       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7407   }
7408
7409   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7410 }
7411
7412 /// Try to perform FMA combining on a given FADD node.
7413 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7414   SDValue N0 = N->getOperand(0);
7415   SDValue N1 = N->getOperand(1);
7416   EVT VT = N->getValueType(0);
7417   SDLoc SL(N);
7418
7419   const TargetOptions &Options = DAG.getTarget().Options;
7420   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7421                        Options.UnsafeFPMath);
7422
7423   // Floating-point multiply-add with intermediate rounding.
7424   bool HasFMAD = (LegalOperations &&
7425                   TLI.isOperationLegal(ISD::FMAD, VT));
7426
7427   // Floating-point multiply-add without intermediate rounding.
7428   bool HasFMA = ((!LegalOperations ||
7429                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7430                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7431                  UnsafeFPMath);
7432
7433   // No valid opcode, do not combine.
7434   if (!HasFMAD && !HasFMA)
7435     return SDValue();
7436
7437   // Always prefer FMAD to FMA for precision.
7438   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7439   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7440   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7441
7442   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7443   // prefer to fold the multiply with fewer uses.
7444   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7445       N1.getOpcode() == ISD::FMUL) {
7446     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7447       std::swap(N0, N1);
7448   }
7449
7450   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7451   if (N0.getOpcode() == ISD::FMUL &&
7452       (Aggressive || N0->hasOneUse())) {
7453     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7454                        N0.getOperand(0), N0.getOperand(1), N1);
7455   }
7456
7457   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7458   // Note: Commutes FADD operands.
7459   if (N1.getOpcode() == ISD::FMUL &&
7460       (Aggressive || N1->hasOneUse())) {
7461     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7462                        N1.getOperand(0), N1.getOperand(1), N0);
7463   }
7464
7465   // Look through FP_EXTEND nodes to do more combining.
7466   if (UnsafeFPMath && LookThroughFPExt) {
7467     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7468     if (N0.getOpcode() == ISD::FP_EXTEND) {
7469       SDValue N00 = N0.getOperand(0);
7470       if (N00.getOpcode() == ISD::FMUL)
7471         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7472                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7473                                        N00.getOperand(0)),
7474                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7475                                        N00.getOperand(1)), N1);
7476     }
7477
7478     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7479     // Note: Commutes FADD operands.
7480     if (N1.getOpcode() == ISD::FP_EXTEND) {
7481       SDValue N10 = N1.getOperand(0);
7482       if (N10.getOpcode() == ISD::FMUL)
7483         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7484                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7485                                        N10.getOperand(0)),
7486                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7487                                        N10.getOperand(1)), N0);
7488     }
7489   }
7490
7491   // More folding opportunities when target permits.
7492   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7493     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7494     if (N0.getOpcode() == PreferredFusedOpcode &&
7495         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7496       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7497                          N0.getOperand(0), N0.getOperand(1),
7498                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7499                                      N0.getOperand(2).getOperand(0),
7500                                      N0.getOperand(2).getOperand(1),
7501                                      N1));
7502     }
7503
7504     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7505     if (N1->getOpcode() == PreferredFusedOpcode &&
7506         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7507       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7508                          N1.getOperand(0), N1.getOperand(1),
7509                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7510                                      N1.getOperand(2).getOperand(0),
7511                                      N1.getOperand(2).getOperand(1),
7512                                      N0));
7513     }
7514
7515     if (UnsafeFPMath && LookThroughFPExt) {
7516       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7517       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7518       auto FoldFAddFMAFPExtFMul = [&] (
7519           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7520         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7521                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7522                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7523                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7524                                        Z));
7525       };
7526       if (N0.getOpcode() == PreferredFusedOpcode) {
7527         SDValue N02 = N0.getOperand(2);
7528         if (N02.getOpcode() == ISD::FP_EXTEND) {
7529           SDValue N020 = N02.getOperand(0);
7530           if (N020.getOpcode() == ISD::FMUL)
7531             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7532                                         N020.getOperand(0), N020.getOperand(1),
7533                                         N1);
7534         }
7535       }
7536
7537       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7538       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7539       // FIXME: This turns two single-precision and one double-precision
7540       // operation into two double-precision operations, which might not be
7541       // interesting for all targets, especially GPUs.
7542       auto FoldFAddFPExtFMAFMul = [&] (
7543           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7544         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7545                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7546                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7547                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7548                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7549                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7550                                        Z));
7551       };
7552       if (N0.getOpcode() == ISD::FP_EXTEND) {
7553         SDValue N00 = N0.getOperand(0);
7554         if (N00.getOpcode() == PreferredFusedOpcode) {
7555           SDValue N002 = N00.getOperand(2);
7556           if (N002.getOpcode() == ISD::FMUL)
7557             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7558                                         N002.getOperand(0), N002.getOperand(1),
7559                                         N1);
7560         }
7561       }
7562
7563       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7564       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7565       if (N1.getOpcode() == PreferredFusedOpcode) {
7566         SDValue N12 = N1.getOperand(2);
7567         if (N12.getOpcode() == ISD::FP_EXTEND) {
7568           SDValue N120 = N12.getOperand(0);
7569           if (N120.getOpcode() == ISD::FMUL)
7570             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7571                                         N120.getOperand(0), N120.getOperand(1),
7572                                         N0);
7573         }
7574       }
7575
7576       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7577       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7578       // FIXME: This turns two single-precision and one double-precision
7579       // operation into two double-precision operations, which might not be
7580       // interesting for all targets, especially GPUs.
7581       if (N1.getOpcode() == ISD::FP_EXTEND) {
7582         SDValue N10 = N1.getOperand(0);
7583         if (N10.getOpcode() == PreferredFusedOpcode) {
7584           SDValue N102 = N10.getOperand(2);
7585           if (N102.getOpcode() == ISD::FMUL)
7586             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7587                                         N102.getOperand(0), N102.getOperand(1),
7588                                         N0);
7589         }
7590       }
7591     }
7592   }
7593
7594   return SDValue();
7595 }
7596
7597 /// Try to perform FMA combining on a given FSUB node.
7598 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7599   SDValue N0 = N->getOperand(0);
7600   SDValue N1 = N->getOperand(1);
7601   EVT VT = N->getValueType(0);
7602   SDLoc SL(N);
7603
7604   const TargetOptions &Options = DAG.getTarget().Options;
7605   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7606                        Options.UnsafeFPMath);
7607
7608   // Floating-point multiply-add with intermediate rounding.
7609   bool HasFMAD = (LegalOperations &&
7610                   TLI.isOperationLegal(ISD::FMAD, VT));
7611
7612   // Floating-point multiply-add without intermediate rounding.
7613   bool HasFMA = ((!LegalOperations ||
7614                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7615                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7616                  UnsafeFPMath);
7617
7618   // No valid opcode, do not combine.
7619   if (!HasFMAD && !HasFMA)
7620     return SDValue();
7621
7622   // Always prefer FMAD to FMA for precision.
7623   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7624   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7625   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7626
7627   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7628   if (N0.getOpcode() == ISD::FMUL &&
7629       (Aggressive || N0->hasOneUse())) {
7630     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7631                        N0.getOperand(0), N0.getOperand(1),
7632                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7633   }
7634
7635   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7636   // Note: Commutes FSUB operands.
7637   if (N1.getOpcode() == ISD::FMUL &&
7638       (Aggressive || N1->hasOneUse()))
7639     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7640                        DAG.getNode(ISD::FNEG, SL, VT,
7641                                    N1.getOperand(0)),
7642                        N1.getOperand(1), N0);
7643
7644   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7645   if (N0.getOpcode() == ISD::FNEG &&
7646       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7647       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7648     SDValue N00 = N0.getOperand(0).getOperand(0);
7649     SDValue N01 = N0.getOperand(0).getOperand(1);
7650     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7651                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7652                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7653   }
7654
7655   // Look through FP_EXTEND nodes to do more combining.
7656   if (UnsafeFPMath && LookThroughFPExt) {
7657     // fold (fsub (fpext (fmul x, y)), z)
7658     //   -> (fma (fpext x), (fpext y), (fneg z))
7659     if (N0.getOpcode() == ISD::FP_EXTEND) {
7660       SDValue N00 = N0.getOperand(0);
7661       if (N00.getOpcode() == ISD::FMUL)
7662         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7663                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7664                                        N00.getOperand(0)),
7665                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7666                                        N00.getOperand(1)),
7667                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7668     }
7669
7670     // fold (fsub x, (fpext (fmul y, z)))
7671     //   -> (fma (fneg (fpext y)), (fpext z), x)
7672     // Note: Commutes FSUB operands.
7673     if (N1.getOpcode() == ISD::FP_EXTEND) {
7674       SDValue N10 = N1.getOperand(0);
7675       if (N10.getOpcode() == ISD::FMUL)
7676         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7677                            DAG.getNode(ISD::FNEG, SL, VT,
7678                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7679                                                    N10.getOperand(0))),
7680                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7681                                        N10.getOperand(1)),
7682                            N0);
7683     }
7684
7685     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7686     //   -> (fneg (fma (fpext x), (fpext y), z))
7687     // Note: This could be removed with appropriate canonicalization of the
7688     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7689     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7690     // from implementing the canonicalization in visitFSUB.
7691     if (N0.getOpcode() == ISD::FP_EXTEND) {
7692       SDValue N00 = N0.getOperand(0);
7693       if (N00.getOpcode() == ISD::FNEG) {
7694         SDValue N000 = N00.getOperand(0);
7695         if (N000.getOpcode() == ISD::FMUL) {
7696           return DAG.getNode(ISD::FNEG, SL, VT,
7697                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7698                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7699                                                      N000.getOperand(0)),
7700                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7701                                                      N000.getOperand(1)),
7702                                          N1));
7703         }
7704       }
7705     }
7706
7707     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7708     //   -> (fneg (fma (fpext x)), (fpext y), z)
7709     // Note: This could be removed with appropriate canonicalization of the
7710     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7711     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7712     // from implementing the canonicalization in visitFSUB.
7713     if (N0.getOpcode() == ISD::FNEG) {
7714       SDValue N00 = N0.getOperand(0);
7715       if (N00.getOpcode() == ISD::FP_EXTEND) {
7716         SDValue N000 = N00.getOperand(0);
7717         if (N000.getOpcode() == ISD::FMUL) {
7718           return DAG.getNode(ISD::FNEG, SL, VT,
7719                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7720                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721                                                      N000.getOperand(0)),
7722                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7723                                                      N000.getOperand(1)),
7724                                          N1));
7725         }
7726       }
7727     }
7728
7729   }
7730
7731   // More folding opportunities when target permits.
7732   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7733     // fold (fsub (fma x, y, (fmul u, v)), z)
7734     //   -> (fma x, y (fma u, v, (fneg z)))
7735     if (N0.getOpcode() == PreferredFusedOpcode &&
7736         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7737       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7738                          N0.getOperand(0), N0.getOperand(1),
7739                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                                      N0.getOperand(2).getOperand(0),
7741                                      N0.getOperand(2).getOperand(1),
7742                                      DAG.getNode(ISD::FNEG, SL, VT,
7743                                                  N1)));
7744     }
7745
7746     // fold (fsub x, (fma y, z, (fmul u, v)))
7747     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7748     if (N1.getOpcode() == PreferredFusedOpcode &&
7749         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7750       SDValue N20 = N1.getOperand(2).getOperand(0);
7751       SDValue N21 = N1.getOperand(2).getOperand(1);
7752       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7753                          DAG.getNode(ISD::FNEG, SL, VT,
7754                                      N1.getOperand(0)),
7755                          N1.getOperand(1),
7756                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7757                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7758
7759                                      N21, N0));
7760     }
7761
7762     if (UnsafeFPMath && LookThroughFPExt) {
7763       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7764       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7765       if (N0.getOpcode() == PreferredFusedOpcode) {
7766         SDValue N02 = N0.getOperand(2);
7767         if (N02.getOpcode() == ISD::FP_EXTEND) {
7768           SDValue N020 = N02.getOperand(0);
7769           if (N020.getOpcode() == ISD::FMUL)
7770             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7771                                N0.getOperand(0), N0.getOperand(1),
7772                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7773                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7774                                                        N020.getOperand(0)),
7775                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7776                                                        N020.getOperand(1)),
7777                                            DAG.getNode(ISD::FNEG, SL, VT,
7778                                                        N1)));
7779         }
7780       }
7781
7782       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7783       //   -> (fma (fpext x), (fpext y),
7784       //           (fma (fpext u), (fpext v), (fneg z)))
7785       // FIXME: This turns two single-precision and one double-precision
7786       // operation into two double-precision operations, which might not be
7787       // interesting for all targets, especially GPUs.
7788       if (N0.getOpcode() == ISD::FP_EXTEND) {
7789         SDValue N00 = N0.getOperand(0);
7790         if (N00.getOpcode() == PreferredFusedOpcode) {
7791           SDValue N002 = N00.getOperand(2);
7792           if (N002.getOpcode() == ISD::FMUL)
7793             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7794                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7795                                            N00.getOperand(0)),
7796                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7797                                            N00.getOperand(1)),
7798                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7799                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7800                                                        N002.getOperand(0)),
7801                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7802                                                        N002.getOperand(1)),
7803                                            DAG.getNode(ISD::FNEG, SL, VT,
7804                                                        N1)));
7805         }
7806       }
7807
7808       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7809       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7810       if (N1.getOpcode() == PreferredFusedOpcode &&
7811         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7812         SDValue N120 = N1.getOperand(2).getOperand(0);
7813         if (N120.getOpcode() == ISD::FMUL) {
7814           SDValue N1200 = N120.getOperand(0);
7815           SDValue N1201 = N120.getOperand(1);
7816           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7817                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7818                              N1.getOperand(1),
7819                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                                          DAG.getNode(ISD::FNEG, SL, VT,
7821                                              DAG.getNode(ISD::FP_EXTEND, SL,
7822                                                          VT, N1200)),
7823                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7824                                                      N1201),
7825                                          N0));
7826         }
7827       }
7828
7829       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7830       //   -> (fma (fneg (fpext y)), (fpext z),
7831       //           (fma (fneg (fpext u)), (fpext v), x))
7832       // FIXME: This turns two single-precision and one double-precision
7833       // operation into two double-precision operations, which might not be
7834       // interesting for all targets, especially GPUs.
7835       if (N1.getOpcode() == ISD::FP_EXTEND &&
7836         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7837         SDValue N100 = N1.getOperand(0).getOperand(0);
7838         SDValue N101 = N1.getOperand(0).getOperand(1);
7839         SDValue N102 = N1.getOperand(0).getOperand(2);
7840         if (N102.getOpcode() == ISD::FMUL) {
7841           SDValue N1020 = N102.getOperand(0);
7842           SDValue N1021 = N102.getOperand(1);
7843           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7844                              DAG.getNode(ISD::FNEG, SL, VT,
7845                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7846                                                      N100)),
7847                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7848                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7849                                          DAG.getNode(ISD::FNEG, SL, VT,
7850                                              DAG.getNode(ISD::FP_EXTEND, SL,
7851                                                          VT, N1020)),
7852                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7853                                                      N1021),
7854                                          N0));
7855         }
7856       }
7857     }
7858   }
7859
7860   return SDValue();
7861 }
7862
7863 SDValue DAGCombiner::visitFADD(SDNode *N) {
7864   SDValue N0 = N->getOperand(0);
7865   SDValue N1 = N->getOperand(1);
7866   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7867   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7868   EVT VT = N->getValueType(0);
7869   SDLoc DL(N);
7870   const TargetOptions &Options = DAG.getTarget().Options;
7871
7872   // fold vector ops
7873   if (VT.isVector())
7874     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7875       return FoldedVOp;
7876
7877   // fold (fadd c1, c2) -> c1 + c2
7878   if (N0CFP && N1CFP)
7879     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7880
7881   // canonicalize constant to RHS
7882   if (N0CFP && !N1CFP)
7883     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7884
7885   // fold (fadd A, (fneg B)) -> (fsub A, B)
7886   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7887       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7888     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7889                        GetNegatedExpression(N1, DAG, LegalOperations));
7890
7891   // fold (fadd (fneg A), B) -> (fsub B, A)
7892   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7893       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7894     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7895                        GetNegatedExpression(N0, DAG, LegalOperations));
7896
7897   // If 'unsafe math' is enabled, fold lots of things.
7898   if (Options.UnsafeFPMath) {
7899     // No FP constant should be created after legalization as Instruction
7900     // Selection pass has a hard time dealing with FP constants.
7901     bool AllowNewConst = (Level < AfterLegalizeDAG);
7902
7903     // fold (fadd A, 0) -> A
7904     if (N1CFP && N1CFP->isZero())
7905       return N0;
7906
7907     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7908     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7909         isa<ConstantFPSDNode>(N0.getOperand(1)))
7910       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7911                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7912
7913     // If allowed, fold (fadd (fneg x), x) -> 0.0
7914     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7915       return DAG.getConstantFP(0.0, DL, VT);
7916
7917     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7918     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7919       return DAG.getConstantFP(0.0, DL, VT);
7920
7921     // We can fold chains of FADD's of the same value into multiplications.
7922     // This transform is not safe in general because we are reducing the number
7923     // of rounding steps.
7924     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7925       if (N0.getOpcode() == ISD::FMUL) {
7926         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7927         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7928
7929         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7930         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7931           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7932                                        DAG.getConstantFP(1.0, DL, VT));
7933           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7934         }
7935
7936         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7937         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7938             N1.getOperand(0) == N1.getOperand(1) &&
7939             N0.getOperand(0) == N1.getOperand(0)) {
7940           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7941                                        DAG.getConstantFP(2.0, DL, VT));
7942           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7943         }
7944       }
7945
7946       if (N1.getOpcode() == ISD::FMUL) {
7947         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7948         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7949
7950         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7951         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7952           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7953                                        DAG.getConstantFP(1.0, DL, VT));
7954           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7955         }
7956
7957         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7958         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7959             N0.getOperand(0) == N0.getOperand(1) &&
7960             N1.getOperand(0) == N0.getOperand(0)) {
7961           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7962                                        DAG.getConstantFP(2.0, DL, VT));
7963           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7964         }
7965       }
7966
7967       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7968         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7969         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7970         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7971             (N0.getOperand(0) == N1)) {
7972           return DAG.getNode(ISD::FMUL, DL, VT,
7973                              N1, DAG.getConstantFP(3.0, DL, VT));
7974         }
7975       }
7976
7977       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7978         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7979         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7980         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7981             N1.getOperand(0) == N0) {
7982           return DAG.getNode(ISD::FMUL, DL, VT,
7983                              N0, DAG.getConstantFP(3.0, DL, VT));
7984         }
7985       }
7986
7987       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7988       if (AllowNewConst &&
7989           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7990           N0.getOperand(0) == N0.getOperand(1) &&
7991           N1.getOperand(0) == N1.getOperand(1) &&
7992           N0.getOperand(0) == N1.getOperand(0)) {
7993         return DAG.getNode(ISD::FMUL, DL, VT,
7994                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7995       }
7996     }
7997   } // enable-unsafe-fp-math
7998
7999   // FADD -> FMA combines:
8000   if (SDValue Fused = visitFADDForFMACombine(N)) {
8001     AddToWorklist(Fused.getNode());
8002     return Fused;
8003   }
8004
8005   return SDValue();
8006 }
8007
8008 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8009   SDValue N0 = N->getOperand(0);
8010   SDValue N1 = N->getOperand(1);
8011   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8012   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8013   EVT VT = N->getValueType(0);
8014   SDLoc dl(N);
8015   const TargetOptions &Options = DAG.getTarget().Options;
8016
8017   // fold vector ops
8018   if (VT.isVector())
8019     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8020       return FoldedVOp;
8021
8022   // fold (fsub c1, c2) -> c1-c2
8023   if (N0CFP && N1CFP)
8024     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8025
8026   // fold (fsub A, (fneg B)) -> (fadd A, B)
8027   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8028     return DAG.getNode(ISD::FADD, dl, VT, N0,
8029                        GetNegatedExpression(N1, DAG, LegalOperations));
8030
8031   // If 'unsafe math' is enabled, fold lots of things.
8032   if (Options.UnsafeFPMath) {
8033     // (fsub A, 0) -> A
8034     if (N1CFP && N1CFP->isZero())
8035       return N0;
8036
8037     // (fsub 0, B) -> -B
8038     if (N0CFP && N0CFP->isZero()) {
8039       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8040         return GetNegatedExpression(N1, DAG, LegalOperations);
8041       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8042         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8043     }
8044
8045     // (fsub x, x) -> 0.0
8046     if (N0 == N1)
8047       return DAG.getConstantFP(0.0f, dl, VT);
8048
8049     // (fsub x, (fadd x, y)) -> (fneg y)
8050     // (fsub x, (fadd y, x)) -> (fneg y)
8051     if (N1.getOpcode() == ISD::FADD) {
8052       SDValue N10 = N1->getOperand(0);
8053       SDValue N11 = N1->getOperand(1);
8054
8055       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8056         return GetNegatedExpression(N11, DAG, LegalOperations);
8057
8058       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8059         return GetNegatedExpression(N10, DAG, LegalOperations);
8060     }
8061   }
8062
8063   // FSUB -> FMA combines:
8064   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8065     AddToWorklist(Fused.getNode());
8066     return Fused;
8067   }
8068
8069   return SDValue();
8070 }
8071
8072 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8073   SDValue N0 = N->getOperand(0);
8074   SDValue N1 = N->getOperand(1);
8075   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8076   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8077   EVT VT = N->getValueType(0);
8078   SDLoc DL(N);
8079   const TargetOptions &Options = DAG.getTarget().Options;
8080
8081   // fold vector ops
8082   if (VT.isVector()) {
8083     // This just handles C1 * C2 for vectors. Other vector folds are below.
8084     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8085       return FoldedVOp;
8086   }
8087
8088   // fold (fmul c1, c2) -> c1*c2
8089   if (N0CFP && N1CFP)
8090     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8091
8092   // canonicalize constant to RHS
8093   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8094      !isConstantFPBuildVectorOrConstantFP(N1))
8095     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8096
8097   // fold (fmul A, 1.0) -> A
8098   if (N1CFP && N1CFP->isExactlyValue(1.0))
8099     return N0;
8100
8101   if (Options.UnsafeFPMath) {
8102     // fold (fmul A, 0) -> 0
8103     if (N1CFP && N1CFP->isZero())
8104       return N1;
8105
8106     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8107     if (N0.getOpcode() == ISD::FMUL) {
8108       // Fold scalars or any vector constants (not just splats).
8109       // This fold is done in general by InstCombine, but extra fmul insts
8110       // may have been generated during lowering.
8111       SDValue N00 = N0.getOperand(0);
8112       SDValue N01 = N0.getOperand(1);
8113       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8114       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8115       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8116
8117       // Check 1: Make sure that the first operand of the inner multiply is NOT
8118       // a constant. Otherwise, we may induce infinite looping.
8119       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8120         // Check 2: Make sure that the second operand of the inner multiply and
8121         // the second operand of the outer multiply are constants.
8122         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8123             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8124           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8125           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8126         }
8127       }
8128     }
8129
8130     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8131     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8132     // during an early run of DAGCombiner can prevent folding with fmuls
8133     // inserted during lowering.
8134     if (N0.getOpcode() == ISD::FADD &&
8135         (N0.getOperand(0) == N0.getOperand(1)) &&
8136         N0.hasOneUse()) {
8137       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8138       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8139       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8140     }
8141   }
8142
8143   // fold (fmul X, 2.0) -> (fadd X, X)
8144   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8145     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8146
8147   // fold (fmul X, -1.0) -> (fneg X)
8148   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8149     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8150       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8151
8152   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8153   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8154     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8155       // Both can be negated for free, check to see if at least one is cheaper
8156       // negated.
8157       if (LHSNeg == 2 || RHSNeg == 2)
8158         return DAG.getNode(ISD::FMUL, DL, VT,
8159                            GetNegatedExpression(N0, DAG, LegalOperations),
8160                            GetNegatedExpression(N1, DAG, LegalOperations));
8161     }
8162   }
8163
8164   return SDValue();
8165 }
8166
8167 SDValue DAGCombiner::visitFMA(SDNode *N) {
8168   SDValue N0 = N->getOperand(0);
8169   SDValue N1 = N->getOperand(1);
8170   SDValue N2 = N->getOperand(2);
8171   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8172   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8173   EVT VT = N->getValueType(0);
8174   SDLoc dl(N);
8175   const TargetOptions &Options = DAG.getTarget().Options;
8176
8177   // Constant fold FMA.
8178   if (isa<ConstantFPSDNode>(N0) &&
8179       isa<ConstantFPSDNode>(N1) &&
8180       isa<ConstantFPSDNode>(N2)) {
8181     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8182   }
8183
8184   if (Options.UnsafeFPMath) {
8185     if (N0CFP && N0CFP->isZero())
8186       return N2;
8187     if (N1CFP && N1CFP->isZero())
8188       return N2;
8189   }
8190   if (N0CFP && N0CFP->isExactlyValue(1.0))
8191     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8192   if (N1CFP && N1CFP->isExactlyValue(1.0))
8193     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8194
8195   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8196   if (N0CFP && !N1CFP)
8197     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8198
8199   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8200   if (Options.UnsafeFPMath && N1CFP &&
8201       N2.getOpcode() == ISD::FMUL &&
8202       N0 == N2.getOperand(0) &&
8203       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8204     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8205                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8206   }
8207
8208
8209   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8210   if (Options.UnsafeFPMath &&
8211       N0.getOpcode() == ISD::FMUL && N1CFP &&
8212       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8213     return DAG.getNode(ISD::FMA, dl, VT,
8214                        N0.getOperand(0),
8215                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8216                        N2);
8217   }
8218
8219   // (fma x, 1, y) -> (fadd x, y)
8220   // (fma x, -1, y) -> (fadd (fneg x), y)
8221   if (N1CFP) {
8222     if (N1CFP->isExactlyValue(1.0))
8223       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8224
8225     if (N1CFP->isExactlyValue(-1.0) &&
8226         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8227       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8228       AddToWorklist(RHSNeg.getNode());
8229       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8230     }
8231   }
8232
8233   // (fma x, c, x) -> (fmul x, (c+1))
8234   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8235     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8236                        DAG.getNode(ISD::FADD, dl, VT,
8237                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8238
8239   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8240   if (Options.UnsafeFPMath && N1CFP &&
8241       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8242     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8243                        DAG.getNode(ISD::FADD, dl, VT,
8244                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8245
8246
8247   return SDValue();
8248 }
8249
8250 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8251 // reciprocal.
8252 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8253 // Notice that this is not always beneficial. One reason is different target
8254 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8255 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8256 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8257 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8258   if (!DAG.getTarget().Options.UnsafeFPMath)
8259     return SDValue();
8260
8261   // Skip if current node is a reciprocal.
8262   SDValue N0 = N->getOperand(0);
8263   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8264   if (N0CFP && N0CFP->isExactlyValue(1.0))
8265     return SDValue();
8266
8267   // Exit early if the target does not want this transform or if there can't
8268   // possibly be enough uses of the divisor to make the transform worthwhile.
8269   SDValue N1 = N->getOperand(1);
8270   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8271   if (!MinUses || N1->use_size() < MinUses)
8272     return SDValue();
8273
8274   // Find all FDIV users of the same divisor.
8275   // Use a set because duplicates may be present in the user list.
8276   SetVector<SDNode *> Users;
8277   for (auto *U : N1->uses())
8278     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8279       Users.insert(U);
8280
8281   // Now that we have the actual number of divisor uses, make sure it meets
8282   // the minimum threshold specified by the target.
8283   if (Users.size() < MinUses)
8284     return SDValue();
8285
8286   EVT VT = N->getValueType(0);
8287   SDLoc DL(N);
8288   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8289   // FIXME: This optimization requires some level of fast-math, so the
8290   // created reciprocal node should at least have the 'allowReciprocal'
8291   // fast-math-flag set.
8292   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8293
8294   // Dividend / Divisor -> Dividend * Reciprocal
8295   for (auto *U : Users) {
8296     SDValue Dividend = U->getOperand(0);
8297     if (Dividend != FPOne) {
8298       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8299                                     Reciprocal);
8300       CombineTo(U, NewNode);
8301     } else if (U != Reciprocal.getNode()) {
8302       // In the absence of fast-math-flags, this user node is always the
8303       // same node as Reciprocal, but with FMF they may be different nodes.
8304       CombineTo(U, Reciprocal);
8305     }
8306   }
8307   return SDValue(N, 0);  // N was replaced.
8308 }
8309
8310 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8311   SDValue N0 = N->getOperand(0);
8312   SDValue N1 = N->getOperand(1);
8313   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8314   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8315   EVT VT = N->getValueType(0);
8316   SDLoc DL(N);
8317   const TargetOptions &Options = DAG.getTarget().Options;
8318
8319   // fold vector ops
8320   if (VT.isVector())
8321     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8322       return FoldedVOp;
8323
8324   // fold (fdiv c1, c2) -> c1/c2
8325   if (N0CFP && N1CFP)
8326     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8327
8328   if (Options.UnsafeFPMath) {
8329     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8330     if (N1CFP) {
8331       // Compute the reciprocal 1.0 / c2.
8332       APFloat N1APF = N1CFP->getValueAPF();
8333       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8334       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8335       // Only do the transform if the reciprocal is a legal fp immediate that
8336       // isn't too nasty (eg NaN, denormal, ...).
8337       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8338           (!LegalOperations ||
8339            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8340            // backend)... we should handle this gracefully after Legalize.
8341            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8342            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8343            TLI.isFPImmLegal(Recip, VT)))
8344         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8345                            DAG.getConstantFP(Recip, DL, VT));
8346     }
8347
8348     // If this FDIV is part of a reciprocal square root, it may be folded
8349     // into a target-specific square root estimate instruction.
8350     if (N1.getOpcode() == ISD::FSQRT) {
8351       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8352         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8353       }
8354     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8355                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8356       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8357         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8358         AddToWorklist(RV.getNode());
8359         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8360       }
8361     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8362                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8363       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8364         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8365         AddToWorklist(RV.getNode());
8366         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8367       }
8368     } else if (N1.getOpcode() == ISD::FMUL) {
8369       // Look through an FMUL. Even though this won't remove the FDIV directly,
8370       // it's still worthwhile to get rid of the FSQRT if possible.
8371       SDValue SqrtOp;
8372       SDValue OtherOp;
8373       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8374         SqrtOp = N1.getOperand(0);
8375         OtherOp = N1.getOperand(1);
8376       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8377         SqrtOp = N1.getOperand(1);
8378         OtherOp = N1.getOperand(0);
8379       }
8380       if (SqrtOp.getNode()) {
8381         // We found a FSQRT, so try to make this fold:
8382         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8383         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8384           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8385           AddToWorklist(RV.getNode());
8386           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8387         }
8388       }
8389     }
8390
8391     // Fold into a reciprocal estimate and multiply instead of a real divide.
8392     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8393       AddToWorklist(RV.getNode());
8394       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8395     }
8396   }
8397
8398   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8399   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8400     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8401       // Both can be negated for free, check to see if at least one is cheaper
8402       // negated.
8403       if (LHSNeg == 2 || RHSNeg == 2)
8404         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8405                            GetNegatedExpression(N0, DAG, LegalOperations),
8406                            GetNegatedExpression(N1, DAG, LegalOperations));
8407     }
8408   }
8409
8410   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8411     return CombineRepeatedDivisors;
8412
8413   return SDValue();
8414 }
8415
8416 SDValue DAGCombiner::visitFREM(SDNode *N) {
8417   SDValue N0 = N->getOperand(0);
8418   SDValue N1 = N->getOperand(1);
8419   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8420   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8421   EVT VT = N->getValueType(0);
8422
8423   // fold (frem c1, c2) -> fmod(c1,c2)
8424   if (N0CFP && N1CFP)
8425     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8426
8427   return SDValue();
8428 }
8429
8430 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8431   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8432     return SDValue();
8433
8434   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8435   SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8436   if (!RV)
8437     return SDValue();
8438
8439   EVT VT = RV.getValueType();
8440   SDLoc DL(N);
8441   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8442   AddToWorklist(RV.getNode());
8443
8444   // Unfortunately, RV is now NaN if the input was exactly 0.
8445   // Select out this case and force the answer to 0.
8446   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8447   EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8448   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8449   AddToWorklist(ZeroCmp.getNode());
8450   AddToWorklist(RV.getNode());
8451
8452   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8453                      ZeroCmp, Zero, RV);
8454 }
8455
8456 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8457   SDValue N0 = N->getOperand(0);
8458   SDValue N1 = N->getOperand(1);
8459   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8460   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8461   EVT VT = N->getValueType(0);
8462
8463   if (N0CFP && N1CFP)  // Constant fold
8464     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8465
8466   if (N1CFP) {
8467     const APFloat& V = N1CFP->getValueAPF();
8468     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8469     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8470     if (!V.isNegative()) {
8471       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8472         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8473     } else {
8474       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8475         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8476                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8477     }
8478   }
8479
8480   // copysign(fabs(x), y) -> copysign(x, y)
8481   // copysign(fneg(x), y) -> copysign(x, y)
8482   // copysign(copysign(x,z), y) -> copysign(x, y)
8483   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8484       N0.getOpcode() == ISD::FCOPYSIGN)
8485     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8486                        N0.getOperand(0), N1);
8487
8488   // copysign(x, abs(y)) -> abs(x)
8489   if (N1.getOpcode() == ISD::FABS)
8490     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8491
8492   // copysign(x, copysign(y,z)) -> copysign(x, z)
8493   if (N1.getOpcode() == ISD::FCOPYSIGN)
8494     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8495                        N0, N1.getOperand(1));
8496
8497   // copysign(x, fp_extend(y)) -> copysign(x, y)
8498   // copysign(x, fp_round(y)) -> copysign(x, y)
8499   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8500     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8501                        N0, N1.getOperand(0));
8502
8503   return SDValue();
8504 }
8505
8506 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8507   SDValue N0 = N->getOperand(0);
8508   EVT VT = N->getValueType(0);
8509   EVT OpVT = N0.getValueType();
8510
8511   // fold (sint_to_fp c1) -> c1fp
8512   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8513       // ...but only if the target supports immediate floating-point values
8514       (!LegalOperations ||
8515        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8516     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8517
8518   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8519   // but UINT_TO_FP is legal on this target, try to convert.
8520   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8521       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8522     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8523     if (DAG.SignBitIsZero(N0))
8524       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8525   }
8526
8527   // The next optimizations are desirable only if SELECT_CC can be lowered.
8528   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8529     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8530     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8531         !VT.isVector() &&
8532         (!LegalOperations ||
8533          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8534       SDLoc DL(N);
8535       SDValue Ops[] =
8536         { N0.getOperand(0), N0.getOperand(1),
8537           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8538           N0.getOperand(2) };
8539       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8540     }
8541
8542     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8543     //      (select_cc x, y, 1.0, 0.0,, cc)
8544     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8545         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8546         (!LegalOperations ||
8547          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8548       SDLoc DL(N);
8549       SDValue Ops[] =
8550         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8551           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8552           N0.getOperand(0).getOperand(2) };
8553       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8554     }
8555   }
8556
8557   return SDValue();
8558 }
8559
8560 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8561   SDValue N0 = N->getOperand(0);
8562   EVT VT = N->getValueType(0);
8563   EVT OpVT = N0.getValueType();
8564
8565   // fold (uint_to_fp c1) -> c1fp
8566   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8567       // ...but only if the target supports immediate floating-point values
8568       (!LegalOperations ||
8569        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8570     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8571
8572   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8573   // but SINT_TO_FP is legal on this target, try to convert.
8574   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8575       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8576     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8577     if (DAG.SignBitIsZero(N0))
8578       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8579   }
8580
8581   // The next optimizations are desirable only if SELECT_CC can be lowered.
8582   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8583     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8584
8585     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8586         (!LegalOperations ||
8587          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8588       SDLoc DL(N);
8589       SDValue Ops[] =
8590         { N0.getOperand(0), N0.getOperand(1),
8591           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8592           N0.getOperand(2) };
8593       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8594     }
8595   }
8596
8597   return SDValue();
8598 }
8599
8600 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8601 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8602   SDValue N0 = N->getOperand(0);
8603   EVT VT = N->getValueType(0);
8604
8605   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8606     return SDValue();
8607
8608   SDValue Src = N0.getOperand(0);
8609   EVT SrcVT = Src.getValueType();
8610   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8611   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8612
8613   // We can safely assume the conversion won't overflow the output range,
8614   // because (for example) (uint8_t)18293.f is undefined behavior.
8615
8616   // Since we can assume the conversion won't overflow, our decision as to
8617   // whether the input will fit in the float should depend on the minimum
8618   // of the input range and output range.
8619
8620   // This means this is also safe for a signed input and unsigned output, since
8621   // a negative input would lead to undefined behavior.
8622   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8623   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8624   unsigned ActualSize = std::min(InputSize, OutputSize);
8625   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8626
8627   // We can only fold away the float conversion if the input range can be
8628   // represented exactly in the float range.
8629   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8630     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8631       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8632                                                        : ISD::ZERO_EXTEND;
8633       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8634     }
8635     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8636       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8637     if (SrcVT == VT)
8638       return Src;
8639     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8640   }
8641   return SDValue();
8642 }
8643
8644 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8645   SDValue N0 = N->getOperand(0);
8646   EVT VT = N->getValueType(0);
8647
8648   // fold (fp_to_sint c1fp) -> c1
8649   if (isConstantFPBuildVectorOrConstantFP(N0))
8650     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8651
8652   return FoldIntToFPToInt(N, DAG);
8653 }
8654
8655 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8656   SDValue N0 = N->getOperand(0);
8657   EVT VT = N->getValueType(0);
8658
8659   // fold (fp_to_uint c1fp) -> c1
8660   if (isConstantFPBuildVectorOrConstantFP(N0))
8661     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8662
8663   return FoldIntToFPToInt(N, DAG);
8664 }
8665
8666 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8667   SDValue N0 = N->getOperand(0);
8668   SDValue N1 = N->getOperand(1);
8669   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8670   EVT VT = N->getValueType(0);
8671
8672   // fold (fp_round c1fp) -> c1fp
8673   if (N0CFP)
8674     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8675
8676   // fold (fp_round (fp_extend x)) -> x
8677   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8678     return N0.getOperand(0);
8679
8680   // fold (fp_round (fp_round x)) -> (fp_round x)
8681   if (N0.getOpcode() == ISD::FP_ROUND) {
8682     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8683     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8684     // If the first fp_round isn't a value preserving truncation, it might
8685     // introduce a tie in the second fp_round, that wouldn't occur in the
8686     // single-step fp_round we want to fold to.
8687     // In other words, double rounding isn't the same as rounding.
8688     // Also, this is a value preserving truncation iff both fp_round's are.
8689     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8690       SDLoc DL(N);
8691       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8692                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8693     }
8694   }
8695
8696   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8697   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8698     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8699                               N0.getOperand(0), N1);
8700     AddToWorklist(Tmp.getNode());
8701     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8702                        Tmp, N0.getOperand(1));
8703   }
8704
8705   return SDValue();
8706 }
8707
8708 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8709   SDValue N0 = N->getOperand(0);
8710   EVT VT = N->getValueType(0);
8711   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8712   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8713
8714   // fold (fp_round_inreg c1fp) -> c1fp
8715   if (N0CFP && isTypeLegal(EVT)) {
8716     SDLoc DL(N);
8717     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8718     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8719   }
8720
8721   return SDValue();
8722 }
8723
8724 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8725   SDValue N0 = N->getOperand(0);
8726   EVT VT = N->getValueType(0);
8727
8728   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8729   if (N->hasOneUse() &&
8730       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8731     return SDValue();
8732
8733   // fold (fp_extend c1fp) -> c1fp
8734   if (isConstantFPBuildVectorOrConstantFP(N0))
8735     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8736
8737   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8738   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8739       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8740     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8741
8742   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8743   // value of X.
8744   if (N0.getOpcode() == ISD::FP_ROUND
8745       && N0.getNode()->getConstantOperandVal(1) == 1) {
8746     SDValue In = N0.getOperand(0);
8747     if (In.getValueType() == VT) return In;
8748     if (VT.bitsLT(In.getValueType()))
8749       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8750                          In, N0.getOperand(1));
8751     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8752   }
8753
8754   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8755   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8756        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8757     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8758     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8759                                      LN0->getChain(),
8760                                      LN0->getBasePtr(), N0.getValueType(),
8761                                      LN0->getMemOperand());
8762     CombineTo(N, ExtLoad);
8763     CombineTo(N0.getNode(),
8764               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8765                           N0.getValueType(), ExtLoad,
8766                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8767               ExtLoad.getValue(1));
8768     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8769   }
8770
8771   return SDValue();
8772 }
8773
8774 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8775   SDValue N0 = N->getOperand(0);
8776   EVT VT = N->getValueType(0);
8777
8778   // fold (fceil c1) -> fceil(c1)
8779   if (isConstantFPBuildVectorOrConstantFP(N0))
8780     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8781
8782   return SDValue();
8783 }
8784
8785 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8786   SDValue N0 = N->getOperand(0);
8787   EVT VT = N->getValueType(0);
8788
8789   // fold (ftrunc c1) -> ftrunc(c1)
8790   if (isConstantFPBuildVectorOrConstantFP(N0))
8791     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8792
8793   return SDValue();
8794 }
8795
8796 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8797   SDValue N0 = N->getOperand(0);
8798   EVT VT = N->getValueType(0);
8799
8800   // fold (ffloor c1) -> ffloor(c1)
8801   if (isConstantFPBuildVectorOrConstantFP(N0))
8802     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8803
8804   return SDValue();
8805 }
8806
8807 // FIXME: FNEG and FABS have a lot in common; refactor.
8808 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8809   SDValue N0 = N->getOperand(0);
8810   EVT VT = N->getValueType(0);
8811
8812   // Constant fold FNEG.
8813   if (isConstantFPBuildVectorOrConstantFP(N0))
8814     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8815
8816   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8817                          &DAG.getTarget().Options))
8818     return GetNegatedExpression(N0, DAG, LegalOperations);
8819
8820   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8821   // constant pool values.
8822   if (!TLI.isFNegFree(VT) &&
8823       N0.getOpcode() == ISD::BITCAST &&
8824       N0.getNode()->hasOneUse()) {
8825     SDValue Int = N0.getOperand(0);
8826     EVT IntVT = Int.getValueType();
8827     if (IntVT.isInteger() && !IntVT.isVector()) {
8828       APInt SignMask;
8829       if (N0.getValueType().isVector()) {
8830         // For a vector, get a mask such as 0x80... per scalar element
8831         // and splat it.
8832         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8833         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8834       } else {
8835         // For a scalar, just generate 0x80...
8836         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8837       }
8838       SDLoc DL0(N0);
8839       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8840                         DAG.getConstant(SignMask, DL0, IntVT));
8841       AddToWorklist(Int.getNode());
8842       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8843     }
8844   }
8845
8846   // (fneg (fmul c, x)) -> (fmul -c, x)
8847   if (N0.getOpcode() == ISD::FMUL &&
8848       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8849     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8850     if (CFP1) {
8851       APFloat CVal = CFP1->getValueAPF();
8852       CVal.changeSign();
8853       if (Level >= AfterLegalizeDAG &&
8854           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8855            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8856         return DAG.getNode(
8857             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8858             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8859     }
8860   }
8861
8862   return SDValue();
8863 }
8864
8865 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8866   SDValue N0 = N->getOperand(0);
8867   SDValue N1 = N->getOperand(1);
8868   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8869   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8870
8871   if (N0CFP && N1CFP) {
8872     const APFloat &C0 = N0CFP->getValueAPF();
8873     const APFloat &C1 = N1CFP->getValueAPF();
8874     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8875   }
8876
8877   if (N0CFP) {
8878     EVT VT = N->getValueType(0);
8879     // Canonicalize to constant on RHS.
8880     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8881   }
8882
8883   return SDValue();
8884 }
8885
8886 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8887   SDValue N0 = N->getOperand(0);
8888   SDValue N1 = N->getOperand(1);
8889   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8890   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8891
8892   if (N0CFP && N1CFP) {
8893     const APFloat &C0 = N0CFP->getValueAPF();
8894     const APFloat &C1 = N1CFP->getValueAPF();
8895     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8896   }
8897
8898   if (N0CFP) {
8899     EVT VT = N->getValueType(0);
8900     // Canonicalize to constant on RHS.
8901     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8902   }
8903
8904   return SDValue();
8905 }
8906
8907 SDValue DAGCombiner::visitFABS(SDNode *N) {
8908   SDValue N0 = N->getOperand(0);
8909   EVT VT = N->getValueType(0);
8910
8911   // fold (fabs c1) -> fabs(c1)
8912   if (isConstantFPBuildVectorOrConstantFP(N0))
8913     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8914
8915   // fold (fabs (fabs x)) -> (fabs x)
8916   if (N0.getOpcode() == ISD::FABS)
8917     return N->getOperand(0);
8918
8919   // fold (fabs (fneg x)) -> (fabs x)
8920   // fold (fabs (fcopysign x, y)) -> (fabs x)
8921   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8922     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8923
8924   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8925   // constant pool values.
8926   if (!TLI.isFAbsFree(VT) &&
8927       N0.getOpcode() == ISD::BITCAST &&
8928       N0.getNode()->hasOneUse()) {
8929     SDValue Int = N0.getOperand(0);
8930     EVT IntVT = Int.getValueType();
8931     if (IntVT.isInteger() && !IntVT.isVector()) {
8932       APInt SignMask;
8933       if (N0.getValueType().isVector()) {
8934         // For a vector, get a mask such as 0x7f... per scalar element
8935         // and splat it.
8936         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8937         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8938       } else {
8939         // For a scalar, just generate 0x7f...
8940         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8941       }
8942       SDLoc DL(N0);
8943       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8944                         DAG.getConstant(SignMask, DL, IntVT));
8945       AddToWorklist(Int.getNode());
8946       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8947     }
8948   }
8949
8950   return SDValue();
8951 }
8952
8953 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8954   SDValue Chain = N->getOperand(0);
8955   SDValue N1 = N->getOperand(1);
8956   SDValue N2 = N->getOperand(2);
8957
8958   // If N is a constant we could fold this into a fallthrough or unconditional
8959   // branch. However that doesn't happen very often in normal code, because
8960   // Instcombine/SimplifyCFG should have handled the available opportunities.
8961   // If we did this folding here, it would be necessary to update the
8962   // MachineBasicBlock CFG, which is awkward.
8963
8964   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8965   // on the target.
8966   if (N1.getOpcode() == ISD::SETCC &&
8967       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8968                                    N1.getOperand(0).getValueType())) {
8969     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8970                        Chain, N1.getOperand(2),
8971                        N1.getOperand(0), N1.getOperand(1), N2);
8972   }
8973
8974   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8975       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8976        (N1.getOperand(0).hasOneUse() &&
8977         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8978     SDNode *Trunc = nullptr;
8979     if (N1.getOpcode() == ISD::TRUNCATE) {
8980       // Look pass the truncate.
8981       Trunc = N1.getNode();
8982       N1 = N1.getOperand(0);
8983     }
8984
8985     // Match this pattern so that we can generate simpler code:
8986     //
8987     //   %a = ...
8988     //   %b = and i32 %a, 2
8989     //   %c = srl i32 %b, 1
8990     //   brcond i32 %c ...
8991     //
8992     // into
8993     //
8994     //   %a = ...
8995     //   %b = and i32 %a, 2
8996     //   %c = setcc eq %b, 0
8997     //   brcond %c ...
8998     //
8999     // This applies only when the AND constant value has one bit set and the
9000     // SRL constant is equal to the log2 of the AND constant. The back-end is
9001     // smart enough to convert the result into a TEST/JMP sequence.
9002     SDValue Op0 = N1.getOperand(0);
9003     SDValue Op1 = N1.getOperand(1);
9004
9005     if (Op0.getOpcode() == ISD::AND &&
9006         Op1.getOpcode() == ISD::Constant) {
9007       SDValue AndOp1 = Op0.getOperand(1);
9008
9009       if (AndOp1.getOpcode() == ISD::Constant) {
9010         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9011
9012         if (AndConst.isPowerOf2() &&
9013             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9014           SDLoc DL(N);
9015           SDValue SetCC =
9016             DAG.getSetCC(DL,
9017                          getSetCCResultType(Op0.getValueType()),
9018                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9019                          ISD::SETNE);
9020
9021           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9022                                           MVT::Other, Chain, SetCC, N2);
9023           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9024           // will convert it back to (X & C1) >> C2.
9025           CombineTo(N, NewBRCond, false);
9026           // Truncate is dead.
9027           if (Trunc)
9028             deleteAndRecombine(Trunc);
9029           // Replace the uses of SRL with SETCC
9030           WorklistRemover DeadNodes(*this);
9031           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9032           deleteAndRecombine(N1.getNode());
9033           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9034         }
9035       }
9036     }
9037
9038     if (Trunc)
9039       // Restore N1 if the above transformation doesn't match.
9040       N1 = N->getOperand(1);
9041   }
9042
9043   // Transform br(xor(x, y)) -> br(x != y)
9044   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9045   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9046     SDNode *TheXor = N1.getNode();
9047     SDValue Op0 = TheXor->getOperand(0);
9048     SDValue Op1 = TheXor->getOperand(1);
9049     if (Op0.getOpcode() == Op1.getOpcode()) {
9050       // Avoid missing important xor optimizations.
9051       if (SDValue Tmp = visitXOR(TheXor)) {
9052         if (Tmp.getNode() != TheXor) {
9053           DEBUG(dbgs() << "\nReplacing.8 ";
9054                 TheXor->dump(&DAG);
9055                 dbgs() << "\nWith: ";
9056                 Tmp.getNode()->dump(&DAG);
9057                 dbgs() << '\n');
9058           WorklistRemover DeadNodes(*this);
9059           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9060           deleteAndRecombine(TheXor);
9061           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9062                              MVT::Other, Chain, Tmp, N2);
9063         }
9064
9065         // visitXOR has changed XOR's operands or replaced the XOR completely,
9066         // bail out.
9067         return SDValue(N, 0);
9068       }
9069     }
9070
9071     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9072       bool Equal = false;
9073       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9074           Op0.getOpcode() == ISD::XOR) {
9075         TheXor = Op0.getNode();
9076         Equal = true;
9077       }
9078
9079       EVT SetCCVT = N1.getValueType();
9080       if (LegalTypes)
9081         SetCCVT = getSetCCResultType(SetCCVT);
9082       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9083                                    SetCCVT,
9084                                    Op0, Op1,
9085                                    Equal ? ISD::SETEQ : ISD::SETNE);
9086       // Replace the uses of XOR with SETCC
9087       WorklistRemover DeadNodes(*this);
9088       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9089       deleteAndRecombine(N1.getNode());
9090       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9091                          MVT::Other, Chain, SetCC, N2);
9092     }
9093   }
9094
9095   return SDValue();
9096 }
9097
9098 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9099 //
9100 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9101   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9102   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9103
9104   // If N is a constant we could fold this into a fallthrough or unconditional
9105   // branch. However that doesn't happen very often in normal code, because
9106   // Instcombine/SimplifyCFG should have handled the available opportunities.
9107   // If we did this folding here, it would be necessary to update the
9108   // MachineBasicBlock CFG, which is awkward.
9109
9110   // Use SimplifySetCC to simplify SETCC's.
9111   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9112                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9113                                false);
9114   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9115
9116   // fold to a simpler setcc
9117   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9118     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9119                        N->getOperand(0), Simp.getOperand(2),
9120                        Simp.getOperand(0), Simp.getOperand(1),
9121                        N->getOperand(4));
9122
9123   return SDValue();
9124 }
9125
9126 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9127 /// and that N may be folded in the load / store addressing mode.
9128 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9129                                     SelectionDAG &DAG,
9130                                     const TargetLowering &TLI) {
9131   EVT VT;
9132   unsigned AS;
9133
9134   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9135     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9136       return false;
9137     VT = LD->getMemoryVT();
9138     AS = LD->getAddressSpace();
9139   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9140     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9141       return false;
9142     VT = ST->getMemoryVT();
9143     AS = ST->getAddressSpace();
9144   } else
9145     return false;
9146
9147   TargetLowering::AddrMode AM;
9148   if (N->getOpcode() == ISD::ADD) {
9149     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9150     if (Offset)
9151       // [reg +/- imm]
9152       AM.BaseOffs = Offset->getSExtValue();
9153     else
9154       // [reg +/- reg]
9155       AM.Scale = 1;
9156   } else if (N->getOpcode() == ISD::SUB) {
9157     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9158     if (Offset)
9159       // [reg +/- imm]
9160       AM.BaseOffs = -Offset->getSExtValue();
9161     else
9162       // [reg +/- reg]
9163       AM.Scale = 1;
9164   } else
9165     return false;
9166
9167   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9168                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9169 }
9170
9171 /// Try turning a load/store into a pre-indexed load/store when the base
9172 /// pointer is an add or subtract and it has other uses besides the load/store.
9173 /// After the transformation, the new indexed load/store has effectively folded
9174 /// the add/subtract in and all of its other uses are redirected to the
9175 /// new load/store.
9176 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9177   if (Level < AfterLegalizeDAG)
9178     return false;
9179
9180   bool isLoad = true;
9181   SDValue Ptr;
9182   EVT VT;
9183   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9184     if (LD->isIndexed())
9185       return false;
9186     VT = LD->getMemoryVT();
9187     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9188         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9189       return false;
9190     Ptr = LD->getBasePtr();
9191   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9192     if (ST->isIndexed())
9193       return false;
9194     VT = ST->getMemoryVT();
9195     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9196         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9197       return false;
9198     Ptr = ST->getBasePtr();
9199     isLoad = false;
9200   } else {
9201     return false;
9202   }
9203
9204   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9205   // out.  There is no reason to make this a preinc/predec.
9206   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9207       Ptr.getNode()->hasOneUse())
9208     return false;
9209
9210   // Ask the target to do addressing mode selection.
9211   SDValue BasePtr;
9212   SDValue Offset;
9213   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9214   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9215     return false;
9216
9217   // Backends without true r+i pre-indexed forms may need to pass a
9218   // constant base with a variable offset so that constant coercion
9219   // will work with the patterns in canonical form.
9220   bool Swapped = false;
9221   if (isa<ConstantSDNode>(BasePtr)) {
9222     std::swap(BasePtr, Offset);
9223     Swapped = true;
9224   }
9225
9226   // Don't create a indexed load / store with zero offset.
9227   if (isNullConstant(Offset))
9228     return false;
9229
9230   // Try turning it into a pre-indexed load / store except when:
9231   // 1) The new base ptr is a frame index.
9232   // 2) If N is a store and the new base ptr is either the same as or is a
9233   //    predecessor of the value being stored.
9234   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9235   //    that would create a cycle.
9236   // 4) All uses are load / store ops that use it as old base ptr.
9237
9238   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9239   // (plus the implicit offset) to a register to preinc anyway.
9240   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9241     return false;
9242
9243   // Check #2.
9244   if (!isLoad) {
9245     SDValue Val = cast<StoreSDNode>(N)->getValue();
9246     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9247       return false;
9248   }
9249
9250   // If the offset is a constant, there may be other adds of constants that
9251   // can be folded with this one. We should do this to avoid having to keep
9252   // a copy of the original base pointer.
9253   SmallVector<SDNode *, 16> OtherUses;
9254   if (isa<ConstantSDNode>(Offset))
9255     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9256                               UE = BasePtr.getNode()->use_end();
9257          UI != UE; ++UI) {
9258       SDUse &Use = UI.getUse();
9259       // Skip the use that is Ptr and uses of other results from BasePtr's
9260       // node (important for nodes that return multiple results).
9261       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9262         continue;
9263
9264       if (Use.getUser()->isPredecessorOf(N))
9265         continue;
9266
9267       if (Use.getUser()->getOpcode() != ISD::ADD &&
9268           Use.getUser()->getOpcode() != ISD::SUB) {
9269         OtherUses.clear();
9270         break;
9271       }
9272
9273       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9274       if (!isa<ConstantSDNode>(Op1)) {
9275         OtherUses.clear();
9276         break;
9277       }
9278
9279       // FIXME: In some cases, we can be smarter about this.
9280       if (Op1.getValueType() != Offset.getValueType()) {
9281         OtherUses.clear();
9282         break;
9283       }
9284
9285       OtherUses.push_back(Use.getUser());
9286     }
9287
9288   if (Swapped)
9289     std::swap(BasePtr, Offset);
9290
9291   // Now check for #3 and #4.
9292   bool RealUse = false;
9293
9294   // Caches for hasPredecessorHelper
9295   SmallPtrSet<const SDNode *, 32> Visited;
9296   SmallVector<const SDNode *, 16> Worklist;
9297
9298   for (SDNode *Use : Ptr.getNode()->uses()) {
9299     if (Use == N)
9300       continue;
9301     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9302       return false;
9303
9304     // If Ptr may be folded in addressing mode of other use, then it's
9305     // not profitable to do this transformation.
9306     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9307       RealUse = true;
9308   }
9309
9310   if (!RealUse)
9311     return false;
9312
9313   SDValue Result;
9314   if (isLoad)
9315     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9316                                 BasePtr, Offset, AM);
9317   else
9318     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9319                                  BasePtr, Offset, AM);
9320   ++PreIndexedNodes;
9321   ++NodesCombined;
9322   DEBUG(dbgs() << "\nReplacing.4 ";
9323         N->dump(&DAG);
9324         dbgs() << "\nWith: ";
9325         Result.getNode()->dump(&DAG);
9326         dbgs() << '\n');
9327   WorklistRemover DeadNodes(*this);
9328   if (isLoad) {
9329     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9330     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9331   } else {
9332     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9333   }
9334
9335   // Finally, since the node is now dead, remove it from the graph.
9336   deleteAndRecombine(N);
9337
9338   if (Swapped)
9339     std::swap(BasePtr, Offset);
9340
9341   // Replace other uses of BasePtr that can be updated to use Ptr
9342   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9343     unsigned OffsetIdx = 1;
9344     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9345       OffsetIdx = 0;
9346     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9347            BasePtr.getNode() && "Expected BasePtr operand");
9348
9349     // We need to replace ptr0 in the following expression:
9350     //   x0 * offset0 + y0 * ptr0 = t0
9351     // knowing that
9352     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9353     //
9354     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9355     // indexed load/store and the expresion that needs to be re-written.
9356     //
9357     // Therefore, we have:
9358     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9359
9360     ConstantSDNode *CN =
9361       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9362     int X0, X1, Y0, Y1;
9363     APInt Offset0 = CN->getAPIntValue();
9364     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9365
9366     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9367     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9368     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9369     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9370
9371     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9372
9373     APInt CNV = Offset0;
9374     if (X0 < 0) CNV = -CNV;
9375     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9376     else CNV = CNV - Offset1;
9377
9378     SDLoc DL(OtherUses[i]);
9379
9380     // We can now generate the new expression.
9381     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9382     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9383
9384     SDValue NewUse = DAG.getNode(Opcode,
9385                                  DL,
9386                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9387     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9388     deleteAndRecombine(OtherUses[i]);
9389   }
9390
9391   // Replace the uses of Ptr with uses of the updated base value.
9392   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9393   deleteAndRecombine(Ptr.getNode());
9394
9395   return true;
9396 }
9397
9398 /// Try to combine a load/store with a add/sub of the base pointer node into a
9399 /// post-indexed load/store. The transformation folded the add/subtract into the
9400 /// new indexed load/store effectively and all of its uses are redirected to the
9401 /// new load/store.
9402 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9403   if (Level < AfterLegalizeDAG)
9404     return false;
9405
9406   bool isLoad = true;
9407   SDValue Ptr;
9408   EVT VT;
9409   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9410     if (LD->isIndexed())
9411       return false;
9412     VT = LD->getMemoryVT();
9413     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9414         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9415       return false;
9416     Ptr = LD->getBasePtr();
9417   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9418     if (ST->isIndexed())
9419       return false;
9420     VT = ST->getMemoryVT();
9421     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9422         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9423       return false;
9424     Ptr = ST->getBasePtr();
9425     isLoad = false;
9426   } else {
9427     return false;
9428   }
9429
9430   if (Ptr.getNode()->hasOneUse())
9431     return false;
9432
9433   for (SDNode *Op : Ptr.getNode()->uses()) {
9434     if (Op == N ||
9435         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9436       continue;
9437
9438     SDValue BasePtr;
9439     SDValue Offset;
9440     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9441     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9442       // Don't create a indexed load / store with zero offset.
9443       if (isNullConstant(Offset))
9444         continue;
9445
9446       // Try turning it into a post-indexed load / store except when
9447       // 1) All uses are load / store ops that use it as base ptr (and
9448       //    it may be folded as addressing mmode).
9449       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9450       //    nor a successor of N. Otherwise, if Op is folded that would
9451       //    create a cycle.
9452
9453       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9454         continue;
9455
9456       // Check for #1.
9457       bool TryNext = false;
9458       for (SDNode *Use : BasePtr.getNode()->uses()) {
9459         if (Use == Ptr.getNode())
9460           continue;
9461
9462         // If all the uses are load / store addresses, then don't do the
9463         // transformation.
9464         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9465           bool RealUse = false;
9466           for (SDNode *UseUse : Use->uses()) {
9467             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9468               RealUse = true;
9469           }
9470
9471           if (!RealUse) {
9472             TryNext = true;
9473             break;
9474           }
9475         }
9476       }
9477
9478       if (TryNext)
9479         continue;
9480
9481       // Check for #2
9482       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9483         SDValue Result = isLoad
9484           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9485                                BasePtr, Offset, AM)
9486           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9487                                 BasePtr, Offset, AM);
9488         ++PostIndexedNodes;
9489         ++NodesCombined;
9490         DEBUG(dbgs() << "\nReplacing.5 ";
9491               N->dump(&DAG);
9492               dbgs() << "\nWith: ";
9493               Result.getNode()->dump(&DAG);
9494               dbgs() << '\n');
9495         WorklistRemover DeadNodes(*this);
9496         if (isLoad) {
9497           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9498           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9499         } else {
9500           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9501         }
9502
9503         // Finally, since the node is now dead, remove it from the graph.
9504         deleteAndRecombine(N);
9505
9506         // Replace the uses of Use with uses of the updated base value.
9507         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9508                                       Result.getValue(isLoad ? 1 : 0));
9509         deleteAndRecombine(Op);
9510         return true;
9511       }
9512     }
9513   }
9514
9515   return false;
9516 }
9517
9518 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9519 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9520   ISD::MemIndexedMode AM = LD->getAddressingMode();
9521   assert(AM != ISD::UNINDEXED);
9522   SDValue BP = LD->getOperand(1);
9523   SDValue Inc = LD->getOperand(2);
9524
9525   // Some backends use TargetConstants for load offsets, but don't expect
9526   // TargetConstants in general ADD nodes. We can convert these constants into
9527   // regular Constants (if the constant is not opaque).
9528   assert((Inc.getOpcode() != ISD::TargetConstant ||
9529           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9530          "Cannot split out indexing using opaque target constants");
9531   if (Inc.getOpcode() == ISD::TargetConstant) {
9532     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9533     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9534                           ConstInc->getValueType(0));
9535   }
9536
9537   unsigned Opc =
9538       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9539   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9540 }
9541
9542 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9543   LoadSDNode *LD  = cast<LoadSDNode>(N);
9544   SDValue Chain = LD->getChain();
9545   SDValue Ptr   = LD->getBasePtr();
9546
9547   // If load is not volatile and there are no uses of the loaded value (and
9548   // the updated indexed value in case of indexed loads), change uses of the
9549   // chain value into uses of the chain input (i.e. delete the dead load).
9550   if (!LD->isVolatile()) {
9551     if (N->getValueType(1) == MVT::Other) {
9552       // Unindexed loads.
9553       if (!N->hasAnyUseOfValue(0)) {
9554         // It's not safe to use the two value CombineTo variant here. e.g.
9555         // v1, chain2 = load chain1, loc
9556         // v2, chain3 = load chain2, loc
9557         // v3         = add v2, c
9558         // Now we replace use of chain2 with chain1.  This makes the second load
9559         // isomorphic to the one we are deleting, and thus makes this load live.
9560         DEBUG(dbgs() << "\nReplacing.6 ";
9561               N->dump(&DAG);
9562               dbgs() << "\nWith chain: ";
9563               Chain.getNode()->dump(&DAG);
9564               dbgs() << "\n");
9565         WorklistRemover DeadNodes(*this);
9566         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9567
9568         if (N->use_empty())
9569           deleteAndRecombine(N);
9570
9571         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9572       }
9573     } else {
9574       // Indexed loads.
9575       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9576
9577       // If this load has an opaque TargetConstant offset, then we cannot split
9578       // the indexing into an add/sub directly (that TargetConstant may not be
9579       // valid for a different type of node, and we cannot convert an opaque
9580       // target constant into a regular constant).
9581       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9582                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9583
9584       if (!N->hasAnyUseOfValue(0) &&
9585           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9586         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9587         SDValue Index;
9588         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9589           Index = SplitIndexingFromLoad(LD);
9590           // Try to fold the base pointer arithmetic into subsequent loads and
9591           // stores.
9592           AddUsersToWorklist(N);
9593         } else
9594           Index = DAG.getUNDEF(N->getValueType(1));
9595         DEBUG(dbgs() << "\nReplacing.7 ";
9596               N->dump(&DAG);
9597               dbgs() << "\nWith: ";
9598               Undef.getNode()->dump(&DAG);
9599               dbgs() << " and 2 other values\n");
9600         WorklistRemover DeadNodes(*this);
9601         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9602         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9603         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9604         deleteAndRecombine(N);
9605         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9606       }
9607     }
9608   }
9609
9610   // If this load is directly stored, replace the load value with the stored
9611   // value.
9612   // TODO: Handle store large -> read small portion.
9613   // TODO: Handle TRUNCSTORE/LOADEXT
9614   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9615     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9616       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9617       if (PrevST->getBasePtr() == Ptr &&
9618           PrevST->getValue().getValueType() == N->getValueType(0))
9619       return CombineTo(N, Chain.getOperand(1), Chain);
9620     }
9621   }
9622
9623   // Try to infer better alignment information than the load already has.
9624   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9625     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9626       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9627         SDValue NewLoad =
9628                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9629                               LD->getValueType(0),
9630                               Chain, Ptr, LD->getPointerInfo(),
9631                               LD->getMemoryVT(),
9632                               LD->isVolatile(), LD->isNonTemporal(),
9633                               LD->isInvariant(), Align, LD->getAAInfo());
9634         if (NewLoad.getNode() != N)
9635           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9636       }
9637     }
9638   }
9639
9640   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9641                                                   : DAG.getSubtarget().useAA();
9642 #ifndef NDEBUG
9643   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9644       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9645     UseAA = false;
9646 #endif
9647   if (UseAA && LD->isUnindexed()) {
9648     // Walk up chain skipping non-aliasing memory nodes.
9649     SDValue BetterChain = FindBetterChain(N, Chain);
9650
9651     // If there is a better chain.
9652     if (Chain != BetterChain) {
9653       SDValue ReplLoad;
9654
9655       // Replace the chain to void dependency.
9656       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9657         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9658                                BetterChain, Ptr, LD->getMemOperand());
9659       } else {
9660         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9661                                   LD->getValueType(0),
9662                                   BetterChain, Ptr, LD->getMemoryVT(),
9663                                   LD->getMemOperand());
9664       }
9665
9666       // Create token factor to keep old chain connected.
9667       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9668                                   MVT::Other, Chain, ReplLoad.getValue(1));
9669
9670       // Make sure the new and old chains are cleaned up.
9671       AddToWorklist(Token.getNode());
9672
9673       // Replace uses with load result and token factor. Don't add users
9674       // to work list.
9675       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9676     }
9677   }
9678
9679   // Try transforming N to an indexed load.
9680   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9681     return SDValue(N, 0);
9682
9683   // Try to slice up N to more direct loads if the slices are mapped to
9684   // different register banks or pairing can take place.
9685   if (SliceUpLoad(N))
9686     return SDValue(N, 0);
9687
9688   return SDValue();
9689 }
9690
9691 namespace {
9692 /// \brief Helper structure used to slice a load in smaller loads.
9693 /// Basically a slice is obtained from the following sequence:
9694 /// Origin = load Ty1, Base
9695 /// Shift = srl Ty1 Origin, CstTy Amount
9696 /// Inst = trunc Shift to Ty2
9697 ///
9698 /// Then, it will be rewriten into:
9699 /// Slice = load SliceTy, Base + SliceOffset
9700 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9701 ///
9702 /// SliceTy is deduced from the number of bits that are actually used to
9703 /// build Inst.
9704 struct LoadedSlice {
9705   /// \brief Helper structure used to compute the cost of a slice.
9706   struct Cost {
9707     /// Are we optimizing for code size.
9708     bool ForCodeSize;
9709     /// Various cost.
9710     unsigned Loads;
9711     unsigned Truncates;
9712     unsigned CrossRegisterBanksCopies;
9713     unsigned ZExts;
9714     unsigned Shift;
9715
9716     Cost(bool ForCodeSize = false)
9717         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9718           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9719
9720     /// \brief Get the cost of one isolated slice.
9721     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9722         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9723           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9724       EVT TruncType = LS.Inst->getValueType(0);
9725       EVT LoadedType = LS.getLoadedType();
9726       if (TruncType != LoadedType &&
9727           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9728         ZExts = 1;
9729     }
9730
9731     /// \brief Account for slicing gain in the current cost.
9732     /// Slicing provide a few gains like removing a shift or a
9733     /// truncate. This method allows to grow the cost of the original
9734     /// load with the gain from this slice.
9735     void addSliceGain(const LoadedSlice &LS) {
9736       // Each slice saves a truncate.
9737       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9738       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9739                               LS.Inst->getOperand(0).getValueType()))
9740         ++Truncates;
9741       // If there is a shift amount, this slice gets rid of it.
9742       if (LS.Shift)
9743         ++Shift;
9744       // If this slice can merge a cross register bank copy, account for it.
9745       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9746         ++CrossRegisterBanksCopies;
9747     }
9748
9749     Cost &operator+=(const Cost &RHS) {
9750       Loads += RHS.Loads;
9751       Truncates += RHS.Truncates;
9752       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9753       ZExts += RHS.ZExts;
9754       Shift += RHS.Shift;
9755       return *this;
9756     }
9757
9758     bool operator==(const Cost &RHS) const {
9759       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9760              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9761              ZExts == RHS.ZExts && Shift == RHS.Shift;
9762     }
9763
9764     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9765
9766     bool operator<(const Cost &RHS) const {
9767       // Assume cross register banks copies are as expensive as loads.
9768       // FIXME: Do we want some more target hooks?
9769       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9770       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9771       // Unless we are optimizing for code size, consider the
9772       // expensive operation first.
9773       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9774         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9775       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9776              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9777     }
9778
9779     bool operator>(const Cost &RHS) const { return RHS < *this; }
9780
9781     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9782
9783     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9784   };
9785   // The last instruction that represent the slice. This should be a
9786   // truncate instruction.
9787   SDNode *Inst;
9788   // The original load instruction.
9789   LoadSDNode *Origin;
9790   // The right shift amount in bits from the original load.
9791   unsigned Shift;
9792   // The DAG from which Origin came from.
9793   // This is used to get some contextual information about legal types, etc.
9794   SelectionDAG *DAG;
9795
9796   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9797               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9798       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9799
9800   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9801   /// \return Result is \p BitWidth and has used bits set to 1 and
9802   ///         not used bits set to 0.
9803   APInt getUsedBits() const {
9804     // Reproduce the trunc(lshr) sequence:
9805     // - Start from the truncated value.
9806     // - Zero extend to the desired bit width.
9807     // - Shift left.
9808     assert(Origin && "No original load to compare against.");
9809     unsigned BitWidth = Origin->getValueSizeInBits(0);
9810     assert(Inst && "This slice is not bound to an instruction");
9811     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9812            "Extracted slice is bigger than the whole type!");
9813     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9814     UsedBits.setAllBits();
9815     UsedBits = UsedBits.zext(BitWidth);
9816     UsedBits <<= Shift;
9817     return UsedBits;
9818   }
9819
9820   /// \brief Get the size of the slice to be loaded in bytes.
9821   unsigned getLoadedSize() const {
9822     unsigned SliceSize = getUsedBits().countPopulation();
9823     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9824     return SliceSize / 8;
9825   }
9826
9827   /// \brief Get the type that will be loaded for this slice.
9828   /// Note: This may not be the final type for the slice.
9829   EVT getLoadedType() const {
9830     assert(DAG && "Missing context");
9831     LLVMContext &Ctxt = *DAG->getContext();
9832     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9833   }
9834
9835   /// \brief Get the alignment of the load used for this slice.
9836   unsigned getAlignment() const {
9837     unsigned Alignment = Origin->getAlignment();
9838     unsigned Offset = getOffsetFromBase();
9839     if (Offset != 0)
9840       Alignment = MinAlign(Alignment, Alignment + Offset);
9841     return Alignment;
9842   }
9843
9844   /// \brief Check if this slice can be rewritten with legal operations.
9845   bool isLegal() const {
9846     // An invalid slice is not legal.
9847     if (!Origin || !Inst || !DAG)
9848       return false;
9849
9850     // Offsets are for indexed load only, we do not handle that.
9851     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9852       return false;
9853
9854     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9855
9856     // Check that the type is legal.
9857     EVT SliceType = getLoadedType();
9858     if (!TLI.isTypeLegal(SliceType))
9859       return false;
9860
9861     // Check that the load is legal for this type.
9862     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9863       return false;
9864
9865     // Check that the offset can be computed.
9866     // 1. Check its type.
9867     EVT PtrType = Origin->getBasePtr().getValueType();
9868     if (PtrType == MVT::Untyped || PtrType.isExtended())
9869       return false;
9870
9871     // 2. Check that it fits in the immediate.
9872     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9873       return false;
9874
9875     // 3. Check that the computation is legal.
9876     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9877       return false;
9878
9879     // Check that the zext is legal if it needs one.
9880     EVT TruncateType = Inst->getValueType(0);
9881     if (TruncateType != SliceType &&
9882         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9883       return false;
9884
9885     return true;
9886   }
9887
9888   /// \brief Get the offset in bytes of this slice in the original chunk of
9889   /// bits.
9890   /// \pre DAG != nullptr.
9891   uint64_t getOffsetFromBase() const {
9892     assert(DAG && "Missing context.");
9893     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9894     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9895     uint64_t Offset = Shift / 8;
9896     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9897     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9898            "The size of the original loaded type is not a multiple of a"
9899            " byte.");
9900     // If Offset is bigger than TySizeInBytes, it means we are loading all
9901     // zeros. This should have been optimized before in the process.
9902     assert(TySizeInBytes > Offset &&
9903            "Invalid shift amount for given loaded size");
9904     if (IsBigEndian)
9905       Offset = TySizeInBytes - Offset - getLoadedSize();
9906     return Offset;
9907   }
9908
9909   /// \brief Generate the sequence of instructions to load the slice
9910   /// represented by this object and redirect the uses of this slice to
9911   /// this new sequence of instructions.
9912   /// \pre this->Inst && this->Origin are valid Instructions and this
9913   /// object passed the legal check: LoadedSlice::isLegal returned true.
9914   /// \return The last instruction of the sequence used to load the slice.
9915   SDValue loadSlice() const {
9916     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9917     const SDValue &OldBaseAddr = Origin->getBasePtr();
9918     SDValue BaseAddr = OldBaseAddr;
9919     // Get the offset in that chunk of bytes w.r.t. the endianess.
9920     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9921     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9922     if (Offset) {
9923       // BaseAddr = BaseAddr + Offset.
9924       EVT ArithType = BaseAddr.getValueType();
9925       SDLoc DL(Origin);
9926       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9927                               DAG->getConstant(Offset, DL, ArithType));
9928     }
9929
9930     // Create the type of the loaded slice according to its size.
9931     EVT SliceType = getLoadedType();
9932
9933     // Create the load for the slice.
9934     SDValue LastInst = DAG->getLoad(
9935         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9936         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9937         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9938     // If the final type is not the same as the loaded type, this means that
9939     // we have to pad with zero. Create a zero extend for that.
9940     EVT FinalType = Inst->getValueType(0);
9941     if (SliceType != FinalType)
9942       LastInst =
9943           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9944     return LastInst;
9945   }
9946
9947   /// \brief Check if this slice can be merged with an expensive cross register
9948   /// bank copy. E.g.,
9949   /// i = load i32
9950   /// f = bitcast i32 i to float
9951   bool canMergeExpensiveCrossRegisterBankCopy() const {
9952     if (!Inst || !Inst->hasOneUse())
9953       return false;
9954     SDNode *Use = *Inst->use_begin();
9955     if (Use->getOpcode() != ISD::BITCAST)
9956       return false;
9957     assert(DAG && "Missing context");
9958     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9959     EVT ResVT = Use->getValueType(0);
9960     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9961     const TargetRegisterClass *ArgRC =
9962         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9963     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9964       return false;
9965
9966     // At this point, we know that we perform a cross-register-bank copy.
9967     // Check if it is expensive.
9968     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9969     // Assume bitcasts are cheap, unless both register classes do not
9970     // explicitly share a common sub class.
9971     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9972       return false;
9973
9974     // Check if it will be merged with the load.
9975     // 1. Check the alignment constraint.
9976     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
9977         ResVT.getTypeForEVT(*DAG->getContext()));
9978
9979     if (RequiredAlignment > getAlignment())
9980       return false;
9981
9982     // 2. Check that the load is a legal operation for that type.
9983     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9984       return false;
9985
9986     // 3. Check that we do not have a zext in the way.
9987     if (Inst->getValueType(0) != getLoadedType())
9988       return false;
9989
9990     return true;
9991   }
9992 };
9993 }
9994
9995 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9996 /// \p UsedBits looks like 0..0 1..1 0..0.
9997 static bool areUsedBitsDense(const APInt &UsedBits) {
9998   // If all the bits are one, this is dense!
9999   if (UsedBits.isAllOnesValue())
10000     return true;
10001
10002   // Get rid of the unused bits on the right.
10003   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10004   // Get rid of the unused bits on the left.
10005   if (NarrowedUsedBits.countLeadingZeros())
10006     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10007   // Check that the chunk of bits is completely used.
10008   return NarrowedUsedBits.isAllOnesValue();
10009 }
10010
10011 /// \brief Check whether or not \p First and \p Second are next to each other
10012 /// in memory. This means that there is no hole between the bits loaded
10013 /// by \p First and the bits loaded by \p Second.
10014 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10015                                      const LoadedSlice &Second) {
10016   assert(First.Origin == Second.Origin && First.Origin &&
10017          "Unable to match different memory origins.");
10018   APInt UsedBits = First.getUsedBits();
10019   assert((UsedBits & Second.getUsedBits()) == 0 &&
10020          "Slices are not supposed to overlap.");
10021   UsedBits |= Second.getUsedBits();
10022   return areUsedBitsDense(UsedBits);
10023 }
10024
10025 /// \brief Adjust the \p GlobalLSCost according to the target
10026 /// paring capabilities and the layout of the slices.
10027 /// \pre \p GlobalLSCost should account for at least as many loads as
10028 /// there is in the slices in \p LoadedSlices.
10029 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10030                                  LoadedSlice::Cost &GlobalLSCost) {
10031   unsigned NumberOfSlices = LoadedSlices.size();
10032   // If there is less than 2 elements, no pairing is possible.
10033   if (NumberOfSlices < 2)
10034     return;
10035
10036   // Sort the slices so that elements that are likely to be next to each
10037   // other in memory are next to each other in the list.
10038   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10039             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10040     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10041     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10042   });
10043   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10044   // First (resp. Second) is the first (resp. Second) potentially candidate
10045   // to be placed in a paired load.
10046   const LoadedSlice *First = nullptr;
10047   const LoadedSlice *Second = nullptr;
10048   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10049                 // Set the beginning of the pair.
10050                                                            First = Second) {
10051
10052     Second = &LoadedSlices[CurrSlice];
10053
10054     // If First is NULL, it means we start a new pair.
10055     // Get to the next slice.
10056     if (!First)
10057       continue;
10058
10059     EVT LoadedType = First->getLoadedType();
10060
10061     // If the types of the slices are different, we cannot pair them.
10062     if (LoadedType != Second->getLoadedType())
10063       continue;
10064
10065     // Check if the target supplies paired loads for this type.
10066     unsigned RequiredAlignment = 0;
10067     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10068       // move to the next pair, this type is hopeless.
10069       Second = nullptr;
10070       continue;
10071     }
10072     // Check if we meet the alignment requirement.
10073     if (RequiredAlignment > First->getAlignment())
10074       continue;
10075
10076     // Check that both loads are next to each other in memory.
10077     if (!areSlicesNextToEachOther(*First, *Second))
10078       continue;
10079
10080     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10081     --GlobalLSCost.Loads;
10082     // Move to the next pair.
10083     Second = nullptr;
10084   }
10085 }
10086
10087 /// \brief Check the profitability of all involved LoadedSlice.
10088 /// Currently, it is considered profitable if there is exactly two
10089 /// involved slices (1) which are (2) next to each other in memory, and
10090 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10091 ///
10092 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10093 /// the elements themselves.
10094 ///
10095 /// FIXME: When the cost model will be mature enough, we can relax
10096 /// constraints (1) and (2).
10097 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10098                                 const APInt &UsedBits, bool ForCodeSize) {
10099   unsigned NumberOfSlices = LoadedSlices.size();
10100   if (StressLoadSlicing)
10101     return NumberOfSlices > 1;
10102
10103   // Check (1).
10104   if (NumberOfSlices != 2)
10105     return false;
10106
10107   // Check (2).
10108   if (!areUsedBitsDense(UsedBits))
10109     return false;
10110
10111   // Check (3).
10112   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10113   // The original code has one big load.
10114   OrigCost.Loads = 1;
10115   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10116     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10117     // Accumulate the cost of all the slices.
10118     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10119     GlobalSlicingCost += SliceCost;
10120
10121     // Account as cost in the original configuration the gain obtained
10122     // with the current slices.
10123     OrigCost.addSliceGain(LS);
10124   }
10125
10126   // If the target supports paired load, adjust the cost accordingly.
10127   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10128   return OrigCost > GlobalSlicingCost;
10129 }
10130
10131 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10132 /// operations, split it in the various pieces being extracted.
10133 ///
10134 /// This sort of thing is introduced by SROA.
10135 /// This slicing takes care not to insert overlapping loads.
10136 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10137 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10138   if (Level < AfterLegalizeDAG)
10139     return false;
10140
10141   LoadSDNode *LD = cast<LoadSDNode>(N);
10142   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10143       !LD->getValueType(0).isInteger())
10144     return false;
10145
10146   // Keep track of already used bits to detect overlapping values.
10147   // In that case, we will just abort the transformation.
10148   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10149
10150   SmallVector<LoadedSlice, 4> LoadedSlices;
10151
10152   // Check if this load is used as several smaller chunks of bits.
10153   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10154   // of computation for each trunc.
10155   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10156        UI != UIEnd; ++UI) {
10157     // Skip the uses of the chain.
10158     if (UI.getUse().getResNo() != 0)
10159       continue;
10160
10161     SDNode *User = *UI;
10162     unsigned Shift = 0;
10163
10164     // Check if this is a trunc(lshr).
10165     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10166         isa<ConstantSDNode>(User->getOperand(1))) {
10167       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10168       User = *User->use_begin();
10169     }
10170
10171     // At this point, User is a Truncate, iff we encountered, trunc or
10172     // trunc(lshr).
10173     if (User->getOpcode() != ISD::TRUNCATE)
10174       return false;
10175
10176     // The width of the type must be a power of 2 and greater than 8-bits.
10177     // Otherwise the load cannot be represented in LLVM IR.
10178     // Moreover, if we shifted with a non-8-bits multiple, the slice
10179     // will be across several bytes. We do not support that.
10180     unsigned Width = User->getValueSizeInBits(0);
10181     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10182       return 0;
10183
10184     // Build the slice for this chain of computations.
10185     LoadedSlice LS(User, LD, Shift, &DAG);
10186     APInt CurrentUsedBits = LS.getUsedBits();
10187
10188     // Check if this slice overlaps with another.
10189     if ((CurrentUsedBits & UsedBits) != 0)
10190       return false;
10191     // Update the bits used globally.
10192     UsedBits |= CurrentUsedBits;
10193
10194     // Check if the new slice would be legal.
10195     if (!LS.isLegal())
10196       return false;
10197
10198     // Record the slice.
10199     LoadedSlices.push_back(LS);
10200   }
10201
10202   // Abort slicing if it does not seem to be profitable.
10203   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10204     return false;
10205
10206   ++SlicedLoads;
10207
10208   // Rewrite each chain to use an independent load.
10209   // By construction, each chain can be represented by a unique load.
10210
10211   // Prepare the argument for the new token factor for all the slices.
10212   SmallVector<SDValue, 8> ArgChains;
10213   for (SmallVectorImpl<LoadedSlice>::const_iterator
10214            LSIt = LoadedSlices.begin(),
10215            LSItEnd = LoadedSlices.end();
10216        LSIt != LSItEnd; ++LSIt) {
10217     SDValue SliceInst = LSIt->loadSlice();
10218     CombineTo(LSIt->Inst, SliceInst, true);
10219     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10220       SliceInst = SliceInst.getOperand(0);
10221     assert(SliceInst->getOpcode() == ISD::LOAD &&
10222            "It takes more than a zext to get to the loaded slice!!");
10223     ArgChains.push_back(SliceInst.getValue(1));
10224   }
10225
10226   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10227                               ArgChains);
10228   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10229   return true;
10230 }
10231
10232 /// Check to see if V is (and load (ptr), imm), where the load is having
10233 /// specific bytes cleared out.  If so, return the byte size being masked out
10234 /// and the shift amount.
10235 static std::pair<unsigned, unsigned>
10236 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10237   std::pair<unsigned, unsigned> Result(0, 0);
10238
10239   // Check for the structure we're looking for.
10240   if (V->getOpcode() != ISD::AND ||
10241       !isa<ConstantSDNode>(V->getOperand(1)) ||
10242       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10243     return Result;
10244
10245   // Check the chain and pointer.
10246   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10247   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10248
10249   // The store should be chained directly to the load or be an operand of a
10250   // tokenfactor.
10251   if (LD == Chain.getNode())
10252     ; // ok.
10253   else if (Chain->getOpcode() != ISD::TokenFactor)
10254     return Result; // Fail.
10255   else {
10256     bool isOk = false;
10257     for (const SDValue &ChainOp : Chain->op_values())
10258       if (ChainOp.getNode() == LD) {
10259         isOk = true;
10260         break;
10261       }
10262     if (!isOk) return Result;
10263   }
10264
10265   // This only handles simple types.
10266   if (V.getValueType() != MVT::i16 &&
10267       V.getValueType() != MVT::i32 &&
10268       V.getValueType() != MVT::i64)
10269     return Result;
10270
10271   // Check the constant mask.  Invert it so that the bits being masked out are
10272   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10273   // follow the sign bit for uniformity.
10274   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10275   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10276   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10277   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10278   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10279   if (NotMaskLZ == 64) return Result;  // All zero mask.
10280
10281   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10282   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10283     return Result;
10284
10285   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10286   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10287     NotMaskLZ -= 64-V.getValueSizeInBits();
10288
10289   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10290   switch (MaskedBytes) {
10291   case 1:
10292   case 2:
10293   case 4: break;
10294   default: return Result; // All one mask, or 5-byte mask.
10295   }
10296
10297   // Verify that the first bit starts at a multiple of mask so that the access
10298   // is aligned the same as the access width.
10299   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10300
10301   Result.first = MaskedBytes;
10302   Result.second = NotMaskTZ/8;
10303   return Result;
10304 }
10305
10306
10307 /// Check to see if IVal is something that provides a value as specified by
10308 /// MaskInfo. If so, replace the specified store with a narrower store of
10309 /// truncated IVal.
10310 static SDNode *
10311 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10312                                 SDValue IVal, StoreSDNode *St,
10313                                 DAGCombiner *DC) {
10314   unsigned NumBytes = MaskInfo.first;
10315   unsigned ByteShift = MaskInfo.second;
10316   SelectionDAG &DAG = DC->getDAG();
10317
10318   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10319   // that uses this.  If not, this is not a replacement.
10320   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10321                                   ByteShift*8, (ByteShift+NumBytes)*8);
10322   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10323
10324   // Check that it is legal on the target to do this.  It is legal if the new
10325   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10326   // legalization.
10327   MVT VT = MVT::getIntegerVT(NumBytes*8);
10328   if (!DC->isTypeLegal(VT))
10329     return nullptr;
10330
10331   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10332   // shifted by ByteShift and truncated down to NumBytes.
10333   if (ByteShift) {
10334     SDLoc DL(IVal);
10335     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10336                        DAG.getConstant(ByteShift*8, DL,
10337                                     DC->getShiftAmountTy(IVal.getValueType())));
10338   }
10339
10340   // Figure out the offset for the store and the alignment of the access.
10341   unsigned StOffset;
10342   unsigned NewAlign = St->getAlignment();
10343
10344   if (DAG.getDataLayout().isLittleEndian())
10345     StOffset = ByteShift;
10346   else
10347     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10348
10349   SDValue Ptr = St->getBasePtr();
10350   if (StOffset) {
10351     SDLoc DL(IVal);
10352     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10353                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10354     NewAlign = MinAlign(NewAlign, StOffset);
10355   }
10356
10357   // Truncate down to the new size.
10358   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10359
10360   ++OpsNarrowed;
10361   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10362                       St->getPointerInfo().getWithOffset(StOffset),
10363                       false, false, NewAlign).getNode();
10364 }
10365
10366
10367 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10368 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10369 /// narrowing the load and store if it would end up being a win for performance
10370 /// or code size.
10371 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10372   StoreSDNode *ST  = cast<StoreSDNode>(N);
10373   if (ST->isVolatile())
10374     return SDValue();
10375
10376   SDValue Chain = ST->getChain();
10377   SDValue Value = ST->getValue();
10378   SDValue Ptr   = ST->getBasePtr();
10379   EVT VT = Value.getValueType();
10380
10381   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10382     return SDValue();
10383
10384   unsigned Opc = Value.getOpcode();
10385
10386   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10387   // is a byte mask indicating a consecutive number of bytes, check to see if
10388   // Y is known to provide just those bytes.  If so, we try to replace the
10389   // load + replace + store sequence with a single (narrower) store, which makes
10390   // the load dead.
10391   if (Opc == ISD::OR) {
10392     std::pair<unsigned, unsigned> MaskedLoad;
10393     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10394     if (MaskedLoad.first)
10395       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10396                                                   Value.getOperand(1), ST,this))
10397         return SDValue(NewST, 0);
10398
10399     // Or is commutative, so try swapping X and Y.
10400     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10401     if (MaskedLoad.first)
10402       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10403                                                   Value.getOperand(0), ST,this))
10404         return SDValue(NewST, 0);
10405   }
10406
10407   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10408       Value.getOperand(1).getOpcode() != ISD::Constant)
10409     return SDValue();
10410
10411   SDValue N0 = Value.getOperand(0);
10412   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10413       Chain == SDValue(N0.getNode(), 1)) {
10414     LoadSDNode *LD = cast<LoadSDNode>(N0);
10415     if (LD->getBasePtr() != Ptr ||
10416         LD->getPointerInfo().getAddrSpace() !=
10417         ST->getPointerInfo().getAddrSpace())
10418       return SDValue();
10419
10420     // Find the type to narrow it the load / op / store to.
10421     SDValue N1 = Value.getOperand(1);
10422     unsigned BitWidth = N1.getValueSizeInBits();
10423     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10424     if (Opc == ISD::AND)
10425       Imm ^= APInt::getAllOnesValue(BitWidth);
10426     if (Imm == 0 || Imm.isAllOnesValue())
10427       return SDValue();
10428     unsigned ShAmt = Imm.countTrailingZeros();
10429     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10430     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10431     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10432     // The narrowing should be profitable, the load/store operation should be
10433     // legal (or custom) and the store size should be equal to the NewVT width.
10434     while (NewBW < BitWidth &&
10435            (NewVT.getStoreSizeInBits() != NewBW ||
10436             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10437             !TLI.isNarrowingProfitable(VT, NewVT))) {
10438       NewBW = NextPowerOf2(NewBW);
10439       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10440     }
10441     if (NewBW >= BitWidth)
10442       return SDValue();
10443
10444     // If the lsb changed does not start at the type bitwidth boundary,
10445     // start at the previous one.
10446     if (ShAmt % NewBW)
10447       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10448     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10449                                    std::min(BitWidth, ShAmt + NewBW));
10450     if ((Imm & Mask) == Imm) {
10451       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10452       if (Opc == ISD::AND)
10453         NewImm ^= APInt::getAllOnesValue(NewBW);
10454       uint64_t PtrOff = ShAmt / 8;
10455       // For big endian targets, we need to adjust the offset to the pointer to
10456       // load the correct bytes.
10457       if (DAG.getDataLayout().isBigEndian())
10458         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10459
10460       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10461       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10462       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10463         return SDValue();
10464
10465       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10466                                    Ptr.getValueType(), Ptr,
10467                                    DAG.getConstant(PtrOff, SDLoc(LD),
10468                                                    Ptr.getValueType()));
10469       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10470                                   LD->getChain(), NewPtr,
10471                                   LD->getPointerInfo().getWithOffset(PtrOff),
10472                                   LD->isVolatile(), LD->isNonTemporal(),
10473                                   LD->isInvariant(), NewAlign,
10474                                   LD->getAAInfo());
10475       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10476                                    DAG.getConstant(NewImm, SDLoc(Value),
10477                                                    NewVT));
10478       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10479                                    NewVal, NewPtr,
10480                                    ST->getPointerInfo().getWithOffset(PtrOff),
10481                                    false, false, NewAlign);
10482
10483       AddToWorklist(NewPtr.getNode());
10484       AddToWorklist(NewLD.getNode());
10485       AddToWorklist(NewVal.getNode());
10486       WorklistRemover DeadNodes(*this);
10487       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10488       ++OpsNarrowed;
10489       return NewST;
10490     }
10491   }
10492
10493   return SDValue();
10494 }
10495
10496 /// For a given floating point load / store pair, if the load value isn't used
10497 /// by any other operations, then consider transforming the pair to integer
10498 /// load / store operations if the target deems the transformation profitable.
10499 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10500   StoreSDNode *ST  = cast<StoreSDNode>(N);
10501   SDValue Chain = ST->getChain();
10502   SDValue Value = ST->getValue();
10503   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10504       Value.hasOneUse() &&
10505       Chain == SDValue(Value.getNode(), 1)) {
10506     LoadSDNode *LD = cast<LoadSDNode>(Value);
10507     EVT VT = LD->getMemoryVT();
10508     if (!VT.isFloatingPoint() ||
10509         VT != ST->getMemoryVT() ||
10510         LD->isNonTemporal() ||
10511         ST->isNonTemporal() ||
10512         LD->getPointerInfo().getAddrSpace() != 0 ||
10513         ST->getPointerInfo().getAddrSpace() != 0)
10514       return SDValue();
10515
10516     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10517     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10518         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10519         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10520         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10521       return SDValue();
10522
10523     unsigned LDAlign = LD->getAlignment();
10524     unsigned STAlign = ST->getAlignment();
10525     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10526     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10527     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10528       return SDValue();
10529
10530     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10531                                 LD->getChain(), LD->getBasePtr(),
10532                                 LD->getPointerInfo(),
10533                                 false, false, false, LDAlign);
10534
10535     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10536                                  NewLD, ST->getBasePtr(),
10537                                  ST->getPointerInfo(),
10538                                  false, false, STAlign);
10539
10540     AddToWorklist(NewLD.getNode());
10541     AddToWorklist(NewST.getNode());
10542     WorklistRemover DeadNodes(*this);
10543     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10544     ++LdStFP2Int;
10545     return NewST;
10546   }
10547
10548   return SDValue();
10549 }
10550
10551 namespace {
10552 /// Helper struct to parse and store a memory address as base + index + offset.
10553 /// We ignore sign extensions when it is safe to do so.
10554 /// The following two expressions are not equivalent. To differentiate we need
10555 /// to store whether there was a sign extension involved in the index
10556 /// computation.
10557 ///  (load (i64 add (i64 copyfromreg %c)
10558 ///                 (i64 signextend (add (i8 load %index)
10559 ///                                      (i8 1))))
10560 /// vs
10561 ///
10562 /// (load (i64 add (i64 copyfromreg %c)
10563 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10564 ///                                         (i32 1)))))
10565 struct BaseIndexOffset {
10566   SDValue Base;
10567   SDValue Index;
10568   int64_t Offset;
10569   bool IsIndexSignExt;
10570
10571   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10572
10573   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10574                   bool IsIndexSignExt) :
10575     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10576
10577   bool equalBaseIndex(const BaseIndexOffset &Other) {
10578     return Other.Base == Base && Other.Index == Index &&
10579       Other.IsIndexSignExt == IsIndexSignExt;
10580   }
10581
10582   /// Parses tree in Ptr for base, index, offset addresses.
10583   static BaseIndexOffset match(SDValue Ptr) {
10584     bool IsIndexSignExt = false;
10585
10586     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10587     // instruction, then it could be just the BASE or everything else we don't
10588     // know how to handle. Just use Ptr as BASE and give up.
10589     if (Ptr->getOpcode() != ISD::ADD)
10590       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10591
10592     // We know that we have at least an ADD instruction. Try to pattern match
10593     // the simple case of BASE + OFFSET.
10594     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10595       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10596       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10597                               IsIndexSignExt);
10598     }
10599
10600     // Inside a loop the current BASE pointer is calculated using an ADD and a
10601     // MUL instruction. In this case Ptr is the actual BASE pointer.
10602     // (i64 add (i64 %array_ptr)
10603     //          (i64 mul (i64 %induction_var)
10604     //                   (i64 %element_size)))
10605     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10606       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10607
10608     // Look at Base + Index + Offset cases.
10609     SDValue Base = Ptr->getOperand(0);
10610     SDValue IndexOffset = Ptr->getOperand(1);
10611
10612     // Skip signextends.
10613     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10614       IndexOffset = IndexOffset->getOperand(0);
10615       IsIndexSignExt = true;
10616     }
10617
10618     // Either the case of Base + Index (no offset) or something else.
10619     if (IndexOffset->getOpcode() != ISD::ADD)
10620       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10621
10622     // Now we have the case of Base + Index + offset.
10623     SDValue Index = IndexOffset->getOperand(0);
10624     SDValue Offset = IndexOffset->getOperand(1);
10625
10626     if (!isa<ConstantSDNode>(Offset))
10627       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10628
10629     // Ignore signextends.
10630     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10631       Index = Index->getOperand(0);
10632       IsIndexSignExt = true;
10633     } else IsIndexSignExt = false;
10634
10635     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10636     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10637   }
10638 };
10639 } // namespace
10640
10641 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10642                                                   SDLoc SL,
10643                                                   ArrayRef<MemOpLink> Stores,
10644                                                   EVT Ty) const {
10645   SmallVector<SDValue, 8> BuildVector;
10646
10647   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10648     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10649
10650   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10651 }
10652
10653 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10654                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10655                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10656   // Make sure we have something to merge.
10657   if (NumElem < 2)
10658     return false;
10659
10660   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10661   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10662   unsigned LatestNodeUsed = 0;
10663
10664   for (unsigned i=0; i < NumElem; ++i) {
10665     // Find a chain for the new wide-store operand. Notice that some
10666     // of the store nodes that we found may not be selected for inclusion
10667     // in the wide store. The chain we use needs to be the chain of the
10668     // latest store node which is *used* and replaced by the wide store.
10669     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10670       LatestNodeUsed = i;
10671   }
10672
10673   // The latest Node in the DAG.
10674   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10675   SDLoc DL(StoreNodes[0].MemNode);
10676
10677   SDValue StoredVal;
10678   if (UseVector) {
10679     // Find a legal type for the vector store.
10680     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10681     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10682     if (IsConstantSrc) {
10683       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10684     } else {
10685       SmallVector<SDValue, 8> Ops;
10686       for (unsigned i = 0; i < NumElem ; ++i) {
10687         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10688         SDValue Val = St->getValue();
10689         // All of the operands of a BUILD_VECTOR must have the same type.
10690         if (Val.getValueType() != MemVT)
10691           return false;
10692         Ops.push_back(Val);
10693       }
10694
10695       // Build the extracted vector elements back into a vector.
10696       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10697     }
10698   } else {
10699     // We should always use a vector store when merging extracted vector
10700     // elements, so this path implies a store of constants.
10701     assert(IsConstantSrc && "Merged vector elements should use vector store");
10702
10703     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10704     APInt StoreInt(SizeInBits, 0);
10705
10706     // Construct a single integer constant which is made of the smaller
10707     // constant inputs.
10708     bool IsLE = DAG.getDataLayout().isLittleEndian();
10709     for (unsigned i = 0; i < NumElem ; ++i) {
10710       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10711       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10712       SDValue Val = St->getValue();
10713       StoreInt <<= ElementSizeBytes * 8;
10714       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10715         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10716       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10717         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10718       } else {
10719         llvm_unreachable("Invalid constant element type");
10720       }
10721     }
10722
10723     // Create the new Load and Store operations.
10724     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10725     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10726   }
10727
10728   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10729                                   FirstInChain->getBasePtr(),
10730                                   FirstInChain->getPointerInfo(),
10731                                   false, false,
10732                                   FirstInChain->getAlignment());
10733
10734   // Replace the last store with the new store
10735   CombineTo(LatestOp, NewStore);
10736   // Erase all other stores.
10737   for (unsigned i = 0; i < NumElem ; ++i) {
10738     if (StoreNodes[i].MemNode == LatestOp)
10739       continue;
10740     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10741     // ReplaceAllUsesWith will replace all uses that existed when it was
10742     // called, but graph optimizations may cause new ones to appear. For
10743     // example, the case in pr14333 looks like
10744     //
10745     //  St's chain -> St -> another store -> X
10746     //
10747     // And the only difference from St to the other store is the chain.
10748     // When we change it's chain to be St's chain they become identical,
10749     // get CSEed and the net result is that X is now a use of St.
10750     // Since we know that St is redundant, just iterate.
10751     while (!St->use_empty())
10752       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10753     deleteAndRecombine(St);
10754   }
10755
10756   return true;
10757 }
10758
10759 void DAGCombiner::getStoreMergeAndAliasCandidates(
10760     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10761     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10762   // This holds the base pointer, index, and the offset in bytes from the base
10763   // pointer.
10764   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10765
10766   // We must have a base and an offset.
10767   if (!BasePtr.Base.getNode())
10768     return;
10769
10770   // Do not handle stores to undef base pointers.
10771   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10772     return;
10773
10774   // Walk up the chain and look for nodes with offsets from the same
10775   // base pointer. Stop when reaching an instruction with a different kind
10776   // or instruction which has a different base pointer.
10777   EVT MemVT = St->getMemoryVT();
10778   unsigned Seq = 0;
10779   StoreSDNode *Index = St;
10780   while (Index) {
10781     // If the chain has more than one use, then we can't reorder the mem ops.
10782     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10783       break;
10784
10785     // Find the base pointer and offset for this memory node.
10786     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10787
10788     // Check that the base pointer is the same as the original one.
10789     if (!Ptr.equalBaseIndex(BasePtr))
10790       break;
10791
10792     // The memory operands must not be volatile.
10793     if (Index->isVolatile() || Index->isIndexed())
10794       break;
10795
10796     // No truncation.
10797     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10798       if (St->isTruncatingStore())
10799         break;
10800
10801     // The stored memory type must be the same.
10802     if (Index->getMemoryVT() != MemVT)
10803       break;
10804
10805     // We found a potential memory operand to merge.
10806     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10807
10808     // Find the next memory operand in the chain. If the next operand in the
10809     // chain is a store then move up and continue the scan with the next
10810     // memory operand. If the next operand is a load save it and use alias
10811     // information to check if it interferes with anything.
10812     SDNode *NextInChain = Index->getChain().getNode();
10813     while (1) {
10814       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10815         // We found a store node. Use it for the next iteration.
10816         Index = STn;
10817         break;
10818       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10819         if (Ldn->isVolatile()) {
10820           Index = nullptr;
10821           break;
10822         }
10823
10824         // Save the load node for later. Continue the scan.
10825         AliasLoadNodes.push_back(Ldn);
10826         NextInChain = Ldn->getChain().getNode();
10827         continue;
10828       } else {
10829         Index = nullptr;
10830         break;
10831       }
10832     }
10833   }
10834 }
10835
10836 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10837   if (OptLevel == CodeGenOpt::None)
10838     return false;
10839
10840   EVT MemVT = St->getMemoryVT();
10841   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10842   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10843       Attribute::NoImplicitFloat);
10844
10845   // This function cannot currently deal with non-byte-sized memory sizes.
10846   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10847     return false;
10848
10849   // Don't merge vectors into wider inputs.
10850   if (MemVT.isVector() || !MemVT.isSimple())
10851     return false;
10852
10853   // Perform an early exit check. Do not bother looking at stored values that
10854   // are not constants, loads, or extracted vector elements.
10855   SDValue StoredVal = St->getValue();
10856   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10857   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10858                        isa<ConstantFPSDNode>(StoredVal);
10859   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10860
10861   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10862     return false;
10863
10864   // Only look at ends of store sequences.
10865   SDValue Chain = SDValue(St, 0);
10866   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10867     return false;
10868
10869   // Save the LoadSDNodes that we find in the chain.
10870   // We need to make sure that these nodes do not interfere with
10871   // any of the store nodes.
10872   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10873
10874   // Save the StoreSDNodes that we find in the chain.
10875   SmallVector<MemOpLink, 8> StoreNodes;
10876
10877   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10878
10879   // Check if there is anything to merge.
10880   if (StoreNodes.size() < 2)
10881     return false;
10882
10883   // Sort the memory operands according to their distance from the base pointer.
10884   std::sort(StoreNodes.begin(), StoreNodes.end(),
10885             [](MemOpLink LHS, MemOpLink RHS) {
10886     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10887            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10888             LHS.SequenceNum > RHS.SequenceNum);
10889   });
10890
10891   // Scan the memory operations on the chain and find the first non-consecutive
10892   // store memory address.
10893   unsigned LastConsecutiveStore = 0;
10894   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10895   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10896
10897     // Check that the addresses are consecutive starting from the second
10898     // element in the list of stores.
10899     if (i > 0) {
10900       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10901       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10902         break;
10903     }
10904
10905     bool Alias = false;
10906     // Check if this store interferes with any of the loads that we found.
10907     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10908       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10909         Alias = true;
10910         break;
10911       }
10912     // We found a load that alias with this store. Stop the sequence.
10913     if (Alias)
10914       break;
10915
10916     // Mark this node as useful.
10917     LastConsecutiveStore = i;
10918   }
10919
10920   // The node with the lowest store address.
10921   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10922   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10923   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10924   LLVMContext &Context = *DAG.getContext();
10925   const DataLayout &DL = DAG.getDataLayout();
10926
10927   // Store the constants into memory as one consecutive store.
10928   if (IsConstantSrc) {
10929     unsigned LastLegalType = 0;
10930     unsigned LastLegalVectorType = 0;
10931     bool NonZero = false;
10932     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10933       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10934       SDValue StoredVal = St->getValue();
10935
10936       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10937         NonZero |= !C->isNullValue();
10938       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10939         NonZero |= !C->getConstantFPValue()->isNullValue();
10940       } else {
10941         // Non-constant.
10942         break;
10943       }
10944
10945       // Find a legal type for the constant store.
10946       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10947       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
10948       if (TLI.isTypeLegal(StoreTy) &&
10949           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
10950                                  FirstStoreAlign)) {
10951         LastLegalType = i+1;
10952       // Or check whether a truncstore is legal.
10953       } else if (TLI.getTypeAction(Context, StoreTy) ==
10954                  TargetLowering::TypePromoteInteger) {
10955         EVT LegalizedStoredValueTy =
10956           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
10957         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10958             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
10959                                    FirstStoreAS, FirstStoreAlign)) {
10960           LastLegalType = i + 1;
10961         }
10962       }
10963
10964       // Find a legal type for the vector store.
10965       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
10966       if (TLI.isTypeLegal(Ty) &&
10967           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
10968                                  FirstStoreAlign)) {
10969         LastLegalVectorType = i + 1;
10970       }
10971     }
10972
10973
10974     // We only use vectors if the constant is known to be zero or the target
10975     // allows it and the function is not marked with the noimplicitfloat
10976     // attribute.
10977     if (NoVectors) {
10978       LastLegalVectorType = 0;
10979     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10980                                                             LastLegalVectorType,
10981                                                             FirstStoreAS)) {
10982       LastLegalVectorType = 0;
10983     }
10984
10985     // Check if we found a legal integer type to store.
10986     if (LastLegalType == 0 && LastLegalVectorType == 0)
10987       return false;
10988
10989     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10990     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10991
10992     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10993                                            true, UseVector);
10994   }
10995
10996   // When extracting multiple vector elements, try to store them
10997   // in one vector store rather than a sequence of scalar stores.
10998   if (IsExtractVecEltSrc) {
10999     unsigned NumElem = 0;
11000     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11001       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11002       SDValue StoredVal = St->getValue();
11003       // This restriction could be loosened.
11004       // Bail out if any stored values are not elements extracted from a vector.
11005       // It should be possible to handle mixed sources, but load sources need
11006       // more careful handling (see the block of code below that handles
11007       // consecutive loads).
11008       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11009         return false;
11010
11011       // Find a legal type for the vector store.
11012       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11013       if (TLI.isTypeLegal(Ty) &&
11014           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11015                                  FirstStoreAlign))
11016         NumElem = i + 1;
11017     }
11018
11019     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11020                                            false, true);
11021   }
11022
11023   // Below we handle the case of multiple consecutive stores that
11024   // come from multiple consecutive loads. We merge them into a single
11025   // wide load and a single wide store.
11026
11027   // Look for load nodes which are used by the stored values.
11028   SmallVector<MemOpLink, 8> LoadNodes;
11029
11030   // Find acceptable loads. Loads need to have the same chain (token factor),
11031   // must not be zext, volatile, indexed, and they must be consecutive.
11032   BaseIndexOffset LdBasePtr;
11033   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11034     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11035     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11036     if (!Ld) break;
11037
11038     // Loads must only have one use.
11039     if (!Ld->hasNUsesOfValue(1, 0))
11040       break;
11041
11042     // The memory operands must not be volatile.
11043     if (Ld->isVolatile() || Ld->isIndexed())
11044       break;
11045
11046     // We do not accept ext loads.
11047     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11048       break;
11049
11050     // The stored memory type must be the same.
11051     if (Ld->getMemoryVT() != MemVT)
11052       break;
11053
11054     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11055     // If this is not the first ptr that we check.
11056     if (LdBasePtr.Base.getNode()) {
11057       // The base ptr must be the same.
11058       if (!LdPtr.equalBaseIndex(LdBasePtr))
11059         break;
11060     } else {
11061       // Check that all other base pointers are the same as this one.
11062       LdBasePtr = LdPtr;
11063     }
11064
11065     // We found a potential memory operand to merge.
11066     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11067   }
11068
11069   if (LoadNodes.size() < 2)
11070     return false;
11071
11072   // If we have load/store pair instructions and we only have two values,
11073   // don't bother.
11074   unsigned RequiredAlignment;
11075   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11076       St->getAlignment() >= RequiredAlignment)
11077     return false;
11078
11079   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11080   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11081   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11082
11083   // Scan the memory operations on the chain and find the first non-consecutive
11084   // load memory address. These variables hold the index in the store node
11085   // array.
11086   unsigned LastConsecutiveLoad = 0;
11087   // This variable refers to the size and not index in the array.
11088   unsigned LastLegalVectorType = 0;
11089   unsigned LastLegalIntegerType = 0;
11090   StartAddress = LoadNodes[0].OffsetFromBase;
11091   SDValue FirstChain = FirstLoad->getChain();
11092   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11093     // All loads much share the same chain.
11094     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11095       break;
11096
11097     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11098     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11099       break;
11100     LastConsecutiveLoad = i;
11101
11102     // Find a legal type for the vector store.
11103     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11104     if (TLI.isTypeLegal(StoreTy) &&
11105         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11106                                FirstStoreAlign) &&
11107         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11108                                FirstLoadAlign)) {
11109       LastLegalVectorType = i + 1;
11110     }
11111
11112     // Find a legal type for the integer store.
11113     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11114     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11115     if (TLI.isTypeLegal(StoreTy) &&
11116         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11117                                FirstStoreAlign) &&
11118         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11119                                FirstLoadAlign))
11120       LastLegalIntegerType = i + 1;
11121     // Or check whether a truncstore and extload is legal.
11122     else if (TLI.getTypeAction(Context, StoreTy) ==
11123              TargetLowering::TypePromoteInteger) {
11124       EVT LegalizedStoredValueTy =
11125         TLI.getTypeToTransformTo(Context, StoreTy);
11126       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11127           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11128           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11129           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11130           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11131                                  FirstStoreAS, FirstStoreAlign) &&
11132           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11133                                  FirstLoadAS, FirstLoadAlign))
11134         LastLegalIntegerType = i+1;
11135     }
11136   }
11137
11138   // Only use vector types if the vector type is larger than the integer type.
11139   // If they are the same, use integers.
11140   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11141   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11142
11143   // We add +1 here because the LastXXX variables refer to location while
11144   // the NumElem refers to array/index size.
11145   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11146   NumElem = std::min(LastLegalType, NumElem);
11147
11148   if (NumElem < 2)
11149     return false;
11150
11151   // The latest Node in the DAG.
11152   unsigned LatestNodeUsed = 0;
11153   for (unsigned i=1; i<NumElem; ++i) {
11154     // Find a chain for the new wide-store operand. Notice that some
11155     // of the store nodes that we found may not be selected for inclusion
11156     // in the wide store. The chain we use needs to be the chain of the
11157     // latest store node which is *used* and replaced by the wide store.
11158     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11159       LatestNodeUsed = i;
11160   }
11161
11162   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11163
11164   // Find if it is better to use vectors or integers to load and store
11165   // to memory.
11166   EVT JointMemOpVT;
11167   if (UseVectorTy) {
11168     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11169   } else {
11170     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11171     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11172   }
11173
11174   SDLoc LoadDL(LoadNodes[0].MemNode);
11175   SDLoc StoreDL(StoreNodes[0].MemNode);
11176
11177   SDValue NewLoad = DAG.getLoad(
11178       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11179       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11180
11181   SDValue NewStore = DAG.getStore(
11182       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11183       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11184
11185   // Replace one of the loads with the new load.
11186   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11187   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11188                                 SDValue(NewLoad.getNode(), 1));
11189
11190   // Remove the rest of the load chains.
11191   for (unsigned i = 1; i < NumElem ; ++i) {
11192     // Replace all chain users of the old load nodes with the chain of the new
11193     // load node.
11194     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11195     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11196   }
11197
11198   // Replace the last store with the new store.
11199   CombineTo(LatestOp, NewStore);
11200   // Erase all other stores.
11201   for (unsigned i = 0; i < NumElem ; ++i) {
11202     // Remove all Store nodes.
11203     if (StoreNodes[i].MemNode == LatestOp)
11204       continue;
11205     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11206     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11207     deleteAndRecombine(St);
11208   }
11209
11210   return true;
11211 }
11212
11213 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11214   StoreSDNode *ST  = cast<StoreSDNode>(N);
11215   SDValue Chain = ST->getChain();
11216   SDValue Value = ST->getValue();
11217   SDValue Ptr   = ST->getBasePtr();
11218
11219   // If this is a store of a bit convert, store the input value if the
11220   // resultant store does not need a higher alignment than the original.
11221   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11222       ST->isUnindexed()) {
11223     unsigned OrigAlign = ST->getAlignment();
11224     EVT SVT = Value.getOperand(0).getValueType();
11225     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11226         SVT.getTypeForEVT(*DAG.getContext()));
11227     if (Align <= OrigAlign &&
11228         ((!LegalOperations && !ST->isVolatile()) ||
11229          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11230       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11231                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11232                           ST->isNonTemporal(), OrigAlign,
11233                           ST->getAAInfo());
11234   }
11235
11236   // Turn 'store undef, Ptr' -> nothing.
11237   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11238     return Chain;
11239
11240   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11241   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11242     // NOTE: If the original store is volatile, this transform must not increase
11243     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11244     // processor operation but an i64 (which is not legal) requires two.  So the
11245     // transform should not be done in this case.
11246     if (Value.getOpcode() != ISD::TargetConstantFP) {
11247       SDValue Tmp;
11248       switch (CFP->getSimpleValueType(0).SimpleTy) {
11249       default: llvm_unreachable("Unknown FP type");
11250       case MVT::f16:    // We don't do this for these yet.
11251       case MVT::f80:
11252       case MVT::f128:
11253       case MVT::ppcf128:
11254         break;
11255       case MVT::f32:
11256         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11257             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11258           ;
11259           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11260                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11261                               MVT::i32);
11262           return DAG.getStore(Chain, SDLoc(N), Tmp,
11263                               Ptr, ST->getMemOperand());
11264         }
11265         break;
11266       case MVT::f64:
11267         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11268              !ST->isVolatile()) ||
11269             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11270           ;
11271           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11272                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11273           return DAG.getStore(Chain, SDLoc(N), Tmp,
11274                               Ptr, ST->getMemOperand());
11275         }
11276
11277         if (!ST->isVolatile() &&
11278             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11279           // Many FP stores are not made apparent until after legalize, e.g. for
11280           // argument passing.  Since this is so common, custom legalize the
11281           // 64-bit integer store into two 32-bit stores.
11282           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11283           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11284           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11285           if (DAG.getDataLayout().isBigEndian())
11286             std::swap(Lo, Hi);
11287
11288           unsigned Alignment = ST->getAlignment();
11289           bool isVolatile = ST->isVolatile();
11290           bool isNonTemporal = ST->isNonTemporal();
11291           AAMDNodes AAInfo = ST->getAAInfo();
11292
11293           SDLoc DL(N);
11294
11295           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11296                                      Ptr, ST->getPointerInfo(),
11297                                      isVolatile, isNonTemporal,
11298                                      ST->getAlignment(), AAInfo);
11299           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11300                             DAG.getConstant(4, DL, Ptr.getValueType()));
11301           Alignment = MinAlign(Alignment, 4U);
11302           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11303                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11304                                      isVolatile, isNonTemporal,
11305                                      Alignment, AAInfo);
11306           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11307                              St0, St1);
11308         }
11309
11310         break;
11311       }
11312     }
11313   }
11314
11315   // Try to infer better alignment information than the store already has.
11316   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11317     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11318       if (Align > ST->getAlignment()) {
11319         SDValue NewStore =
11320                DAG.getTruncStore(Chain, SDLoc(N), Value,
11321                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11322                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11323                                  ST->getAAInfo());
11324         if (NewStore.getNode() != N)
11325           return CombineTo(ST, NewStore, true);
11326       }
11327     }
11328   }
11329
11330   // Try transforming a pair floating point load / store ops to integer
11331   // load / store ops.
11332   if (SDValue NewST = TransformFPLoadStorePair(N))
11333     return NewST;
11334
11335   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11336                                                   : DAG.getSubtarget().useAA();
11337 #ifndef NDEBUG
11338   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11339       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11340     UseAA = false;
11341 #endif
11342   if (UseAA && ST->isUnindexed()) {
11343     // Walk up chain skipping non-aliasing memory nodes.
11344     SDValue BetterChain = FindBetterChain(N, Chain);
11345
11346     // If there is a better chain.
11347     if (Chain != BetterChain) {
11348       SDValue ReplStore;
11349
11350       // Replace the chain to avoid dependency.
11351       if (ST->isTruncatingStore()) {
11352         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11353                                       ST->getMemoryVT(), ST->getMemOperand());
11354       } else {
11355         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11356                                  ST->getMemOperand());
11357       }
11358
11359       // Create token to keep both nodes around.
11360       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11361                                   MVT::Other, Chain, ReplStore);
11362
11363       // Make sure the new and old chains are cleaned up.
11364       AddToWorklist(Token.getNode());
11365
11366       // Don't add users to work list.
11367       return CombineTo(N, Token, false);
11368     }
11369   }
11370
11371   // Try transforming N to an indexed store.
11372   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11373     return SDValue(N, 0);
11374
11375   // FIXME: is there such a thing as a truncating indexed store?
11376   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11377       Value.getValueType().isInteger()) {
11378     // See if we can simplify the input to this truncstore with knowledge that
11379     // only the low bits are being used.  For example:
11380     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11381     SDValue Shorter =
11382       GetDemandedBits(Value,
11383                       APInt::getLowBitsSet(
11384                         Value.getValueType().getScalarType().getSizeInBits(),
11385                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11386     AddToWorklist(Value.getNode());
11387     if (Shorter.getNode())
11388       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11389                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11390
11391     // Otherwise, see if we can simplify the operation with
11392     // SimplifyDemandedBits, which only works if the value has a single use.
11393     if (SimplifyDemandedBits(Value,
11394                         APInt::getLowBitsSet(
11395                           Value.getValueType().getScalarType().getSizeInBits(),
11396                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11397       return SDValue(N, 0);
11398   }
11399
11400   // If this is a load followed by a store to the same location, then the store
11401   // is dead/noop.
11402   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11403     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11404         ST->isUnindexed() && !ST->isVolatile() &&
11405         // There can't be any side effects between the load and store, such as
11406         // a call or store.
11407         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11408       // The store is dead, remove it.
11409       return Chain;
11410     }
11411   }
11412
11413   // If this is a store followed by a store with the same value to the same
11414   // location, then the store is dead/noop.
11415   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11416     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11417         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11418         ST1->isUnindexed() && !ST1->isVolatile()) {
11419       // The store is dead, remove it.
11420       return Chain;
11421     }
11422   }
11423
11424   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11425   // truncating store.  We can do this even if this is already a truncstore.
11426   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11427       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11428       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11429                             ST->getMemoryVT())) {
11430     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11431                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11432   }
11433
11434   // Only perform this optimization before the types are legal, because we
11435   // don't want to perform this optimization on every DAGCombine invocation.
11436   if (!LegalTypes) {
11437     bool EverChanged = false;
11438
11439     do {
11440       // There can be multiple store sequences on the same chain.
11441       // Keep trying to merge store sequences until we are unable to do so
11442       // or until we merge the last store on the chain.
11443       bool Changed = MergeConsecutiveStores(ST);
11444       EverChanged |= Changed;
11445       if (!Changed) break;
11446     } while (ST->getOpcode() != ISD::DELETED_NODE);
11447
11448     if (EverChanged)
11449       return SDValue(N, 0);
11450   }
11451
11452   return ReduceLoadOpStoreWidth(N);
11453 }
11454
11455 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11456   SDValue InVec = N->getOperand(0);
11457   SDValue InVal = N->getOperand(1);
11458   SDValue EltNo = N->getOperand(2);
11459   SDLoc dl(N);
11460
11461   // If the inserted element is an UNDEF, just use the input vector.
11462   if (InVal.getOpcode() == ISD::UNDEF)
11463     return InVec;
11464
11465   EVT VT = InVec.getValueType();
11466
11467   // If we can't generate a legal BUILD_VECTOR, exit
11468   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11469     return SDValue();
11470
11471   // Check that we know which element is being inserted
11472   if (!isa<ConstantSDNode>(EltNo))
11473     return SDValue();
11474   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11475
11476   // Canonicalize insert_vector_elt dag nodes.
11477   // Example:
11478   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11479   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11480   //
11481   // Do this only if the child insert_vector node has one use; also
11482   // do this only if indices are both constants and Idx1 < Idx0.
11483   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11484       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11485     unsigned OtherElt =
11486       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11487     if (Elt < OtherElt) {
11488       // Swap nodes.
11489       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11490                                   InVec.getOperand(0), InVal, EltNo);
11491       AddToWorklist(NewOp.getNode());
11492       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11493                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11494     }
11495   }
11496
11497   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11498   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11499   // vector elements.
11500   SmallVector<SDValue, 8> Ops;
11501   // Do not combine these two vectors if the output vector will not replace
11502   // the input vector.
11503   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11504     Ops.append(InVec.getNode()->op_begin(),
11505                InVec.getNode()->op_end());
11506   } else if (InVec.getOpcode() == ISD::UNDEF) {
11507     unsigned NElts = VT.getVectorNumElements();
11508     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11509   } else {
11510     return SDValue();
11511   }
11512
11513   // Insert the element
11514   if (Elt < Ops.size()) {
11515     // All the operands of BUILD_VECTOR must have the same type;
11516     // we enforce that here.
11517     EVT OpVT = Ops[0].getValueType();
11518     if (InVal.getValueType() != OpVT)
11519       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11520                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11521                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11522     Ops[Elt] = InVal;
11523   }
11524
11525   // Return the new vector
11526   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11527 }
11528
11529 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11530     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11531   EVT ResultVT = EVE->getValueType(0);
11532   EVT VecEltVT = InVecVT.getVectorElementType();
11533   unsigned Align = OriginalLoad->getAlignment();
11534   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11535       VecEltVT.getTypeForEVT(*DAG.getContext()));
11536
11537   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11538     return SDValue();
11539
11540   Align = NewAlign;
11541
11542   SDValue NewPtr = OriginalLoad->getBasePtr();
11543   SDValue Offset;
11544   EVT PtrType = NewPtr.getValueType();
11545   MachinePointerInfo MPI;
11546   SDLoc DL(EVE);
11547   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11548     int Elt = ConstEltNo->getZExtValue();
11549     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11550     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11551     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11552   } else {
11553     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11554     Offset = DAG.getNode(
11555         ISD::MUL, DL, PtrType, Offset,
11556         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11557     MPI = OriginalLoad->getPointerInfo();
11558   }
11559   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11560
11561   // The replacement we need to do here is a little tricky: we need to
11562   // replace an extractelement of a load with a load.
11563   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11564   // Note that this replacement assumes that the extractvalue is the only
11565   // use of the load; that's okay because we don't want to perform this
11566   // transformation in other cases anyway.
11567   SDValue Load;
11568   SDValue Chain;
11569   if (ResultVT.bitsGT(VecEltVT)) {
11570     // If the result type of vextract is wider than the load, then issue an
11571     // extending load instead.
11572     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11573                                                   VecEltVT)
11574                                    ? ISD::ZEXTLOAD
11575                                    : ISD::EXTLOAD;
11576     Load = DAG.getExtLoad(
11577         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11578         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11579         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11580     Chain = Load.getValue(1);
11581   } else {
11582     Load = DAG.getLoad(
11583         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11584         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11585         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11586     Chain = Load.getValue(1);
11587     if (ResultVT.bitsLT(VecEltVT))
11588       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11589     else
11590       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11591   }
11592   WorklistRemover DeadNodes(*this);
11593   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11594   SDValue To[] = { Load, Chain };
11595   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11596   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11597   // worklist explicitly as well.
11598   AddToWorklist(Load.getNode());
11599   AddUsersToWorklist(Load.getNode()); // Add users too
11600   // Make sure to revisit this node to clean it up; it will usually be dead.
11601   AddToWorklist(EVE);
11602   ++OpsNarrowed;
11603   return SDValue(EVE, 0);
11604 }
11605
11606 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11607   // (vextract (scalar_to_vector val, 0) -> val
11608   SDValue InVec = N->getOperand(0);
11609   EVT VT = InVec.getValueType();
11610   EVT NVT = N->getValueType(0);
11611
11612   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11613     // Check if the result type doesn't match the inserted element type. A
11614     // SCALAR_TO_VECTOR may truncate the inserted element and the
11615     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11616     SDValue InOp = InVec.getOperand(0);
11617     if (InOp.getValueType() != NVT) {
11618       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11619       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11620     }
11621     return InOp;
11622   }
11623
11624   SDValue EltNo = N->getOperand(1);
11625   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11626
11627   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11628   // We only perform this optimization before the op legalization phase because
11629   // we may introduce new vector instructions which are not backed by TD
11630   // patterns. For example on AVX, extracting elements from a wide vector
11631   // without using extract_subvector. However, if we can find an underlying
11632   // scalar value, then we can always use that.
11633   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11634       && ConstEltNo) {
11635     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11636     int NumElem = VT.getVectorNumElements();
11637     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11638     // Find the new index to extract from.
11639     int OrigElt = SVOp->getMaskElt(Elt);
11640
11641     // Extracting an undef index is undef.
11642     if (OrigElt == -1)
11643       return DAG.getUNDEF(NVT);
11644
11645     // Select the right vector half to extract from.
11646     SDValue SVInVec;
11647     if (OrigElt < NumElem) {
11648       SVInVec = InVec->getOperand(0);
11649     } else {
11650       SVInVec = InVec->getOperand(1);
11651       OrigElt -= NumElem;
11652     }
11653
11654     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11655       SDValue InOp = SVInVec.getOperand(OrigElt);
11656       if (InOp.getValueType() != NVT) {
11657         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11658         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11659       }
11660
11661       return InOp;
11662     }
11663
11664     // FIXME: We should handle recursing on other vector shuffles and
11665     // scalar_to_vector here as well.
11666
11667     if (!LegalOperations) {
11668       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11669       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11670                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11671     }
11672   }
11673
11674   bool BCNumEltsChanged = false;
11675   EVT ExtVT = VT.getVectorElementType();
11676   EVT LVT = ExtVT;
11677
11678   // If the result of load has to be truncated, then it's not necessarily
11679   // profitable.
11680   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11681     return SDValue();
11682
11683   if (InVec.getOpcode() == ISD::BITCAST) {
11684     // Don't duplicate a load with other uses.
11685     if (!InVec.hasOneUse())
11686       return SDValue();
11687
11688     EVT BCVT = InVec.getOperand(0).getValueType();
11689     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11690       return SDValue();
11691     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11692       BCNumEltsChanged = true;
11693     InVec = InVec.getOperand(0);
11694     ExtVT = BCVT.getVectorElementType();
11695   }
11696
11697   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11698   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11699       ISD::isNormalLoad(InVec.getNode()) &&
11700       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11701     SDValue Index = N->getOperand(1);
11702     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11703       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11704                                                            OrigLoad);
11705   }
11706
11707   // Perform only after legalization to ensure build_vector / vector_shuffle
11708   // optimizations have already been done.
11709   if (!LegalOperations) return SDValue();
11710
11711   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11712   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11713   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11714
11715   if (ConstEltNo) {
11716     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11717
11718     LoadSDNode *LN0 = nullptr;
11719     const ShuffleVectorSDNode *SVN = nullptr;
11720     if (ISD::isNormalLoad(InVec.getNode())) {
11721       LN0 = cast<LoadSDNode>(InVec);
11722     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11723                InVec.getOperand(0).getValueType() == ExtVT &&
11724                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11725       // Don't duplicate a load with other uses.
11726       if (!InVec.hasOneUse())
11727         return SDValue();
11728
11729       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11730     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11731       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11732       // =>
11733       // (load $addr+1*size)
11734
11735       // Don't duplicate a load with other uses.
11736       if (!InVec.hasOneUse())
11737         return SDValue();
11738
11739       // If the bit convert changed the number of elements, it is unsafe
11740       // to examine the mask.
11741       if (BCNumEltsChanged)
11742         return SDValue();
11743
11744       // Select the input vector, guarding against out of range extract vector.
11745       unsigned NumElems = VT.getVectorNumElements();
11746       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11747       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11748
11749       if (InVec.getOpcode() == ISD::BITCAST) {
11750         // Don't duplicate a load with other uses.
11751         if (!InVec.hasOneUse())
11752           return SDValue();
11753
11754         InVec = InVec.getOperand(0);
11755       }
11756       if (ISD::isNormalLoad(InVec.getNode())) {
11757         LN0 = cast<LoadSDNode>(InVec);
11758         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11759         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11760       }
11761     }
11762
11763     // Make sure we found a non-volatile load and the extractelement is
11764     // the only use.
11765     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11766       return SDValue();
11767
11768     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11769     if (Elt == -1)
11770       return DAG.getUNDEF(LVT);
11771
11772     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11773   }
11774
11775   return SDValue();
11776 }
11777
11778 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11779 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11780   // We perform this optimization post type-legalization because
11781   // the type-legalizer often scalarizes integer-promoted vectors.
11782   // Performing this optimization before may create bit-casts which
11783   // will be type-legalized to complex code sequences.
11784   // We perform this optimization only before the operation legalizer because we
11785   // may introduce illegal operations.
11786   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11787     return SDValue();
11788
11789   unsigned NumInScalars = N->getNumOperands();
11790   SDLoc dl(N);
11791   EVT VT = N->getValueType(0);
11792
11793   // Check to see if this is a BUILD_VECTOR of a bunch of values
11794   // which come from any_extend or zero_extend nodes. If so, we can create
11795   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11796   // optimizations. We do not handle sign-extend because we can't fill the sign
11797   // using shuffles.
11798   EVT SourceType = MVT::Other;
11799   bool AllAnyExt = true;
11800
11801   for (unsigned i = 0; i != NumInScalars; ++i) {
11802     SDValue In = N->getOperand(i);
11803     // Ignore undef inputs.
11804     if (In.getOpcode() == ISD::UNDEF) continue;
11805
11806     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11807     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11808
11809     // Abort if the element is not an extension.
11810     if (!ZeroExt && !AnyExt) {
11811       SourceType = MVT::Other;
11812       break;
11813     }
11814
11815     // The input is a ZeroExt or AnyExt. Check the original type.
11816     EVT InTy = In.getOperand(0).getValueType();
11817
11818     // Check that all of the widened source types are the same.
11819     if (SourceType == MVT::Other)
11820       // First time.
11821       SourceType = InTy;
11822     else if (InTy != SourceType) {
11823       // Multiple income types. Abort.
11824       SourceType = MVT::Other;
11825       break;
11826     }
11827
11828     // Check if all of the extends are ANY_EXTENDs.
11829     AllAnyExt &= AnyExt;
11830   }
11831
11832   // In order to have valid types, all of the inputs must be extended from the
11833   // same source type and all of the inputs must be any or zero extend.
11834   // Scalar sizes must be a power of two.
11835   EVT OutScalarTy = VT.getScalarType();
11836   bool ValidTypes = SourceType != MVT::Other &&
11837                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11838                  isPowerOf2_32(SourceType.getSizeInBits());
11839
11840   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11841   // turn into a single shuffle instruction.
11842   if (!ValidTypes)
11843     return SDValue();
11844
11845   bool isLE = DAG.getDataLayout().isLittleEndian();
11846   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11847   assert(ElemRatio > 1 && "Invalid element size ratio");
11848   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11849                                DAG.getConstant(0, SDLoc(N), SourceType);
11850
11851   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11852   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11853
11854   // Populate the new build_vector
11855   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11856     SDValue Cast = N->getOperand(i);
11857     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11858             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11859             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11860     SDValue In;
11861     if (Cast.getOpcode() == ISD::UNDEF)
11862       In = DAG.getUNDEF(SourceType);
11863     else
11864       In = Cast->getOperand(0);
11865     unsigned Index = isLE ? (i * ElemRatio) :
11866                             (i * ElemRatio + (ElemRatio - 1));
11867
11868     assert(Index < Ops.size() && "Invalid index");
11869     Ops[Index] = In;
11870   }
11871
11872   // The type of the new BUILD_VECTOR node.
11873   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11874   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11875          "Invalid vector size");
11876   // Check if the new vector type is legal.
11877   if (!isTypeLegal(VecVT)) return SDValue();
11878
11879   // Make the new BUILD_VECTOR.
11880   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11881
11882   // The new BUILD_VECTOR node has the potential to be further optimized.
11883   AddToWorklist(BV.getNode());
11884   // Bitcast to the desired type.
11885   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11886 }
11887
11888 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11889   EVT VT = N->getValueType(0);
11890
11891   unsigned NumInScalars = N->getNumOperands();
11892   SDLoc dl(N);
11893
11894   EVT SrcVT = MVT::Other;
11895   unsigned Opcode = ISD::DELETED_NODE;
11896   unsigned NumDefs = 0;
11897
11898   for (unsigned i = 0; i != NumInScalars; ++i) {
11899     SDValue In = N->getOperand(i);
11900     unsigned Opc = In.getOpcode();
11901
11902     if (Opc == ISD::UNDEF)
11903       continue;
11904
11905     // If all scalar values are floats and converted from integers.
11906     if (Opcode == ISD::DELETED_NODE &&
11907         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11908       Opcode = Opc;
11909     }
11910
11911     if (Opc != Opcode)
11912       return SDValue();
11913
11914     EVT InVT = In.getOperand(0).getValueType();
11915
11916     // If all scalar values are typed differently, bail out. It's chosen to
11917     // simplify BUILD_VECTOR of integer types.
11918     if (SrcVT == MVT::Other)
11919       SrcVT = InVT;
11920     if (SrcVT != InVT)
11921       return SDValue();
11922     NumDefs++;
11923   }
11924
11925   // If the vector has just one element defined, it's not worth to fold it into
11926   // a vectorized one.
11927   if (NumDefs < 2)
11928     return SDValue();
11929
11930   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11931          && "Should only handle conversion from integer to float.");
11932   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11933
11934   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11935
11936   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11937     return SDValue();
11938
11939   // Just because the floating-point vector type is legal does not necessarily
11940   // mean that the corresponding integer vector type is.
11941   if (!isTypeLegal(NVT))
11942     return SDValue();
11943
11944   SmallVector<SDValue, 8> Opnds;
11945   for (unsigned i = 0; i != NumInScalars; ++i) {
11946     SDValue In = N->getOperand(i);
11947
11948     if (In.getOpcode() == ISD::UNDEF)
11949       Opnds.push_back(DAG.getUNDEF(SrcVT));
11950     else
11951       Opnds.push_back(In.getOperand(0));
11952   }
11953   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11954   AddToWorklist(BV.getNode());
11955
11956   return DAG.getNode(Opcode, dl, VT, BV);
11957 }
11958
11959 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11960   unsigned NumInScalars = N->getNumOperands();
11961   SDLoc dl(N);
11962   EVT VT = N->getValueType(0);
11963
11964   // A vector built entirely of undefs is undef.
11965   if (ISD::allOperandsUndef(N))
11966     return DAG.getUNDEF(VT);
11967
11968   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11969     return V;
11970
11971   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11972     return V;
11973
11974   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11975   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11976   // at most two distinct vectors, turn this into a shuffle node.
11977
11978   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11979   if (!isTypeLegal(VT))
11980     return SDValue();
11981
11982   // May only combine to shuffle after legalize if shuffle is legal.
11983   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11984     return SDValue();
11985
11986   SDValue VecIn1, VecIn2;
11987   bool UsesZeroVector = false;
11988   for (unsigned i = 0; i != NumInScalars; ++i) {
11989     SDValue Op = N->getOperand(i);
11990     // Ignore undef inputs.
11991     if (Op.getOpcode() == ISD::UNDEF) continue;
11992
11993     // See if we can combine this build_vector into a blend with a zero vector.
11994     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11995       UsesZeroVector = true;
11996       continue;
11997     }
11998
11999     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12000     // constant index, bail out.
12001     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12002         !isa<ConstantSDNode>(Op.getOperand(1))) {
12003       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12004       break;
12005     }
12006
12007     // We allow up to two distinct input vectors.
12008     SDValue ExtractedFromVec = Op.getOperand(0);
12009     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12010       continue;
12011
12012     if (!VecIn1.getNode()) {
12013       VecIn1 = ExtractedFromVec;
12014     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12015       VecIn2 = ExtractedFromVec;
12016     } else {
12017       // Too many inputs.
12018       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12019       break;
12020     }
12021   }
12022
12023   // If everything is good, we can make a shuffle operation.
12024   if (VecIn1.getNode()) {
12025     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12026     SmallVector<int, 8> Mask;
12027     for (unsigned i = 0; i != NumInScalars; ++i) {
12028       unsigned Opcode = N->getOperand(i).getOpcode();
12029       if (Opcode == ISD::UNDEF) {
12030         Mask.push_back(-1);
12031         continue;
12032       }
12033
12034       // Operands can also be zero.
12035       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12036         assert(UsesZeroVector &&
12037                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12038                "Unexpected node found!");
12039         Mask.push_back(NumInScalars+i);
12040         continue;
12041       }
12042
12043       // If extracting from the first vector, just use the index directly.
12044       SDValue Extract = N->getOperand(i);
12045       SDValue ExtVal = Extract.getOperand(1);
12046       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12047       if (Extract.getOperand(0) == VecIn1) {
12048         Mask.push_back(ExtIndex);
12049         continue;
12050       }
12051
12052       // Otherwise, use InIdx + InputVecSize
12053       Mask.push_back(InNumElements + ExtIndex);
12054     }
12055
12056     // Avoid introducing illegal shuffles with zero.
12057     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12058       return SDValue();
12059
12060     // We can't generate a shuffle node with mismatched input and output types.
12061     // Attempt to transform a single input vector to the correct type.
12062     if ((VT != VecIn1.getValueType())) {
12063       // If the input vector type has a different base type to the output
12064       // vector type, bail out.
12065       EVT VTElemType = VT.getVectorElementType();
12066       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12067           (VecIn2.getNode() &&
12068            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12069         return SDValue();
12070
12071       // If the input vector is too small, widen it.
12072       // We only support widening of vectors which are half the size of the
12073       // output registers. For example XMM->YMM widening on X86 with AVX.
12074       EVT VecInT = VecIn1.getValueType();
12075       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12076         // If we only have one small input, widen it by adding undef values.
12077         if (!VecIn2.getNode())
12078           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12079                                DAG.getUNDEF(VecIn1.getValueType()));
12080         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12081           // If we have two small inputs of the same type, try to concat them.
12082           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12083           VecIn2 = SDValue(nullptr, 0);
12084         } else
12085           return SDValue();
12086       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12087         // If the input vector is too large, try to split it.
12088         // We don't support having two input vectors that are too large.
12089         // If the zero vector was used, we can not split the vector,
12090         // since we'd need 3 inputs.
12091         if (UsesZeroVector || VecIn2.getNode())
12092           return SDValue();
12093
12094         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12095           return SDValue();
12096
12097         // Try to replace VecIn1 with two extract_subvectors
12098         // No need to update the masks, they should still be correct.
12099         VecIn2 = DAG.getNode(
12100             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12101             DAG.getConstant(VT.getVectorNumElements(), dl,
12102                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12103         VecIn1 = DAG.getNode(
12104             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12105             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12106       } else
12107         return SDValue();
12108     }
12109
12110     if (UsesZeroVector)
12111       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12112                                 DAG.getConstantFP(0.0, dl, VT);
12113     else
12114       // If VecIn2 is unused then change it to undef.
12115       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12116
12117     // Check that we were able to transform all incoming values to the same
12118     // type.
12119     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12120         VecIn1.getValueType() != VT)
12121           return SDValue();
12122
12123     // Return the new VECTOR_SHUFFLE node.
12124     SDValue Ops[2];
12125     Ops[0] = VecIn1;
12126     Ops[1] = VecIn2;
12127     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12128   }
12129
12130   return SDValue();
12131 }
12132
12133 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12135   EVT OpVT = N->getOperand(0).getValueType();
12136
12137   // If the operands are legal vectors, leave them alone.
12138   if (TLI.isTypeLegal(OpVT))
12139     return SDValue();
12140
12141   SDLoc DL(N);
12142   EVT VT = N->getValueType(0);
12143   SmallVector<SDValue, 8> Ops;
12144
12145   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12146   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12147
12148   // Keep track of what we encounter.
12149   bool AnyInteger = false;
12150   bool AnyFP = false;
12151   for (const SDValue &Op : N->ops()) {
12152     if (ISD::BITCAST == Op.getOpcode() &&
12153         !Op.getOperand(0).getValueType().isVector())
12154       Ops.push_back(Op.getOperand(0));
12155     else if (ISD::UNDEF == Op.getOpcode())
12156       Ops.push_back(ScalarUndef);
12157     else
12158       return SDValue();
12159
12160     // Note whether we encounter an integer or floating point scalar.
12161     // If it's neither, bail out, it could be something weird like x86mmx.
12162     EVT LastOpVT = Ops.back().getValueType();
12163     if (LastOpVT.isFloatingPoint())
12164       AnyFP = true;
12165     else if (LastOpVT.isInteger())
12166       AnyInteger = true;
12167     else
12168       return SDValue();
12169   }
12170
12171   // If any of the operands is a floating point scalar bitcast to a vector,
12172   // use floating point types throughout, and bitcast everything.
12173   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12174   if (AnyFP) {
12175     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12176     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12177     if (AnyInteger) {
12178       for (SDValue &Op : Ops) {
12179         if (Op.getValueType() == SVT)
12180           continue;
12181         if (Op.getOpcode() == ISD::UNDEF)
12182           Op = ScalarUndef;
12183         else
12184           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12185       }
12186     }
12187   }
12188
12189   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12190                                VT.getSizeInBits() / SVT.getSizeInBits());
12191   return DAG.getNode(ISD::BITCAST, DL, VT,
12192                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12193 }
12194
12195 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12196   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12197   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12198   // inputs come from at most two distinct vectors, turn this into a shuffle
12199   // node.
12200
12201   // If we only have one input vector, we don't need to do any concatenation.
12202   if (N->getNumOperands() == 1)
12203     return N->getOperand(0);
12204
12205   // Check if all of the operands are undefs.
12206   EVT VT = N->getValueType(0);
12207   if (ISD::allOperandsUndef(N))
12208     return DAG.getUNDEF(VT);
12209
12210   // Optimize concat_vectors where all but the first of the vectors are undef.
12211   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12212         return Op.getOpcode() == ISD::UNDEF;
12213       })) {
12214     SDValue In = N->getOperand(0);
12215     assert(In.getValueType().isVector() && "Must concat vectors");
12216
12217     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12218     if (In->getOpcode() == ISD::BITCAST &&
12219         !In->getOperand(0)->getValueType(0).isVector()) {
12220       SDValue Scalar = In->getOperand(0);
12221
12222       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12223       // look through the trunc so we can still do the transform:
12224       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12225       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12226           !TLI.isTypeLegal(Scalar.getValueType()) &&
12227           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12228         Scalar = Scalar->getOperand(0);
12229
12230       EVT SclTy = Scalar->getValueType(0);
12231
12232       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12233         return SDValue();
12234
12235       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12236                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12237       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12238         return SDValue();
12239
12240       SDLoc dl = SDLoc(N);
12241       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12242       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12243     }
12244   }
12245
12246   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12247   // We have already tested above for an UNDEF only concatenation.
12248   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12249   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12250   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12251     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12252   };
12253   bool AllBuildVectorsOrUndefs =
12254       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12255   if (AllBuildVectorsOrUndefs) {
12256     SmallVector<SDValue, 8> Opnds;
12257     EVT SVT = VT.getScalarType();
12258
12259     EVT MinVT = SVT;
12260     if (!SVT.isFloatingPoint()) {
12261       // If BUILD_VECTOR are from built from integer, they may have different
12262       // operand types. Get the smallest type and truncate all operands to it.
12263       bool FoundMinVT = false;
12264       for (const SDValue &Op : N->ops())
12265         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12266           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12267           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12268           FoundMinVT = true;
12269         }
12270       assert(FoundMinVT && "Concat vector type mismatch");
12271     }
12272
12273     for (const SDValue &Op : N->ops()) {
12274       EVT OpVT = Op.getValueType();
12275       unsigned NumElts = OpVT.getVectorNumElements();
12276
12277       if (ISD::UNDEF == Op.getOpcode())
12278         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12279
12280       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12281         if (SVT.isFloatingPoint()) {
12282           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12283           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12284         } else {
12285           for (unsigned i = 0; i != NumElts; ++i)
12286             Opnds.push_back(
12287                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12288         }
12289       }
12290     }
12291
12292     assert(VT.getVectorNumElements() == Opnds.size() &&
12293            "Concat vector type mismatch");
12294     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12295   }
12296
12297   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12298   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12299     return V;
12300
12301   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12302   // nodes often generate nop CONCAT_VECTOR nodes.
12303   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12304   // place the incoming vectors at the exact same location.
12305   SDValue SingleSource = SDValue();
12306   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12307
12308   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12309     SDValue Op = N->getOperand(i);
12310
12311     if (Op.getOpcode() == ISD::UNDEF)
12312       continue;
12313
12314     // Check if this is the identity extract:
12315     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12316       return SDValue();
12317
12318     // Find the single incoming vector for the extract_subvector.
12319     if (SingleSource.getNode()) {
12320       if (Op.getOperand(0) != SingleSource)
12321         return SDValue();
12322     } else {
12323       SingleSource = Op.getOperand(0);
12324
12325       // Check the source type is the same as the type of the result.
12326       // If not, this concat may extend the vector, so we can not
12327       // optimize it away.
12328       if (SingleSource.getValueType() != N->getValueType(0))
12329         return SDValue();
12330     }
12331
12332     unsigned IdentityIndex = i * PartNumElem;
12333     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12334     // The extract index must be constant.
12335     if (!CS)
12336       return SDValue();
12337
12338     // Check that we are reading from the identity index.
12339     if (CS->getZExtValue() != IdentityIndex)
12340       return SDValue();
12341   }
12342
12343   if (SingleSource.getNode())
12344     return SingleSource;
12345
12346   return SDValue();
12347 }
12348
12349 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12350   EVT NVT = N->getValueType(0);
12351   SDValue V = N->getOperand(0);
12352
12353   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12354     // Combine:
12355     //    (extract_subvec (concat V1, V2, ...), i)
12356     // Into:
12357     //    Vi if possible
12358     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12359     // type.
12360     if (V->getOperand(0).getValueType() != NVT)
12361       return SDValue();
12362     unsigned Idx = N->getConstantOperandVal(1);
12363     unsigned NumElems = NVT.getVectorNumElements();
12364     assert((Idx % NumElems) == 0 &&
12365            "IDX in concat is not a multiple of the result vector length.");
12366     return V->getOperand(Idx / NumElems);
12367   }
12368
12369   // Skip bitcasting
12370   if (V->getOpcode() == ISD::BITCAST)
12371     V = V.getOperand(0);
12372
12373   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12374     SDLoc dl(N);
12375     // Handle only simple case where vector being inserted and vector
12376     // being extracted are of same type, and are half size of larger vectors.
12377     EVT BigVT = V->getOperand(0).getValueType();
12378     EVT SmallVT = V->getOperand(1).getValueType();
12379     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12380       return SDValue();
12381
12382     // Only handle cases where both indexes are constants with the same type.
12383     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12384     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12385
12386     if (InsIdx && ExtIdx &&
12387         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12388         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12389       // Combine:
12390       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12391       // Into:
12392       //    indices are equal or bit offsets are equal => V1
12393       //    otherwise => (extract_subvec V1, ExtIdx)
12394       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12395           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12396         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12397       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12398                          DAG.getNode(ISD::BITCAST, dl,
12399                                      N->getOperand(0).getValueType(),
12400                                      V->getOperand(0)), N->getOperand(1));
12401     }
12402   }
12403
12404   return SDValue();
12405 }
12406
12407 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12408                                                  SDValue V, SelectionDAG &DAG) {
12409   SDLoc DL(V);
12410   EVT VT = V.getValueType();
12411
12412   switch (V.getOpcode()) {
12413   default:
12414     return V;
12415
12416   case ISD::CONCAT_VECTORS: {
12417     EVT OpVT = V->getOperand(0).getValueType();
12418     int OpSize = OpVT.getVectorNumElements();
12419     SmallBitVector OpUsedElements(OpSize, false);
12420     bool FoundSimplification = false;
12421     SmallVector<SDValue, 4> NewOps;
12422     NewOps.reserve(V->getNumOperands());
12423     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12424       SDValue Op = V->getOperand(i);
12425       bool OpUsed = false;
12426       for (int j = 0; j < OpSize; ++j)
12427         if (UsedElements[i * OpSize + j]) {
12428           OpUsedElements[j] = true;
12429           OpUsed = true;
12430         }
12431       NewOps.push_back(
12432           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12433                  : DAG.getUNDEF(OpVT));
12434       FoundSimplification |= Op == NewOps.back();
12435       OpUsedElements.reset();
12436     }
12437     if (FoundSimplification)
12438       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12439     return V;
12440   }
12441
12442   case ISD::INSERT_SUBVECTOR: {
12443     SDValue BaseV = V->getOperand(0);
12444     SDValue SubV = V->getOperand(1);
12445     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12446     if (!IdxN)
12447       return V;
12448
12449     int SubSize = SubV.getValueType().getVectorNumElements();
12450     int Idx = IdxN->getZExtValue();
12451     bool SubVectorUsed = false;
12452     SmallBitVector SubUsedElements(SubSize, false);
12453     for (int i = 0; i < SubSize; ++i)
12454       if (UsedElements[i + Idx]) {
12455         SubVectorUsed = true;
12456         SubUsedElements[i] = true;
12457         UsedElements[i + Idx] = false;
12458       }
12459
12460     // Now recurse on both the base and sub vectors.
12461     SDValue SimplifiedSubV =
12462         SubVectorUsed
12463             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12464             : DAG.getUNDEF(SubV.getValueType());
12465     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12466     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12467       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12468                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12469     return V;
12470   }
12471   }
12472 }
12473
12474 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12475                                        SDValue N1, SelectionDAG &DAG) {
12476   EVT VT = SVN->getValueType(0);
12477   int NumElts = VT.getVectorNumElements();
12478   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12479   for (int M : SVN->getMask())
12480     if (M >= 0 && M < NumElts)
12481       N0UsedElements[M] = true;
12482     else if (M >= NumElts)
12483       N1UsedElements[M - NumElts] = true;
12484
12485   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12486   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12487   if (S0 == N0 && S1 == N1)
12488     return SDValue();
12489
12490   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12491 }
12492
12493 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12494 // or turn a shuffle of a single concat into simpler shuffle then concat.
12495 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12496   EVT VT = N->getValueType(0);
12497   unsigned NumElts = VT.getVectorNumElements();
12498
12499   SDValue N0 = N->getOperand(0);
12500   SDValue N1 = N->getOperand(1);
12501   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12502
12503   SmallVector<SDValue, 4> Ops;
12504   EVT ConcatVT = N0.getOperand(0).getValueType();
12505   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12506   unsigned NumConcats = NumElts / NumElemsPerConcat;
12507
12508   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12509   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12510   // half vector elements.
12511   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12512       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12513                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12514     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12515                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12516     N1 = DAG.getUNDEF(ConcatVT);
12517     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12518   }
12519
12520   // Look at every vector that's inserted. We're looking for exact
12521   // subvector-sized copies from a concatenated vector
12522   for (unsigned I = 0; I != NumConcats; ++I) {
12523     // Make sure we're dealing with a copy.
12524     unsigned Begin = I * NumElemsPerConcat;
12525     bool AllUndef = true, NoUndef = true;
12526     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12527       if (SVN->getMaskElt(J) >= 0)
12528         AllUndef = false;
12529       else
12530         NoUndef = false;
12531     }
12532
12533     if (NoUndef) {
12534       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12535         return SDValue();
12536
12537       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12538         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12539           return SDValue();
12540
12541       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12542       if (FirstElt < N0.getNumOperands())
12543         Ops.push_back(N0.getOperand(FirstElt));
12544       else
12545         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12546
12547     } else if (AllUndef) {
12548       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12549     } else { // Mixed with general masks and undefs, can't do optimization.
12550       return SDValue();
12551     }
12552   }
12553
12554   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12555 }
12556
12557 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12558   EVT VT = N->getValueType(0);
12559   unsigned NumElts = VT.getVectorNumElements();
12560
12561   SDValue N0 = N->getOperand(0);
12562   SDValue N1 = N->getOperand(1);
12563
12564   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12565
12566   // Canonicalize shuffle undef, undef -> undef
12567   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12568     return DAG.getUNDEF(VT);
12569
12570   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12571
12572   // Canonicalize shuffle v, v -> v, undef
12573   if (N0 == N1) {
12574     SmallVector<int, 8> NewMask;
12575     for (unsigned i = 0; i != NumElts; ++i) {
12576       int Idx = SVN->getMaskElt(i);
12577       if (Idx >= (int)NumElts) Idx -= NumElts;
12578       NewMask.push_back(Idx);
12579     }
12580     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12581                                 &NewMask[0]);
12582   }
12583
12584   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12585   if (N0.getOpcode() == ISD::UNDEF) {
12586     SmallVector<int, 8> NewMask;
12587     for (unsigned i = 0; i != NumElts; ++i) {
12588       int Idx = SVN->getMaskElt(i);
12589       if (Idx >= 0) {
12590         if (Idx >= (int)NumElts)
12591           Idx -= NumElts;
12592         else
12593           Idx = -1; // remove reference to lhs
12594       }
12595       NewMask.push_back(Idx);
12596     }
12597     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12598                                 &NewMask[0]);
12599   }
12600
12601   // Remove references to rhs if it is undef
12602   if (N1.getOpcode() == ISD::UNDEF) {
12603     bool Changed = false;
12604     SmallVector<int, 8> NewMask;
12605     for (unsigned i = 0; i != NumElts; ++i) {
12606       int Idx = SVN->getMaskElt(i);
12607       if (Idx >= (int)NumElts) {
12608         Idx = -1;
12609         Changed = true;
12610       }
12611       NewMask.push_back(Idx);
12612     }
12613     if (Changed)
12614       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12615   }
12616
12617   // If it is a splat, check if the argument vector is another splat or a
12618   // build_vector.
12619   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12620     SDNode *V = N0.getNode();
12621
12622     // If this is a bit convert that changes the element type of the vector but
12623     // not the number of vector elements, look through it.  Be careful not to
12624     // look though conversions that change things like v4f32 to v2f64.
12625     if (V->getOpcode() == ISD::BITCAST) {
12626       SDValue ConvInput = V->getOperand(0);
12627       if (ConvInput.getValueType().isVector() &&
12628           ConvInput.getValueType().getVectorNumElements() == NumElts)
12629         V = ConvInput.getNode();
12630     }
12631
12632     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12633       assert(V->getNumOperands() == NumElts &&
12634              "BUILD_VECTOR has wrong number of operands");
12635       SDValue Base;
12636       bool AllSame = true;
12637       for (unsigned i = 0; i != NumElts; ++i) {
12638         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12639           Base = V->getOperand(i);
12640           break;
12641         }
12642       }
12643       // Splat of <u, u, u, u>, return <u, u, u, u>
12644       if (!Base.getNode())
12645         return N0;
12646       for (unsigned i = 0; i != NumElts; ++i) {
12647         if (V->getOperand(i) != Base) {
12648           AllSame = false;
12649           break;
12650         }
12651       }
12652       // Splat of <x, x, x, x>, return <x, x, x, x>
12653       if (AllSame)
12654         return N0;
12655
12656       // Canonicalize any other splat as a build_vector.
12657       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12658       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12659       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12660                                   V->getValueType(0), Ops);
12661
12662       // We may have jumped through bitcasts, so the type of the
12663       // BUILD_VECTOR may not match the type of the shuffle.
12664       if (V->getValueType(0) != VT)
12665         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12666       return NewBV;
12667     }
12668   }
12669
12670   // There are various patterns used to build up a vector from smaller vectors,
12671   // subvectors, or elements. Scan chains of these and replace unused insertions
12672   // or components with undef.
12673   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12674     return S;
12675
12676   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12677       Level < AfterLegalizeVectorOps &&
12678       (N1.getOpcode() == ISD::UNDEF ||
12679       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12680        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12681     SDValue V = partitionShuffleOfConcats(N, DAG);
12682
12683     if (V.getNode())
12684       return V;
12685   }
12686
12687   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12688   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12689   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12690     SmallVector<SDValue, 8> Ops;
12691     for (int M : SVN->getMask()) {
12692       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12693       if (M >= 0) {
12694         int Idx = M % NumElts;
12695         SDValue &S = (M < (int)NumElts ? N0 : N1);
12696         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12697           Op = S.getOperand(Idx);
12698         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12699           if (Idx == 0)
12700             Op = S.getOperand(0);
12701         } else {
12702           // Operand can't be combined - bail out.
12703           break;
12704         }
12705       }
12706       Ops.push_back(Op);
12707     }
12708     if (Ops.size() == VT.getVectorNumElements()) {
12709       // BUILD_VECTOR requires all inputs to be of the same type, find the
12710       // maximum type and extend them all.
12711       EVT SVT = VT.getScalarType();
12712       if (SVT.isInteger())
12713         for (SDValue &Op : Ops)
12714           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12715       if (SVT != VT.getScalarType())
12716         for (SDValue &Op : Ops)
12717           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12718                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12719                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12720       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12721     }
12722   }
12723
12724   // If this shuffle only has a single input that is a bitcasted shuffle,
12725   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12726   // back to their original types.
12727   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12728       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12729       TLI.isTypeLegal(VT)) {
12730
12731     // Peek through the bitcast only if there is one user.
12732     SDValue BC0 = N0;
12733     while (BC0.getOpcode() == ISD::BITCAST) {
12734       if (!BC0.hasOneUse())
12735         break;
12736       BC0 = BC0.getOperand(0);
12737     }
12738
12739     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12740       if (Scale == 1)
12741         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12742
12743       SmallVector<int, 8> NewMask;
12744       for (int M : Mask)
12745         for (int s = 0; s != Scale; ++s)
12746           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12747       return NewMask;
12748     };
12749
12750     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12751       EVT SVT = VT.getScalarType();
12752       EVT InnerVT = BC0->getValueType(0);
12753       EVT InnerSVT = InnerVT.getScalarType();
12754
12755       // Determine which shuffle works with the smaller scalar type.
12756       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12757       EVT ScaleSVT = ScaleVT.getScalarType();
12758
12759       if (TLI.isTypeLegal(ScaleVT) &&
12760           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12761           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12762
12763         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12764         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12765
12766         // Scale the shuffle masks to the smaller scalar type.
12767         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12768         SmallVector<int, 8> InnerMask =
12769             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12770         SmallVector<int, 8> OuterMask =
12771             ScaleShuffleMask(SVN->getMask(), OuterScale);
12772
12773         // Merge the shuffle masks.
12774         SmallVector<int, 8> NewMask;
12775         for (int M : OuterMask)
12776           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12777
12778         // Test for shuffle mask legality over both commutations.
12779         SDValue SV0 = BC0->getOperand(0);
12780         SDValue SV1 = BC0->getOperand(1);
12781         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12782         if (!LegalMask) {
12783           std::swap(SV0, SV1);
12784           ShuffleVectorSDNode::commuteMask(NewMask);
12785           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12786         }
12787
12788         if (LegalMask) {
12789           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12790           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12791           return DAG.getNode(
12792               ISD::BITCAST, SDLoc(N), VT,
12793               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12794         }
12795       }
12796     }
12797   }
12798
12799   // Canonicalize shuffles according to rules:
12800   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12801   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12802   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12803   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12804       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12805       TLI.isTypeLegal(VT)) {
12806     // The incoming shuffle must be of the same type as the result of the
12807     // current shuffle.
12808     assert(N1->getOperand(0).getValueType() == VT &&
12809            "Shuffle types don't match");
12810
12811     SDValue SV0 = N1->getOperand(0);
12812     SDValue SV1 = N1->getOperand(1);
12813     bool HasSameOp0 = N0 == SV0;
12814     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12815     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12816       // Commute the operands of this shuffle so that next rule
12817       // will trigger.
12818       return DAG.getCommutedVectorShuffle(*SVN);
12819   }
12820
12821   // Try to fold according to rules:
12822   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12823   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12824   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12825   // Don't try to fold shuffles with illegal type.
12826   // Only fold if this shuffle is the only user of the other shuffle.
12827   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12828       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12829     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12830
12831     // The incoming shuffle must be of the same type as the result of the
12832     // current shuffle.
12833     assert(OtherSV->getOperand(0).getValueType() == VT &&
12834            "Shuffle types don't match");
12835
12836     SDValue SV0, SV1;
12837     SmallVector<int, 4> Mask;
12838     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12839     // operand, and SV1 as the second operand.
12840     for (unsigned i = 0; i != NumElts; ++i) {
12841       int Idx = SVN->getMaskElt(i);
12842       if (Idx < 0) {
12843         // Propagate Undef.
12844         Mask.push_back(Idx);
12845         continue;
12846       }
12847
12848       SDValue CurrentVec;
12849       if (Idx < (int)NumElts) {
12850         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12851         // shuffle mask to identify which vector is actually referenced.
12852         Idx = OtherSV->getMaskElt(Idx);
12853         if (Idx < 0) {
12854           // Propagate Undef.
12855           Mask.push_back(Idx);
12856           continue;
12857         }
12858
12859         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12860                                            : OtherSV->getOperand(1);
12861       } else {
12862         // This shuffle index references an element within N1.
12863         CurrentVec = N1;
12864       }
12865
12866       // Simple case where 'CurrentVec' is UNDEF.
12867       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12868         Mask.push_back(-1);
12869         continue;
12870       }
12871
12872       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12873       // will be the first or second operand of the combined shuffle.
12874       Idx = Idx % NumElts;
12875       if (!SV0.getNode() || SV0 == CurrentVec) {
12876         // Ok. CurrentVec is the left hand side.
12877         // Update the mask accordingly.
12878         SV0 = CurrentVec;
12879         Mask.push_back(Idx);
12880         continue;
12881       }
12882
12883       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12884       if (SV1.getNode() && SV1 != CurrentVec)
12885         return SDValue();
12886
12887       // Ok. CurrentVec is the right hand side.
12888       // Update the mask accordingly.
12889       SV1 = CurrentVec;
12890       Mask.push_back(Idx + NumElts);
12891     }
12892
12893     // Check if all indices in Mask are Undef. In case, propagate Undef.
12894     bool isUndefMask = true;
12895     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12896       isUndefMask &= Mask[i] < 0;
12897
12898     if (isUndefMask)
12899       return DAG.getUNDEF(VT);
12900
12901     if (!SV0.getNode())
12902       SV0 = DAG.getUNDEF(VT);
12903     if (!SV1.getNode())
12904       SV1 = DAG.getUNDEF(VT);
12905
12906     // Avoid introducing shuffles with illegal mask.
12907     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12908       ShuffleVectorSDNode::commuteMask(Mask);
12909
12910       if (!TLI.isShuffleMaskLegal(Mask, VT))
12911         return SDValue();
12912
12913       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12914       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12915       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12916       std::swap(SV0, SV1);
12917     }
12918
12919     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12920     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12921     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12922     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12923   }
12924
12925   return SDValue();
12926 }
12927
12928 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12929   SDValue InVal = N->getOperand(0);
12930   EVT VT = N->getValueType(0);
12931
12932   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12933   // with a VECTOR_SHUFFLE.
12934   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12935     SDValue InVec = InVal->getOperand(0);
12936     SDValue EltNo = InVal->getOperand(1);
12937
12938     // FIXME: We could support implicit truncation if the shuffle can be
12939     // scaled to a smaller vector scalar type.
12940     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12941     if (C0 && VT == InVec.getValueType() &&
12942         VT.getScalarType() == InVal.getValueType()) {
12943       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12944       int Elt = C0->getZExtValue();
12945       NewMask[0] = Elt;
12946
12947       if (TLI.isShuffleMaskLegal(NewMask, VT))
12948         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12949                                     NewMask);
12950     }
12951   }
12952
12953   return SDValue();
12954 }
12955
12956 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12957   SDValue N0 = N->getOperand(0);
12958   SDValue N2 = N->getOperand(2);
12959
12960   // If the input vector is a concatenation, and the insert replaces
12961   // one of the halves, we can optimize into a single concat_vectors.
12962   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12963       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12964     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12965     EVT VT = N->getValueType(0);
12966
12967     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12968     // (concat_vectors Z, Y)
12969     if (InsIdx == 0)
12970       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12971                          N->getOperand(1), N0.getOperand(1));
12972
12973     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12974     // (concat_vectors X, Z)
12975     if (InsIdx == VT.getVectorNumElements()/2)
12976       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12977                          N0.getOperand(0), N->getOperand(1));
12978   }
12979
12980   return SDValue();
12981 }
12982
12983 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12984   SDValue N0 = N->getOperand(0);
12985
12986   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12987   if (N0->getOpcode() == ISD::FP16_TO_FP)
12988     return N0->getOperand(0);
12989
12990   return SDValue();
12991 }
12992
12993 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12994 /// with the destination vector and a zero vector.
12995 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12996 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12997 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12998   EVT VT = N->getValueType(0);
12999   SDValue LHS = N->getOperand(0);
13000   SDValue RHS = N->getOperand(1);
13001   SDLoc dl(N);
13002
13003   // Make sure we're not running after operation legalization where it
13004   // may have custom lowered the vector shuffles.
13005   if (LegalOperations)
13006     return SDValue();
13007
13008   if (N->getOpcode() != ISD::AND)
13009     return SDValue();
13010
13011   if (RHS.getOpcode() == ISD::BITCAST)
13012     RHS = RHS.getOperand(0);
13013
13014   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13015     return SDValue();
13016
13017   EVT RVT = RHS.getValueType();
13018   unsigned NumElts = RHS.getNumOperands();
13019
13020   // Attempt to create a valid clear mask, splitting the mask into
13021   // sub elements and checking to see if each is
13022   // all zeros or all ones - suitable for shuffle masking.
13023   auto BuildClearMask = [&](int Split) {
13024     int NumSubElts = NumElts * Split;
13025     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13026
13027     SmallVector<int, 8> Indices;
13028     for (int i = 0; i != NumSubElts; ++i) {
13029       int EltIdx = i / Split;
13030       int SubIdx = i % Split;
13031       SDValue Elt = RHS.getOperand(EltIdx);
13032       if (Elt.getOpcode() == ISD::UNDEF) {
13033         Indices.push_back(-1);
13034         continue;
13035       }
13036
13037       APInt Bits;
13038       if (isa<ConstantSDNode>(Elt))
13039         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13040       else if (isa<ConstantFPSDNode>(Elt))
13041         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13042       else
13043         return SDValue();
13044
13045       // Extract the sub element from the constant bit mask.
13046       if (DAG.getDataLayout().isBigEndian()) {
13047         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13048       } else {
13049         Bits = Bits.lshr(SubIdx * NumSubBits);
13050       }
13051
13052       if (Split > 1)
13053         Bits = Bits.trunc(NumSubBits);
13054
13055       if (Bits.isAllOnesValue())
13056         Indices.push_back(i);
13057       else if (Bits == 0)
13058         Indices.push_back(i + NumSubElts);
13059       else
13060         return SDValue();
13061     }
13062
13063     // Let's see if the target supports this vector_shuffle.
13064     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13065     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13066     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13067       return SDValue();
13068
13069     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13070     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13071                                                    DAG.getBitcast(ClearVT, LHS),
13072                                                    Zero, &Indices[0]));
13073   };
13074
13075   // Determine maximum split level (byte level masking).
13076   int MaxSplit = 1;
13077   if (RVT.getScalarSizeInBits() % 8 == 0)
13078     MaxSplit = RVT.getScalarSizeInBits() / 8;
13079
13080   for (int Split = 1; Split <= MaxSplit; ++Split)
13081     if (RVT.getScalarSizeInBits() % Split == 0)
13082       if (SDValue S = BuildClearMask(Split))
13083         return S;
13084
13085   return SDValue();
13086 }
13087
13088 /// Visit a binary vector operation, like ADD.
13089 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13090   assert(N->getValueType(0).isVector() &&
13091          "SimplifyVBinOp only works on vectors!");
13092
13093   SDValue LHS = N->getOperand(0);
13094   SDValue RHS = N->getOperand(1);
13095
13096   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13097   // this operation.
13098   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13099       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13100     // Check if both vectors are constants. If not bail out.
13101     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13102           cast<BuildVectorSDNode>(RHS)->isConstant()))
13103       return SDValue();
13104
13105     SmallVector<SDValue, 8> Ops;
13106     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13107       SDValue LHSOp = LHS.getOperand(i);
13108       SDValue RHSOp = RHS.getOperand(i);
13109
13110       // Can't fold divide by zero.
13111       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13112           N->getOpcode() == ISD::FDIV) {
13113         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13114              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13115           break;
13116       }
13117
13118       EVT VT = LHSOp.getValueType();
13119       EVT RVT = RHSOp.getValueType();
13120       if (RVT != VT) {
13121         // Integer BUILD_VECTOR operands may have types larger than the element
13122         // size (e.g., when the element type is not legal).  Prior to type
13123         // legalization, the types may not match between the two BUILD_VECTORS.
13124         // Truncate one of the operands to make them match.
13125         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13126           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13127         } else {
13128           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13129           VT = RVT;
13130         }
13131       }
13132       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13133                                    LHSOp, RHSOp);
13134       if (FoldOp.getOpcode() != ISD::UNDEF &&
13135           FoldOp.getOpcode() != ISD::Constant &&
13136           FoldOp.getOpcode() != ISD::ConstantFP)
13137         break;
13138       Ops.push_back(FoldOp);
13139       AddToWorklist(FoldOp.getNode());
13140     }
13141
13142     if (Ops.size() == LHS.getNumOperands())
13143       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13144   }
13145
13146   // Try to convert a constant mask AND into a shuffle clear mask.
13147   if (SDValue Shuffle = XformToShuffleWithZero(N))
13148     return Shuffle;
13149
13150   // Type legalization might introduce new shuffles in the DAG.
13151   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13152   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13153   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13154       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13155       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13156       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13157     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13158     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13159
13160     if (SVN0->getMask().equals(SVN1->getMask())) {
13161       EVT VT = N->getValueType(0);
13162       SDValue UndefVector = LHS.getOperand(1);
13163       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13164                                      LHS.getOperand(0), RHS.getOperand(0));
13165       AddUsersToWorklist(N);
13166       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13167                                   &SVN0->getMask()[0]);
13168     }
13169   }
13170
13171   return SDValue();
13172 }
13173
13174 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13175                                     SDValue N1, SDValue N2){
13176   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13177
13178   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13179                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13180
13181   // If we got a simplified select_cc node back from SimplifySelectCC, then
13182   // break it down into a new SETCC node, and a new SELECT node, and then return
13183   // the SELECT node, since we were called with a SELECT node.
13184   if (SCC.getNode()) {
13185     // Check to see if we got a select_cc back (to turn into setcc/select).
13186     // Otherwise, just return whatever node we got back, like fabs.
13187     if (SCC.getOpcode() == ISD::SELECT_CC) {
13188       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13189                                   N0.getValueType(),
13190                                   SCC.getOperand(0), SCC.getOperand(1),
13191                                   SCC.getOperand(4));
13192       AddToWorklist(SETCC.getNode());
13193       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13194                            SCC.getOperand(2), SCC.getOperand(3));
13195     }
13196
13197     return SCC;
13198   }
13199   return SDValue();
13200 }
13201
13202 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13203 /// being selected between, see if we can simplify the select.  Callers of this
13204 /// should assume that TheSelect is deleted if this returns true.  As such, they
13205 /// should return the appropriate thing (e.g. the node) back to the top-level of
13206 /// the DAG combiner loop to avoid it being looked at.
13207 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13208                                     SDValue RHS) {
13209
13210   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13211   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13212   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13213     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13214       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13215       SDValue Sqrt = RHS;
13216       ISD::CondCode CC;
13217       SDValue CmpLHS;
13218       const ConstantFPSDNode *NegZero = nullptr;
13219
13220       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13221         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13222         CmpLHS = TheSelect->getOperand(0);
13223         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13224       } else {
13225         // SELECT or VSELECT
13226         SDValue Cmp = TheSelect->getOperand(0);
13227         if (Cmp.getOpcode() == ISD::SETCC) {
13228           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13229           CmpLHS = Cmp.getOperand(0);
13230           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13231         }
13232       }
13233       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13234           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13235           CC == ISD::SETULT || CC == ISD::SETLT)) {
13236         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13237         CombineTo(TheSelect, Sqrt);
13238         return true;
13239       }
13240     }
13241   }
13242   // Cannot simplify select with vector condition
13243   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13244
13245   // If this is a select from two identical things, try to pull the operation
13246   // through the select.
13247   if (LHS.getOpcode() != RHS.getOpcode() ||
13248       !LHS.hasOneUse() || !RHS.hasOneUse())
13249     return false;
13250
13251   // If this is a load and the token chain is identical, replace the select
13252   // of two loads with a load through a select of the address to load from.
13253   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13254   // constants have been dropped into the constant pool.
13255   if (LHS.getOpcode() == ISD::LOAD) {
13256     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13257     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13258
13259     // Token chains must be identical.
13260     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13261         // Do not let this transformation reduce the number of volatile loads.
13262         LLD->isVolatile() || RLD->isVolatile() ||
13263         // FIXME: If either is a pre/post inc/dec load,
13264         // we'd need to split out the address adjustment.
13265         LLD->isIndexed() || RLD->isIndexed() ||
13266         // If this is an EXTLOAD, the VT's must match.
13267         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13268         // If this is an EXTLOAD, the kind of extension must match.
13269         (LLD->getExtensionType() != RLD->getExtensionType() &&
13270          // The only exception is if one of the extensions is anyext.
13271          LLD->getExtensionType() != ISD::EXTLOAD &&
13272          RLD->getExtensionType() != ISD::EXTLOAD) ||
13273         // FIXME: this discards src value information.  This is
13274         // over-conservative. It would be beneficial to be able to remember
13275         // both potential memory locations.  Since we are discarding
13276         // src value info, don't do the transformation if the memory
13277         // locations are not in the default address space.
13278         LLD->getPointerInfo().getAddrSpace() != 0 ||
13279         RLD->getPointerInfo().getAddrSpace() != 0 ||
13280         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13281                                       LLD->getBasePtr().getValueType()))
13282       return false;
13283
13284     // Check that the select condition doesn't reach either load.  If so,
13285     // folding this will induce a cycle into the DAG.  If not, this is safe to
13286     // xform, so create a select of the addresses.
13287     SDValue Addr;
13288     if (TheSelect->getOpcode() == ISD::SELECT) {
13289       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13290       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13291           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13292         return false;
13293       // The loads must not depend on one another.
13294       if (LLD->isPredecessorOf(RLD) ||
13295           RLD->isPredecessorOf(LLD))
13296         return false;
13297       Addr = DAG.getSelect(SDLoc(TheSelect),
13298                            LLD->getBasePtr().getValueType(),
13299                            TheSelect->getOperand(0), LLD->getBasePtr(),
13300                            RLD->getBasePtr());
13301     } else {  // Otherwise SELECT_CC
13302       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13303       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13304
13305       if ((LLD->hasAnyUseOfValue(1) &&
13306            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13307           (RLD->hasAnyUseOfValue(1) &&
13308            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13309         return false;
13310
13311       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13312                          LLD->getBasePtr().getValueType(),
13313                          TheSelect->getOperand(0),
13314                          TheSelect->getOperand(1),
13315                          LLD->getBasePtr(), RLD->getBasePtr(),
13316                          TheSelect->getOperand(4));
13317     }
13318
13319     SDValue Load;
13320     // It is safe to replace the two loads if they have different alignments,
13321     // but the new load must be the minimum (most restrictive) alignment of the
13322     // inputs.
13323     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13324     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13325     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13326       Load = DAG.getLoad(TheSelect->getValueType(0),
13327                          SDLoc(TheSelect),
13328                          // FIXME: Discards pointer and AA info.
13329                          LLD->getChain(), Addr, MachinePointerInfo(),
13330                          LLD->isVolatile(), LLD->isNonTemporal(),
13331                          isInvariant, Alignment);
13332     } else {
13333       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13334                             RLD->getExtensionType() : LLD->getExtensionType(),
13335                             SDLoc(TheSelect),
13336                             TheSelect->getValueType(0),
13337                             // FIXME: Discards pointer and AA info.
13338                             LLD->getChain(), Addr, MachinePointerInfo(),
13339                             LLD->getMemoryVT(), LLD->isVolatile(),
13340                             LLD->isNonTemporal(), isInvariant, Alignment);
13341     }
13342
13343     // Users of the select now use the result of the load.
13344     CombineTo(TheSelect, Load);
13345
13346     // Users of the old loads now use the new load's chain.  We know the
13347     // old-load value is dead now.
13348     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13349     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13350     return true;
13351   }
13352
13353   return false;
13354 }
13355
13356 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13357 /// where 'cond' is the comparison specified by CC.
13358 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13359                                       SDValue N2, SDValue N3,
13360                                       ISD::CondCode CC, bool NotExtCompare) {
13361   // (x ? y : y) -> y.
13362   if (N2 == N3) return N2;
13363
13364   EVT VT = N2.getValueType();
13365   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13366   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13367
13368   // Determine if the condition we're dealing with is constant
13369   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13370                               N0, N1, CC, DL, false);
13371   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13372
13373   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13374     // fold select_cc true, x, y -> x
13375     // fold select_cc false, x, y -> y
13376     return !SCCC->isNullValue() ? N2 : N3;
13377   }
13378
13379   // Check to see if we can simplify the select into an fabs node
13380   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13381     // Allow either -0.0 or 0.0
13382     if (CFP->isZero()) {
13383       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13384       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13385           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13386           N2 == N3.getOperand(0))
13387         return DAG.getNode(ISD::FABS, DL, VT, N0);
13388
13389       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13390       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13391           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13392           N2.getOperand(0) == N3)
13393         return DAG.getNode(ISD::FABS, DL, VT, N3);
13394     }
13395   }
13396
13397   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13398   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13399   // in it.  This is a win when the constant is not otherwise available because
13400   // it replaces two constant pool loads with one.  We only do this if the FP
13401   // type is known to be legal, because if it isn't, then we are before legalize
13402   // types an we want the other legalization to happen first (e.g. to avoid
13403   // messing with soft float) and if the ConstantFP is not legal, because if
13404   // it is legal, we may not need to store the FP constant in a constant pool.
13405   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13406     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13407       if (TLI.isTypeLegal(N2.getValueType()) &&
13408           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13409                TargetLowering::Legal &&
13410            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13411            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13412           // If both constants have multiple uses, then we won't need to do an
13413           // extra load, they are likely around in registers for other users.
13414           (TV->hasOneUse() || FV->hasOneUse())) {
13415         Constant *Elts[] = {
13416           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13417           const_cast<ConstantFP*>(TV->getConstantFPValue())
13418         };
13419         Type *FPTy = Elts[0]->getType();
13420         const DataLayout &TD = DAG.getDataLayout();
13421
13422         // Create a ConstantArray of the two constants.
13423         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13424         SDValue CPIdx =
13425             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13426                                 TD.getPrefTypeAlignment(FPTy));
13427         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13428
13429         // Get the offsets to the 0 and 1 element of the array so that we can
13430         // select between them.
13431         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13432         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13433         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13434
13435         SDValue Cond = DAG.getSetCC(DL,
13436                                     getSetCCResultType(N0.getValueType()),
13437                                     N0, N1, CC);
13438         AddToWorklist(Cond.getNode());
13439         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13440                                           Cond, One, Zero);
13441         AddToWorklist(CstOffset.getNode());
13442         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13443                             CstOffset);
13444         AddToWorklist(CPIdx.getNode());
13445         return DAG.getLoad(
13446             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13447             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13448             false, false, false, Alignment);
13449       }
13450     }
13451
13452   // Check to see if we can perform the "gzip trick", transforming
13453   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13454   if (isNullConstant(N3) && CC == ISD::SETLT &&
13455       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13456        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13457     EVT XType = N0.getValueType();
13458     EVT AType = N2.getValueType();
13459     if (XType.bitsGE(AType)) {
13460       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13461       // single-bit constant.
13462       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13463         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13464         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13465         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13466                                        getShiftAmountTy(N0.getValueType()));
13467         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13468                                     XType, N0, ShCt);
13469         AddToWorklist(Shift.getNode());
13470
13471         if (XType.bitsGT(AType)) {
13472           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13473           AddToWorklist(Shift.getNode());
13474         }
13475
13476         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13477       }
13478
13479       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13480                                   XType, N0,
13481                                   DAG.getConstant(XType.getSizeInBits() - 1,
13482                                                   SDLoc(N0),
13483                                          getShiftAmountTy(N0.getValueType())));
13484       AddToWorklist(Shift.getNode());
13485
13486       if (XType.bitsGT(AType)) {
13487         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13488         AddToWorklist(Shift.getNode());
13489       }
13490
13491       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13492     }
13493   }
13494
13495   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13496   // where y is has a single bit set.
13497   // A plaintext description would be, we can turn the SELECT_CC into an AND
13498   // when the condition can be materialized as an all-ones register.  Any
13499   // single bit-test can be materialized as an all-ones register with
13500   // shift-left and shift-right-arith.
13501   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13502       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13503     SDValue AndLHS = N0->getOperand(0);
13504     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13505     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13506       // Shift the tested bit over the sign bit.
13507       APInt AndMask = ConstAndRHS->getAPIntValue();
13508       SDValue ShlAmt =
13509         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13510                         getShiftAmountTy(AndLHS.getValueType()));
13511       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13512
13513       // Now arithmetic right shift it all the way over, so the result is either
13514       // all-ones, or zero.
13515       SDValue ShrAmt =
13516         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13517                         getShiftAmountTy(Shl.getValueType()));
13518       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13519
13520       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13521     }
13522   }
13523
13524   // fold select C, 16, 0 -> shl C, 4
13525   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13526       TLI.getBooleanContents(N0.getValueType()) ==
13527           TargetLowering::ZeroOrOneBooleanContent) {
13528
13529     // If the caller doesn't want us to simplify this into a zext of a compare,
13530     // don't do it.
13531     if (NotExtCompare && N2C->isOne())
13532       return SDValue();
13533
13534     // Get a SetCC of the condition
13535     // NOTE: Don't create a SETCC if it's not legal on this target.
13536     if (!LegalOperations ||
13537         TLI.isOperationLegal(ISD::SETCC,
13538           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13539       SDValue Temp, SCC;
13540       // cast from setcc result type to select result type
13541       if (LegalTypes) {
13542         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13543                             N0, N1, CC);
13544         if (N2.getValueType().bitsLT(SCC.getValueType()))
13545           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13546                                         N2.getValueType());
13547         else
13548           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13549                              N2.getValueType(), SCC);
13550       } else {
13551         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13552         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13553                            N2.getValueType(), SCC);
13554       }
13555
13556       AddToWorklist(SCC.getNode());
13557       AddToWorklist(Temp.getNode());
13558
13559       if (N2C->isOne())
13560         return Temp;
13561
13562       // shl setcc result by log2 n2c
13563       return DAG.getNode(
13564           ISD::SHL, DL, N2.getValueType(), Temp,
13565           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13566                           getShiftAmountTy(Temp.getValueType())));
13567     }
13568   }
13569
13570   // Check to see if this is the equivalent of setcc
13571   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13572   // otherwise, go ahead with the folds.
13573   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13574     EVT XType = N0.getValueType();
13575     if (!LegalOperations ||
13576         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13577       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13578       if (Res.getValueType() != VT)
13579         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13580       return Res;
13581     }
13582
13583     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13584     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13585         (!LegalOperations ||
13586          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13587       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13588       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13589                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13590                                          SDLoc(Ctlz),
13591                                        getShiftAmountTy(Ctlz.getValueType())));
13592     }
13593     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13594     if (isNullConstant(N1) && CC == ISD::SETGT) {
13595       SDLoc DL(N0);
13596       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13597                                   XType, DAG.getConstant(0, DL, XType), N0);
13598       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13599       return DAG.getNode(ISD::SRL, DL, XType,
13600                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13601                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13602                                          getShiftAmountTy(XType)));
13603     }
13604     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13605     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13606       SDLoc DL(N0);
13607       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13608                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13609                                          getShiftAmountTy(N0.getValueType())));
13610       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13611                                                                     XType));
13612     }
13613   }
13614
13615   // Check to see if this is an integer abs.
13616   // select_cc setg[te] X,  0,  X, -X ->
13617   // select_cc setgt    X, -1,  X, -X ->
13618   // select_cc setl[te] X,  0, -X,  X ->
13619   // select_cc setlt    X,  1, -X,  X ->
13620   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13621   if (N1C) {
13622     ConstantSDNode *SubC = nullptr;
13623     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13624          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13625         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13626       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13627     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13628               (N1C->isOne() && CC == ISD::SETLT)) &&
13629              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13630       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13631
13632     EVT XType = N0.getValueType();
13633     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13634       SDLoc DL(N0);
13635       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13636                                   N0,
13637                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13638                                          getShiftAmountTy(N0.getValueType())));
13639       SDValue Add = DAG.getNode(ISD::ADD, DL,
13640                                 XType, N0, Shift);
13641       AddToWorklist(Shift.getNode());
13642       AddToWorklist(Add.getNode());
13643       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13644     }
13645   }
13646
13647   return SDValue();
13648 }
13649
13650 /// This is a stub for TargetLowering::SimplifySetCC.
13651 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13652                                    SDValue N1, ISD::CondCode Cond,
13653                                    SDLoc DL, bool foldBooleans) {
13654   TargetLowering::DAGCombinerInfo
13655     DagCombineInfo(DAG, Level, false, this);
13656   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13657 }
13658
13659 /// Given an ISD::SDIV node expressing a divide by constant, return
13660 /// a DAG expression to select that will generate the same value by multiplying
13661 /// by a magic number.
13662 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13663 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13664   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13665   if (!C)
13666     return SDValue();
13667
13668   // Avoid division by zero.
13669   if (C->isNullValue())
13670     return SDValue();
13671
13672   std::vector<SDNode*> Built;
13673   SDValue S =
13674       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13675
13676   for (SDNode *N : Built)
13677     AddToWorklist(N);
13678   return S;
13679 }
13680
13681 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13682 /// DAG expression that will generate the same value by right shifting.
13683 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13684   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13685   if (!C)
13686     return SDValue();
13687
13688   // Avoid division by zero.
13689   if (C->isNullValue())
13690     return SDValue();
13691
13692   std::vector<SDNode *> Built;
13693   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13694
13695   for (SDNode *N : Built)
13696     AddToWorklist(N);
13697   return S;
13698 }
13699
13700 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13701 /// expression that will generate the same value by multiplying by a magic
13702 /// number.
13703 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13704 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13705   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13706   if (!C)
13707     return SDValue();
13708
13709   // Avoid division by zero.
13710   if (C->isNullValue())
13711     return SDValue();
13712
13713   std::vector<SDNode*> Built;
13714   SDValue S =
13715       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13716
13717   for (SDNode *N : Built)
13718     AddToWorklist(N);
13719   return S;
13720 }
13721
13722 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13723   if (Level >= AfterLegalizeDAG)
13724     return SDValue();
13725
13726   // Expose the DAG combiner to the target combiner implementations.
13727   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13728
13729   unsigned Iterations = 0;
13730   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13731     if (Iterations) {
13732       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13733       // For the reciprocal, we need to find the zero of the function:
13734       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13735       //     =>
13736       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13737       //     does not require additional intermediate precision]
13738       EVT VT = Op.getValueType();
13739       SDLoc DL(Op);
13740       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13741
13742       AddToWorklist(Est.getNode());
13743
13744       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13745       for (unsigned i = 0; i < Iterations; ++i) {
13746         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13747         AddToWorklist(NewEst.getNode());
13748
13749         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13750         AddToWorklist(NewEst.getNode());
13751
13752         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13753         AddToWorklist(NewEst.getNode());
13754
13755         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13756         AddToWorklist(Est.getNode());
13757       }
13758     }
13759     return Est;
13760   }
13761
13762   return SDValue();
13763 }
13764
13765 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13766 /// For the reciprocal sqrt, we need to find the zero of the function:
13767 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13768 ///     =>
13769 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13770 /// As a result, we precompute A/2 prior to the iteration loop.
13771 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13772                                           unsigned Iterations) {
13773   EVT VT = Arg.getValueType();
13774   SDLoc DL(Arg);
13775   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13776
13777   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13778   // this entire sequence requires only one FP constant.
13779   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13780   AddToWorklist(HalfArg.getNode());
13781
13782   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13783   AddToWorklist(HalfArg.getNode());
13784
13785   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13786   for (unsigned i = 0; i < Iterations; ++i) {
13787     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13788     AddToWorklist(NewEst.getNode());
13789
13790     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13791     AddToWorklist(NewEst.getNode());
13792
13793     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13794     AddToWorklist(NewEst.getNode());
13795
13796     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13797     AddToWorklist(Est.getNode());
13798   }
13799   return Est;
13800 }
13801
13802 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13803 /// For the reciprocal sqrt, we need to find the zero of the function:
13804 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13805 ///     =>
13806 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13807 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13808                                           unsigned Iterations) {
13809   EVT VT = Arg.getValueType();
13810   SDLoc DL(Arg);
13811   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13812   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13813
13814   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13815   for (unsigned i = 0; i < Iterations; ++i) {
13816     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13817     AddToWorklist(HalfEst.getNode());
13818
13819     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13820     AddToWorklist(Est.getNode());
13821
13822     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13823     AddToWorklist(Est.getNode());
13824
13825     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13826     AddToWorklist(Est.getNode());
13827
13828     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13829     AddToWorklist(Est.getNode());
13830   }
13831   return Est;
13832 }
13833
13834 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13835   if (Level >= AfterLegalizeDAG)
13836     return SDValue();
13837
13838   // Expose the DAG combiner to the target combiner implementations.
13839   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13840   unsigned Iterations = 0;
13841   bool UseOneConstNR = false;
13842   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13843     AddToWorklist(Est.getNode());
13844     if (Iterations) {
13845       Est = UseOneConstNR ?
13846         BuildRsqrtNROneConst(Op, Est, Iterations) :
13847         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13848     }
13849     return Est;
13850   }
13851
13852   return SDValue();
13853 }
13854
13855 /// Return true if base is a frame index, which is known not to alias with
13856 /// anything but itself.  Provides base object and offset as results.
13857 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13858                            const GlobalValue *&GV, const void *&CV) {
13859   // Assume it is a primitive operation.
13860   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13861
13862   // If it's an adding a simple constant then integrate the offset.
13863   if (Base.getOpcode() == ISD::ADD) {
13864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13865       Base = Base.getOperand(0);
13866       Offset += C->getZExtValue();
13867     }
13868   }
13869
13870   // Return the underlying GlobalValue, and update the Offset.  Return false
13871   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13872   // by multiple nodes with different offsets.
13873   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13874     GV = G->getGlobal();
13875     Offset += G->getOffset();
13876     return false;
13877   }
13878
13879   // Return the underlying Constant value, and update the Offset.  Return false
13880   // for ConstantSDNodes since the same constant pool entry may be represented
13881   // by multiple nodes with different offsets.
13882   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13883     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13884                                          : (const void *)C->getConstVal();
13885     Offset += C->getOffset();
13886     return false;
13887   }
13888   // If it's any of the following then it can't alias with anything but itself.
13889   return isa<FrameIndexSDNode>(Base);
13890 }
13891
13892 /// Return true if there is any possibility that the two addresses overlap.
13893 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13894   // If they are the same then they must be aliases.
13895   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13896
13897   // If they are both volatile then they cannot be reordered.
13898   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13899
13900   // If one operation reads from invariant memory, and the other may store, they
13901   // cannot alias. These should really be checking the equivalent of mayWrite,
13902   // but it only matters for memory nodes other than load /store.
13903   if (Op0->isInvariant() && Op1->writeMem())
13904     return false;
13905
13906   if (Op1->isInvariant() && Op0->writeMem())
13907     return false;
13908
13909   // Gather base node and offset information.
13910   SDValue Base1, Base2;
13911   int64_t Offset1, Offset2;
13912   const GlobalValue *GV1, *GV2;
13913   const void *CV1, *CV2;
13914   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13915                                       Base1, Offset1, GV1, CV1);
13916   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13917                                       Base2, Offset2, GV2, CV2);
13918
13919   // If they have a same base address then check to see if they overlap.
13920   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13921     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13922              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13923
13924   // It is possible for different frame indices to alias each other, mostly
13925   // when tail call optimization reuses return address slots for arguments.
13926   // To catch this case, look up the actual index of frame indices to compute
13927   // the real alias relationship.
13928   if (isFrameIndex1 && isFrameIndex2) {
13929     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13930     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13931     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13932     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13933              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13934   }
13935
13936   // Otherwise, if we know what the bases are, and they aren't identical, then
13937   // we know they cannot alias.
13938   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13939     return false;
13940
13941   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13942   // compared to the size and offset of the access, we may be able to prove they
13943   // do not alias.  This check is conservative for now to catch cases created by
13944   // splitting vector types.
13945   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13946       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13947       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13948        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13949       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13950     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13951     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13952
13953     // There is no overlap between these relatively aligned accesses of similar
13954     // size, return no alias.
13955     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13956         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13957       return false;
13958   }
13959
13960   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13961                    ? CombinerGlobalAA
13962                    : DAG.getSubtarget().useAA();
13963 #ifndef NDEBUG
13964   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13965       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13966     UseAA = false;
13967 #endif
13968   if (UseAA &&
13969       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13970     // Use alias analysis information.
13971     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13972                                  Op1->getSrcValueOffset());
13973     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13974         Op0->getSrcValueOffset() - MinOffset;
13975     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13976         Op1->getSrcValueOffset() - MinOffset;
13977     AliasResult AAResult =
13978         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
13979                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13980                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
13981                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13982     if (AAResult == NoAlias)
13983       return false;
13984   }
13985
13986   // Otherwise we have to assume they alias.
13987   return true;
13988 }
13989
13990 /// Walk up chain skipping non-aliasing memory nodes,
13991 /// looking for aliasing nodes and adding them to the Aliases vector.
13992 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13993                                    SmallVectorImpl<SDValue> &Aliases) {
13994   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13995   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13996
13997   // Get alias information for node.
13998   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13999
14000   // Starting off.
14001   Chains.push_back(OriginalChain);
14002   unsigned Depth = 0;
14003
14004   // Look at each chain and determine if it is an alias.  If so, add it to the
14005   // aliases list.  If not, then continue up the chain looking for the next
14006   // candidate.
14007   while (!Chains.empty()) {
14008     SDValue Chain = Chains.pop_back_val();
14009
14010     // For TokenFactor nodes, look at each operand and only continue up the
14011     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14012     // find more and revert to original chain since the xform is unlikely to be
14013     // profitable.
14014     //
14015     // FIXME: The depth check could be made to return the last non-aliasing
14016     // chain we found before we hit a tokenfactor rather than the original
14017     // chain.
14018     if (Depth > 6 || Aliases.size() == 2) {
14019       Aliases.clear();
14020       Aliases.push_back(OriginalChain);
14021       return;
14022     }
14023
14024     // Don't bother if we've been before.
14025     if (!Visited.insert(Chain.getNode()).second)
14026       continue;
14027
14028     switch (Chain.getOpcode()) {
14029     case ISD::EntryToken:
14030       // Entry token is ideal chain operand, but handled in FindBetterChain.
14031       break;
14032
14033     case ISD::LOAD:
14034     case ISD::STORE: {
14035       // Get alias information for Chain.
14036       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14037           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14038
14039       // If chain is alias then stop here.
14040       if (!(IsLoad && IsOpLoad) &&
14041           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14042         Aliases.push_back(Chain);
14043       } else {
14044         // Look further up the chain.
14045         Chains.push_back(Chain.getOperand(0));
14046         ++Depth;
14047       }
14048       break;
14049     }
14050
14051     case ISD::TokenFactor:
14052       // We have to check each of the operands of the token factor for "small"
14053       // token factors, so we queue them up.  Adding the operands to the queue
14054       // (stack) in reverse order maintains the original order and increases the
14055       // likelihood that getNode will find a matching token factor (CSE.)
14056       if (Chain.getNumOperands() > 16) {
14057         Aliases.push_back(Chain);
14058         break;
14059       }
14060       for (unsigned n = Chain.getNumOperands(); n;)
14061         Chains.push_back(Chain.getOperand(--n));
14062       ++Depth;
14063       break;
14064
14065     default:
14066       // For all other instructions we will just have to take what we can get.
14067       Aliases.push_back(Chain);
14068       break;
14069     }
14070   }
14071
14072   // We need to be careful here to also search for aliases through the
14073   // value operand of a store, etc. Consider the following situation:
14074   //   Token1 = ...
14075   //   L1 = load Token1, %52
14076   //   S1 = store Token1, L1, %51
14077   //   L2 = load Token1, %52+8
14078   //   S2 = store Token1, L2, %51+8
14079   //   Token2 = Token(S1, S2)
14080   //   L3 = load Token2, %53
14081   //   S3 = store Token2, L3, %52
14082   //   L4 = load Token2, %53+8
14083   //   S4 = store Token2, L4, %52+8
14084   // If we search for aliases of S3 (which loads address %52), and we look
14085   // only through the chain, then we'll miss the trivial dependence on L1
14086   // (which also loads from %52). We then might change all loads and
14087   // stores to use Token1 as their chain operand, which could result in
14088   // copying %53 into %52 before copying %52 into %51 (which should
14089   // happen first).
14090   //
14091   // The problem is, however, that searching for such data dependencies
14092   // can become expensive, and the cost is not directly related to the
14093   // chain depth. Instead, we'll rule out such configurations here by
14094   // insisting that we've visited all chain users (except for users
14095   // of the original chain, which is not necessary). When doing this,
14096   // we need to look through nodes we don't care about (otherwise, things
14097   // like register copies will interfere with trivial cases).
14098
14099   SmallVector<const SDNode *, 16> Worklist;
14100   for (const SDNode *N : Visited)
14101     if (N != OriginalChain.getNode())
14102       Worklist.push_back(N);
14103
14104   while (!Worklist.empty()) {
14105     const SDNode *M = Worklist.pop_back_val();
14106
14107     // We have already visited M, and want to make sure we've visited any uses
14108     // of M that we care about. For uses that we've not visisted, and don't
14109     // care about, queue them to the worklist.
14110
14111     for (SDNode::use_iterator UI = M->use_begin(),
14112          UIE = M->use_end(); UI != UIE; ++UI)
14113       if (UI.getUse().getValueType() == MVT::Other &&
14114           Visited.insert(*UI).second) {
14115         if (isa<MemSDNode>(*UI)) {
14116           // We've not visited this use, and we care about it (it could have an
14117           // ordering dependency with the original node).
14118           Aliases.clear();
14119           Aliases.push_back(OriginalChain);
14120           return;
14121         }
14122
14123         // We've not visited this use, but we don't care about it. Mark it as
14124         // visited and enqueue it to the worklist.
14125         Worklist.push_back(*UI);
14126       }
14127   }
14128 }
14129
14130 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14131 /// (aliasing node.)
14132 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14133   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14134
14135   // Accumulate all the aliases to this node.
14136   GatherAllAliases(N, OldChain, Aliases);
14137
14138   // If no operands then chain to entry token.
14139   if (Aliases.size() == 0)
14140     return DAG.getEntryNode();
14141
14142   // If a single operand then chain to it.  We don't need to revisit it.
14143   if (Aliases.size() == 1)
14144     return Aliases[0];
14145
14146   // Construct a custom tailored token factor.
14147   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14148 }
14149
14150 /// This is the entry point for the file.
14151 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14152                            CodeGenOpt::Level OptLevel) {
14153   /// This is the main entry point to this class.
14154   DAGCombiner(*this, AA, OptLevel).Run(Level);
14155 }