propagate IR-level fast-math-flags to DAG nodes, disabled by default
[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 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
342     SDValue BuildSDIV(SDNode *N);
343     SDValue BuildSDIVPow2(SDNode *N);
344     SDValue BuildUDIV(SDNode *N);
345     SDValue BuildReciprocalEstimate(SDValue Op);
346     SDValue BuildRsqrtEstimate(SDValue Op);
347     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
349     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350                                bool DemandHighBits = true);
351     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
352     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353                               SDValue InnerPos, SDValue InnerNeg,
354                               unsigned PosOpcode, unsigned NegOpcode,
355                               SDLoc DL);
356     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
357     SDValue ReduceLoadWidth(SDNode *N);
358     SDValue ReduceLoadOpStoreWidth(SDNode *N);
359     SDValue TransformFPLoadStorePair(SDNode *N);
360     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
361     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
362
363     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
364
365     /// Walk up chain skipping non-aliasing memory nodes,
366     /// looking for aliasing nodes and adding them to the Aliases vector.
367     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
368                           SmallVectorImpl<SDValue> &Aliases);
369
370     /// Return true if there is any possibility that the two addresses overlap.
371     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
372
373     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374     /// chain (aliasing node.)
375     SDValue FindBetterChain(SDNode *N, SDValue Chain);
376
377     /// Holds a pointer to an LSBaseSDNode as well as information on where it
378     /// is located in a sequence of memory operations connected by a chain.
379     struct MemOpLink {
380       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382       // Ptr to the mem node.
383       LSBaseSDNode *MemNode;
384       // Offset from the base ptr.
385       int64_t OffsetFromBase;
386       // What is the sequence number of this mem node.
387       // Lowest mem operand in the DAG starts at zero.
388       unsigned SequenceNum;
389     };
390
391     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
392     /// constant build_vector of the stored constant values in Stores.
393     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
394                                          SDLoc SL,
395                                          ArrayRef<MemOpLink> Stores,
396                                          EVT Ty) const;
397
398     /// This is a helper function for MergeConsecutiveStores. When the source
399     /// elements of the consecutive stores are all constants or all extracted
400     /// vector elements, try to merge them into one larger store.
401     /// \return True if a merged store was created.
402     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
403                                          EVT MemVT, unsigned NumElem,
404                                          bool IsConstantSrc, bool UseVector);
405
406     /// Merge consecutive store operations into a wide store.
407     /// This optimization uses wide integers or vectors when possible.
408     /// \return True if some memory operations were changed.
409     bool MergeConsecutiveStores(StoreSDNode *N);
410
411     /// \brief Try to transform a truncation where C is a constant:
412     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
413     ///
414     /// \p N needs to be a truncation and its first operand an AND. Other
415     /// requirements are checked by the function (e.g. that trunc is
416     /// single-use) and if missed an empty SDValue is returned.
417     SDValue distributeTruncateThroughAnd(SDNode *N);
418
419   public:
420     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
421         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
422           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
423       auto *F = DAG.getMachineFunction().getFunction();
424       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
425                     F->hasFnAttribute(Attribute::MinSize);
426     }
427
428     /// Runs the dag combiner on all nodes in the work list
429     void Run(CombineLevel AtLevel);
430
431     SelectionDAG &getDAG() const { return DAG; }
432
433     /// Returns a type large enough to hold any valid shift amount - before type
434     /// legalization these can be huge.
435     EVT getShiftAmountTy(EVT LHSTy) {
436       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
437       if (LHSTy.isVector())
438         return LHSTy;
439       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
440                         : TLI.getPointerTy();
441     }
442
443     /// This method returns true if we are running before type legalization or
444     /// if the specified VT is legal.
445     bool isTypeLegal(const EVT &VT) {
446       if (!LegalTypes) return true;
447       return TLI.isTypeLegal(VT);
448     }
449
450     /// Convenience wrapper around TargetLowering::getSetCCResultType
451     EVT getSetCCResultType(EVT VT) const {
452       return TLI.getSetCCResultType(*DAG.getContext(), VT);
453     }
454   };
455 }
456
457
458 namespace {
459 /// This class is a DAGUpdateListener that removes any deleted
460 /// nodes from the worklist.
461 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
462   DAGCombiner &DC;
463 public:
464   explicit WorklistRemover(DAGCombiner &dc)
465     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
466
467   void NodeDeleted(SDNode *N, SDNode *E) override {
468     DC.removeFromWorklist(N);
469   }
470 };
471 }
472
473 //===----------------------------------------------------------------------===//
474 //  TargetLowering::DAGCombinerInfo implementation
475 //===----------------------------------------------------------------------===//
476
477 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
478   ((DAGCombiner*)DC)->AddToWorklist(N);
479 }
480
481 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
482   ((DAGCombiner*)DC)->removeFromWorklist(N);
483 }
484
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
487   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
488 }
489
490 SDValue TargetLowering::DAGCombinerInfo::
491 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
492   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
493 }
494
495
496 SDValue TargetLowering::DAGCombinerInfo::
497 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
498   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
499 }
500
501 void TargetLowering::DAGCombinerInfo::
502 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
503   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
504 }
505
506 //===----------------------------------------------------------------------===//
507 // Helper Functions
508 //===----------------------------------------------------------------------===//
509
510 void DAGCombiner::deleteAndRecombine(SDNode *N) {
511   removeFromWorklist(N);
512
513   // If the operands of this node are only used by the node, they will now be
514   // dead. Make sure to re-visit them and recursively delete dead nodes.
515   for (const SDValue &Op : N->ops())
516     // For an operand generating multiple values, one of the values may
517     // become dead allowing further simplification (e.g. split index
518     // arithmetic from an indexed load).
519     if (Op->hasOneUse() || Op->getNumValues() > 1)
520       AddToWorklist(Op.getNode());
521
522   DAG.DeleteNode(N);
523 }
524
525 /// Return 1 if we can compute the negated form of the specified expression for
526 /// the same cost as the expression itself, or 2 if we can compute the negated
527 /// form more cheaply than the expression itself.
528 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
529                                const TargetLowering &TLI,
530                                const TargetOptions *Options,
531                                unsigned Depth = 0) {
532   // fneg is removable even if it has multiple uses.
533   if (Op.getOpcode() == ISD::FNEG) return 2;
534
535   // Don't allow anything with multiple uses.
536   if (!Op.hasOneUse()) return 0;
537
538   // Don't recurse exponentially.
539   if (Depth > 6) return 0;
540
541   switch (Op.getOpcode()) {
542   default: return false;
543   case ISD::ConstantFP:
544     // Don't invert constant FP values after legalize.  The negated constant
545     // isn't necessarily legal.
546     return LegalOperations ? 0 : 1;
547   case ISD::FADD:
548     // FIXME: determine better conditions for this xform.
549     if (!Options->UnsafeFPMath) return 0;
550
551     // After operation legalization, it might not be legal to create new FSUBs.
552     if (LegalOperations &&
553         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
554       return 0;
555
556     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
557     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
558                                     Options, Depth + 1))
559       return V;
560     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
561     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
562                               Depth + 1);
563   case ISD::FSUB:
564     // We can't turn -(A-B) into B-A when we honor signed zeros.
565     if (!Options->UnsafeFPMath) return 0;
566
567     // fold (fneg (fsub A, B)) -> (fsub B, A)
568     return 1;
569
570   case ISD::FMUL:
571   case ISD::FDIV:
572     if (Options->HonorSignDependentRoundingFPMath()) return 0;
573
574     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
575     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
576                                     Options, Depth + 1))
577       return V;
578
579     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
580                               Depth + 1);
581
582   case ISD::FP_EXTEND:
583   case ISD::FP_ROUND:
584   case ISD::FSIN:
585     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
586                               Depth + 1);
587   }
588 }
589
590 /// If isNegatibleForFree returns true, return the newly negated expression.
591 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
592                                     bool LegalOperations, unsigned Depth = 0) {
593   const TargetOptions &Options = DAG.getTarget().Options;
594   // fneg is removable even if it has multiple uses.
595   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
596
597   // Don't allow anything with multiple uses.
598   assert(Op.hasOneUse() && "Unknown reuse!");
599
600   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
601   switch (Op.getOpcode()) {
602   default: llvm_unreachable("Unknown code");
603   case ISD::ConstantFP: {
604     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
605     V.changeSign();
606     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
607   }
608   case ISD::FADD:
609     // FIXME: determine better conditions for this xform.
610     assert(Options.UnsafeFPMath);
611
612     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
613     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
614                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
615       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
616                          GetNegatedExpression(Op.getOperand(0), DAG,
617                                               LegalOperations, Depth+1),
618                          Op.getOperand(1));
619     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
620     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621                        GetNegatedExpression(Op.getOperand(1), DAG,
622                                             LegalOperations, Depth+1),
623                        Op.getOperand(0));
624   case ISD::FSUB:
625     // We can't turn -(A-B) into B-A when we honor signed zeros.
626     assert(Options.UnsafeFPMath);
627
628     // fold (fneg (fsub 0, B)) -> B
629     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
630       if (N0CFP->isZero())
631         return Op.getOperand(1);
632
633     // fold (fneg (fsub A, B)) -> (fsub B, A)
634     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
635                        Op.getOperand(1), Op.getOperand(0));
636
637   case ISD::FMUL:
638   case ISD::FDIV:
639     assert(!Options.HonorSignDependentRoundingFPMath());
640
641     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
642     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
643                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
644       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
645                          GetNegatedExpression(Op.getOperand(0), DAG,
646                                               LegalOperations, Depth+1),
647                          Op.getOperand(1));
648
649     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
650     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
651                        Op.getOperand(0),
652                        GetNegatedExpression(Op.getOperand(1), DAG,
653                                             LegalOperations, Depth+1));
654
655   case ISD::FP_EXTEND:
656   case ISD::FSIN:
657     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
658                        GetNegatedExpression(Op.getOperand(0), DAG,
659                                             LegalOperations, Depth+1));
660   case ISD::FP_ROUND:
661       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
662                          GetNegatedExpression(Op.getOperand(0), DAG,
663                                               LegalOperations, Depth+1),
664                          Op.getOperand(1));
665   }
666 }
667
668 // Return true if this node is a setcc, or is a select_cc
669 // that selects between the target values used for true and false, making it
670 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
671 // the appropriate nodes based on the type of node we are checking. This
672 // simplifies life a bit for the callers.
673 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
674                                     SDValue &CC) const {
675   if (N.getOpcode() == ISD::SETCC) {
676     LHS = N.getOperand(0);
677     RHS = N.getOperand(1);
678     CC  = N.getOperand(2);
679     return true;
680   }
681
682   if (N.getOpcode() != ISD::SELECT_CC ||
683       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
684       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
685     return false;
686
687   if (TLI.getBooleanContents(N.getValueType()) ==
688       TargetLowering::UndefinedBooleanContent)
689     return false;
690
691   LHS = N.getOperand(0);
692   RHS = N.getOperand(1);
693   CC  = N.getOperand(4);
694   return true;
695 }
696
697 /// Return true if this is a SetCC-equivalent operation with only one use.
698 /// If this is true, it allows the users to invert the operation for free when
699 /// it is profitable to do so.
700 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
701   SDValue N0, N1, N2;
702   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
703     return true;
704   return false;
705 }
706
707 /// Returns true if N is a BUILD_VECTOR node whose
708 /// elements are all the same constant or undefined.
709 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
710   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
711   if (!C)
712     return false;
713
714   APInt SplatUndef;
715   unsigned SplatBitSize;
716   bool HasAnyUndefs;
717   EVT EltVT = N->getValueType(0).getVectorElementType();
718   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
719                              HasAnyUndefs) &&
720           EltVT.getSizeInBits() >= SplatBitSize);
721 }
722
723 // \brief Returns the SDNode if it is a constant integer BuildVector
724 // or constant integer.
725 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
726   if (isa<ConstantSDNode>(N))
727     return N.getNode();
728   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
729     return N.getNode();
730   return nullptr;
731 }
732
733 // \brief Returns the SDNode if it is a constant float BuildVector
734 // or constant float.
735 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
736   if (isa<ConstantFPSDNode>(N))
737     return N.getNode();
738   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
739     return N.getNode();
740   return nullptr;
741 }
742
743 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
744 // int.
745 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
746   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
747     return CN;
748
749   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
750     BitVector UndefElements;
751     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
752
753     // BuildVectors can truncate their operands. Ignore that case here.
754     // FIXME: We blindly ignore splats which include undef which is overly
755     // pessimistic.
756     if (CN && UndefElements.none() &&
757         CN->getValueType(0) == N.getValueType().getScalarType())
758       return CN;
759   }
760
761   return nullptr;
762 }
763
764 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
765 // float.
766 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
767   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
768     return CN;
769
770   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
771     BitVector UndefElements;
772     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
773
774     if (CN && UndefElements.none())
775       return CN;
776   }
777
778   return nullptr;
779 }
780
781 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
782                                     SDValue N0, SDValue N1) {
783   EVT VT = N0.getValueType();
784   if (N0.getOpcode() == Opc) {
785     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
786       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
787         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
788         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
789           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
790         return SDValue();
791       }
792       if (N0.hasOneUse()) {
793         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
794         // use
795         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
796         if (!OpNode.getNode())
797           return SDValue();
798         AddToWorklist(OpNode.getNode());
799         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
800       }
801     }
802   }
803
804   if (N1.getOpcode() == Opc) {
805     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
806       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
807         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
808         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
809           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
810         return SDValue();
811       }
812       if (N1.hasOneUse()) {
813         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
814         // use
815         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
816         if (!OpNode.getNode())
817           return SDValue();
818         AddToWorklist(OpNode.getNode());
819         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
820       }
821     }
822   }
823
824   return SDValue();
825 }
826
827 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
828                                bool AddTo) {
829   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
830   ++NodesCombined;
831   DEBUG(dbgs() << "\nReplacing.1 ";
832         N->dump(&DAG);
833         dbgs() << "\nWith: ";
834         To[0].getNode()->dump(&DAG);
835         dbgs() << " and " << NumTo-1 << " other values\n");
836   for (unsigned i = 0, e = NumTo; i != e; ++i)
837     assert((!To[i].getNode() ||
838             N->getValueType(i) == To[i].getValueType()) &&
839            "Cannot combine value to value of different type!");
840
841   WorklistRemover DeadNodes(*this);
842   DAG.ReplaceAllUsesWith(N, To);
843   if (AddTo) {
844     // Push the new nodes and any users onto the worklist
845     for (unsigned i = 0, e = NumTo; i != e; ++i) {
846       if (To[i].getNode()) {
847         AddToWorklist(To[i].getNode());
848         AddUsersToWorklist(To[i].getNode());
849       }
850     }
851   }
852
853   // Finally, if the node is now dead, remove it from the graph.  The node
854   // may not be dead if the replacement process recursively simplified to
855   // something else needing this node.
856   if (N->use_empty())
857     deleteAndRecombine(N);
858   return SDValue(N, 0);
859 }
860
861 void DAGCombiner::
862 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
863   // Replace all uses.  If any nodes become isomorphic to other nodes and
864   // are deleted, make sure to remove them from our worklist.
865   WorklistRemover DeadNodes(*this);
866   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
867
868   // Push the new node and any (possibly new) users onto the worklist.
869   AddToWorklist(TLO.New.getNode());
870   AddUsersToWorklist(TLO.New.getNode());
871
872   // Finally, if the node is now dead, remove it from the graph.  The node
873   // may not be dead if the replacement process recursively simplified to
874   // something else needing this node.
875   if (TLO.Old.getNode()->use_empty())
876     deleteAndRecombine(TLO.Old.getNode());
877 }
878
879 /// Check the specified integer node value to see if it can be simplified or if
880 /// things it uses can be simplified by bit propagation. If so, return true.
881 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
882   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
883   APInt KnownZero, KnownOne;
884   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
885     return false;
886
887   // Revisit the node.
888   AddToWorklist(Op.getNode());
889
890   // Replace the old value with the new one.
891   ++NodesCombined;
892   DEBUG(dbgs() << "\nReplacing.2 ";
893         TLO.Old.getNode()->dump(&DAG);
894         dbgs() << "\nWith: ";
895         TLO.New.getNode()->dump(&DAG);
896         dbgs() << '\n');
897
898   CommitTargetLoweringOpt(TLO);
899   return true;
900 }
901
902 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
903   SDLoc dl(Load);
904   EVT VT = Load->getValueType(0);
905   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
906
907   DEBUG(dbgs() << "\nReplacing.9 ";
908         Load->dump(&DAG);
909         dbgs() << "\nWith: ";
910         Trunc.getNode()->dump(&DAG);
911         dbgs() << '\n');
912   WorklistRemover DeadNodes(*this);
913   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
914   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
915   deleteAndRecombine(Load);
916   AddToWorklist(Trunc.getNode());
917 }
918
919 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
920   Replace = false;
921   SDLoc dl(Op);
922   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
923     EVT MemVT = LD->getMemoryVT();
924     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
925       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
926                                                        : ISD::EXTLOAD)
927       : LD->getExtensionType();
928     Replace = true;
929     return DAG.getExtLoad(ExtType, dl, PVT,
930                           LD->getChain(), LD->getBasePtr(),
931                           MemVT, LD->getMemOperand());
932   }
933
934   unsigned Opc = Op.getOpcode();
935   switch (Opc) {
936   default: break;
937   case ISD::AssertSext:
938     return DAG.getNode(ISD::AssertSext, dl, PVT,
939                        SExtPromoteOperand(Op.getOperand(0), PVT),
940                        Op.getOperand(1));
941   case ISD::AssertZext:
942     return DAG.getNode(ISD::AssertZext, dl, PVT,
943                        ZExtPromoteOperand(Op.getOperand(0), PVT),
944                        Op.getOperand(1));
945   case ISD::Constant: {
946     unsigned ExtOpc =
947       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
948     return DAG.getNode(ExtOpc, dl, PVT, Op);
949   }
950   }
951
952   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
953     return SDValue();
954   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
955 }
956
957 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
958   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
959     return SDValue();
960   EVT OldVT = Op.getValueType();
961   SDLoc dl(Op);
962   bool Replace = false;
963   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
964   if (!NewOp.getNode())
965     return SDValue();
966   AddToWorklist(NewOp.getNode());
967
968   if (Replace)
969     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
970   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
971                      DAG.getValueType(OldVT));
972 }
973
974 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
975   EVT OldVT = Op.getValueType();
976   SDLoc dl(Op);
977   bool Replace = false;
978   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
979   if (!NewOp.getNode())
980     return SDValue();
981   AddToWorklist(NewOp.getNode());
982
983   if (Replace)
984     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
985   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
986 }
987
988 /// Promote the specified integer binary operation if the target indicates it is
989 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
990 /// i32 since i16 instructions are longer.
991 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
992   if (!LegalOperations)
993     return SDValue();
994
995   EVT VT = Op.getValueType();
996   if (VT.isVector() || !VT.isInteger())
997     return SDValue();
998
999   // If operation type is 'undesirable', e.g. i16 on x86, consider
1000   // promoting it.
1001   unsigned Opc = Op.getOpcode();
1002   if (TLI.isTypeDesirableForOp(Opc, VT))
1003     return SDValue();
1004
1005   EVT PVT = VT;
1006   // Consult target whether it is a good idea to promote this operation and
1007   // what's the right type to promote it to.
1008   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1009     assert(PVT != VT && "Don't know what type to promote to!");
1010
1011     bool Replace0 = false;
1012     SDValue N0 = Op.getOperand(0);
1013     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1014     if (!NN0.getNode())
1015       return SDValue();
1016
1017     bool Replace1 = false;
1018     SDValue N1 = Op.getOperand(1);
1019     SDValue NN1;
1020     if (N0 == N1)
1021       NN1 = NN0;
1022     else {
1023       NN1 = PromoteOperand(N1, PVT, Replace1);
1024       if (!NN1.getNode())
1025         return SDValue();
1026     }
1027
1028     AddToWorklist(NN0.getNode());
1029     if (NN1.getNode())
1030       AddToWorklist(NN1.getNode());
1031
1032     if (Replace0)
1033       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1034     if (Replace1)
1035       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1036
1037     DEBUG(dbgs() << "\nPromoting ";
1038           Op.getNode()->dump(&DAG));
1039     SDLoc dl(Op);
1040     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1041                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1042   }
1043   return SDValue();
1044 }
1045
1046 /// Promote the specified integer shift operation if the target indicates it is
1047 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1048 /// i32 since i16 instructions are longer.
1049 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1050   if (!LegalOperations)
1051     return SDValue();
1052
1053   EVT VT = Op.getValueType();
1054   if (VT.isVector() || !VT.isInteger())
1055     return SDValue();
1056
1057   // If operation type is 'undesirable', e.g. i16 on x86, consider
1058   // promoting it.
1059   unsigned Opc = Op.getOpcode();
1060   if (TLI.isTypeDesirableForOp(Opc, VT))
1061     return SDValue();
1062
1063   EVT PVT = VT;
1064   // Consult target whether it is a good idea to promote this operation and
1065   // what's the right type to promote it to.
1066   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1067     assert(PVT != VT && "Don't know what type to promote to!");
1068
1069     bool Replace = false;
1070     SDValue N0 = Op.getOperand(0);
1071     if (Opc == ISD::SRA)
1072       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1073     else if (Opc == ISD::SRL)
1074       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1075     else
1076       N0 = PromoteOperand(N0, PVT, Replace);
1077     if (!N0.getNode())
1078       return SDValue();
1079
1080     AddToWorklist(N0.getNode());
1081     if (Replace)
1082       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1083
1084     DEBUG(dbgs() << "\nPromoting ";
1085           Op.getNode()->dump(&DAG));
1086     SDLoc dl(Op);
1087     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1088                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1089   }
1090   return SDValue();
1091 }
1092
1093 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1094   if (!LegalOperations)
1095     return SDValue();
1096
1097   EVT VT = Op.getValueType();
1098   if (VT.isVector() || !VT.isInteger())
1099     return SDValue();
1100
1101   // If operation type is 'undesirable', e.g. i16 on x86, consider
1102   // promoting it.
1103   unsigned Opc = Op.getOpcode();
1104   if (TLI.isTypeDesirableForOp(Opc, VT))
1105     return SDValue();
1106
1107   EVT PVT = VT;
1108   // Consult target whether it is a good idea to promote this operation and
1109   // what's the right type to promote it to.
1110   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1111     assert(PVT != VT && "Don't know what type to promote to!");
1112     // fold (aext (aext x)) -> (aext x)
1113     // fold (aext (zext x)) -> (zext x)
1114     // fold (aext (sext x)) -> (sext x)
1115     DEBUG(dbgs() << "\nPromoting ";
1116           Op.getNode()->dump(&DAG));
1117     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1118   }
1119   return SDValue();
1120 }
1121
1122 bool DAGCombiner::PromoteLoad(SDValue Op) {
1123   if (!LegalOperations)
1124     return false;
1125
1126   EVT VT = Op.getValueType();
1127   if (VT.isVector() || !VT.isInteger())
1128     return false;
1129
1130   // If operation type is 'undesirable', e.g. i16 on x86, consider
1131   // promoting it.
1132   unsigned Opc = Op.getOpcode();
1133   if (TLI.isTypeDesirableForOp(Opc, VT))
1134     return false;
1135
1136   EVT PVT = VT;
1137   // Consult target whether it is a good idea to promote this operation and
1138   // what's the right type to promote it to.
1139   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1140     assert(PVT != VT && "Don't know what type to promote to!");
1141
1142     SDLoc dl(Op);
1143     SDNode *N = Op.getNode();
1144     LoadSDNode *LD = cast<LoadSDNode>(N);
1145     EVT MemVT = LD->getMemoryVT();
1146     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1147       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1148                                                        : ISD::EXTLOAD)
1149       : LD->getExtensionType();
1150     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1151                                    LD->getChain(), LD->getBasePtr(),
1152                                    MemVT, LD->getMemOperand());
1153     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1154
1155     DEBUG(dbgs() << "\nPromoting ";
1156           N->dump(&DAG);
1157           dbgs() << "\nTo: ";
1158           Result.getNode()->dump(&DAG);
1159           dbgs() << '\n');
1160     WorklistRemover DeadNodes(*this);
1161     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1162     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1163     deleteAndRecombine(N);
1164     AddToWorklist(Result.getNode());
1165     return true;
1166   }
1167   return false;
1168 }
1169
1170 /// \brief Recursively delete a node which has no uses and any operands for
1171 /// which it is the only use.
1172 ///
1173 /// Note that this both deletes the nodes and removes them from the worklist.
1174 /// It also adds any nodes who have had a user deleted to the worklist as they
1175 /// may now have only one use and subject to other combines.
1176 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1177   if (!N->use_empty())
1178     return false;
1179
1180   SmallSetVector<SDNode *, 16> Nodes;
1181   Nodes.insert(N);
1182   do {
1183     N = Nodes.pop_back_val();
1184     if (!N)
1185       continue;
1186
1187     if (N->use_empty()) {
1188       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1189         Nodes.insert(N->getOperand(i).getNode());
1190
1191       removeFromWorklist(N);
1192       DAG.DeleteNode(N);
1193     } else {
1194       AddToWorklist(N);
1195     }
1196   } while (!Nodes.empty());
1197   return true;
1198 }
1199
1200 //===----------------------------------------------------------------------===//
1201 //  Main DAG Combiner implementation
1202 //===----------------------------------------------------------------------===//
1203
1204 void DAGCombiner::Run(CombineLevel AtLevel) {
1205   // set the instance variables, so that the various visit routines may use it.
1206   Level = AtLevel;
1207   LegalOperations = Level >= AfterLegalizeVectorOps;
1208   LegalTypes = Level >= AfterLegalizeTypes;
1209
1210   // Add all the dag nodes to the worklist.
1211   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1212        E = DAG.allnodes_end(); I != E; ++I)
1213     AddToWorklist(I);
1214
1215   // Create a dummy node (which is not added to allnodes), that adds a reference
1216   // to the root node, preventing it from being deleted, and tracking any
1217   // changes of the root.
1218   HandleSDNode Dummy(DAG.getRoot());
1219
1220   // while the worklist isn't empty, find a node and
1221   // try and combine it.
1222   while (!WorklistMap.empty()) {
1223     SDNode *N;
1224     // The Worklist holds the SDNodes in order, but it may contain null entries.
1225     do {
1226       N = Worklist.pop_back_val();
1227     } while (!N);
1228
1229     bool GoodWorklistEntry = WorklistMap.erase(N);
1230     (void)GoodWorklistEntry;
1231     assert(GoodWorklistEntry &&
1232            "Found a worklist entry without a corresponding map entry!");
1233
1234     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1235     // N is deleted from the DAG, since they too may now be dead or may have a
1236     // reduced number of uses, allowing other xforms.
1237     if (recursivelyDeleteUnusedNodes(N))
1238       continue;
1239
1240     WorklistRemover DeadNodes(*this);
1241
1242     // If this combine is running after legalizing the DAG, re-legalize any
1243     // nodes pulled off the worklist.
1244     if (Level == AfterLegalizeDAG) {
1245       SmallSetVector<SDNode *, 16> UpdatedNodes;
1246       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1247
1248       for (SDNode *LN : UpdatedNodes) {
1249         AddToWorklist(LN);
1250         AddUsersToWorklist(LN);
1251       }
1252       if (!NIsValid)
1253         continue;
1254     }
1255
1256     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1257
1258     // Add any operands of the new node which have not yet been combined to the
1259     // worklist as well. Because the worklist uniques things already, this
1260     // won't repeatedly process the same operand.
1261     CombinedNodes.insert(N);
1262     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1263       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1264         AddToWorklist(N->getOperand(i).getNode());
1265
1266     SDValue RV = combine(N);
1267
1268     if (!RV.getNode())
1269       continue;
1270
1271     ++NodesCombined;
1272
1273     // If we get back the same node we passed in, rather than a new node or
1274     // zero, we know that the node must have defined multiple values and
1275     // CombineTo was used.  Since CombineTo takes care of the worklist
1276     // mechanics for us, we have no work to do in this case.
1277     if (RV.getNode() == N)
1278       continue;
1279
1280     assert(N->getOpcode() != ISD::DELETED_NODE &&
1281            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1282            "Node was deleted but visit returned new node!");
1283
1284     DEBUG(dbgs() << " ... into: ";
1285           RV.getNode()->dump(&DAG));
1286
1287     // Transfer debug value.
1288     DAG.TransferDbgValues(SDValue(N, 0), RV);
1289     if (N->getNumValues() == RV.getNode()->getNumValues())
1290       DAG.ReplaceAllUsesWith(N, RV.getNode());
1291     else {
1292       assert(N->getValueType(0) == RV.getValueType() &&
1293              N->getNumValues() == 1 && "Type mismatch");
1294       SDValue OpV = RV;
1295       DAG.ReplaceAllUsesWith(N, &OpV);
1296     }
1297
1298     // Push the new node and any users onto the worklist
1299     AddToWorklist(RV.getNode());
1300     AddUsersToWorklist(RV.getNode());
1301
1302     // Finally, if the node is now dead, remove it from the graph.  The node
1303     // may not be dead if the replacement process recursively simplified to
1304     // something else needing this node. This will also take care of adding any
1305     // operands which have lost a user to the worklist.
1306     recursivelyDeleteUnusedNodes(N);
1307   }
1308
1309   // If the root changed (e.g. it was a dead load, update the root).
1310   DAG.setRoot(Dummy.getValue());
1311   DAG.RemoveDeadNodes();
1312 }
1313
1314 SDValue DAGCombiner::visit(SDNode *N) {
1315   switch (N->getOpcode()) {
1316   default: break;
1317   case ISD::TokenFactor:        return visitTokenFactor(N);
1318   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1319   case ISD::ADD:                return visitADD(N);
1320   case ISD::SUB:                return visitSUB(N);
1321   case ISD::ADDC:               return visitADDC(N);
1322   case ISD::SUBC:               return visitSUBC(N);
1323   case ISD::ADDE:               return visitADDE(N);
1324   case ISD::SUBE:               return visitSUBE(N);
1325   case ISD::MUL:                return visitMUL(N);
1326   case ISD::SDIV:               return visitSDIV(N);
1327   case ISD::UDIV:               return visitUDIV(N);
1328   case ISD::SREM:               return visitSREM(N);
1329   case ISD::UREM:               return visitUREM(N);
1330   case ISD::MULHU:              return visitMULHU(N);
1331   case ISD::MULHS:              return visitMULHS(N);
1332   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1333   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1334   case ISD::SMULO:              return visitSMULO(N);
1335   case ISD::UMULO:              return visitUMULO(N);
1336   case ISD::SDIVREM:            return visitSDIVREM(N);
1337   case ISD::UDIVREM:            return visitUDIVREM(N);
1338   case ISD::AND:                return visitAND(N);
1339   case ISD::OR:                 return visitOR(N);
1340   case ISD::XOR:                return visitXOR(N);
1341   case ISD::SHL:                return visitSHL(N);
1342   case ISD::SRA:                return visitSRA(N);
1343   case ISD::SRL:                return visitSRL(N);
1344   case ISD::ROTR:
1345   case ISD::ROTL:               return visitRotate(N);
1346   case ISD::BSWAP:              return visitBSWAP(N);
1347   case ISD::CTLZ:               return visitCTLZ(N);
1348   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1349   case ISD::CTTZ:               return visitCTTZ(N);
1350   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1351   case ISD::CTPOP:              return visitCTPOP(N);
1352   case ISD::SELECT:             return visitSELECT(N);
1353   case ISD::VSELECT:            return visitVSELECT(N);
1354   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1355   case ISD::SETCC:              return visitSETCC(N);
1356   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1357   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1358   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1359   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1360   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1361   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1362   case ISD::BITCAST:            return visitBITCAST(N);
1363   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1364   case ISD::FADD:               return visitFADD(N);
1365   case ISD::FSUB:               return visitFSUB(N);
1366   case ISD::FMUL:               return visitFMUL(N);
1367   case ISD::FMA:                return visitFMA(N);
1368   case ISD::FDIV:               return visitFDIV(N);
1369   case ISD::FREM:               return visitFREM(N);
1370   case ISD::FSQRT:              return visitFSQRT(N);
1371   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1372   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1373   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1374   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1375   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1376   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1377   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1378   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1379   case ISD::FNEG:               return visitFNEG(N);
1380   case ISD::FABS:               return visitFABS(N);
1381   case ISD::FFLOOR:             return visitFFLOOR(N);
1382   case ISD::FMINNUM:            return visitFMINNUM(N);
1383   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1384   case ISD::FCEIL:              return visitFCEIL(N);
1385   case ISD::FTRUNC:             return visitFTRUNC(N);
1386   case ISD::BRCOND:             return visitBRCOND(N);
1387   case ISD::BR_CC:              return visitBR_CC(N);
1388   case ISD::LOAD:               return visitLOAD(N);
1389   case ISD::STORE:              return visitSTORE(N);
1390   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1391   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1392   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1393   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1394   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1395   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1396   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1397   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1398   case ISD::MGATHER:            return visitMGATHER(N);
1399   case ISD::MLOAD:              return visitMLOAD(N);
1400   case ISD::MSCATTER:           return visitMSCATTER(N);
1401   case ISD::MSTORE:             return visitMSTORE(N);
1402   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1403   }
1404   return SDValue();
1405 }
1406
1407 SDValue DAGCombiner::combine(SDNode *N) {
1408   SDValue RV = visit(N);
1409
1410   // If nothing happened, try a target-specific DAG combine.
1411   if (!RV.getNode()) {
1412     assert(N->getOpcode() != ISD::DELETED_NODE &&
1413            "Node was deleted but visit returned NULL!");
1414
1415     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1416         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1417
1418       // Expose the DAG combiner to the target combiner impls.
1419       TargetLowering::DAGCombinerInfo
1420         DagCombineInfo(DAG, Level, false, this);
1421
1422       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1423     }
1424   }
1425
1426   // If nothing happened still, try promoting the operation.
1427   if (!RV.getNode()) {
1428     switch (N->getOpcode()) {
1429     default: break;
1430     case ISD::ADD:
1431     case ISD::SUB:
1432     case ISD::MUL:
1433     case ISD::AND:
1434     case ISD::OR:
1435     case ISD::XOR:
1436       RV = PromoteIntBinOp(SDValue(N, 0));
1437       break;
1438     case ISD::SHL:
1439     case ISD::SRA:
1440     case ISD::SRL:
1441       RV = PromoteIntShiftOp(SDValue(N, 0));
1442       break;
1443     case ISD::SIGN_EXTEND:
1444     case ISD::ZERO_EXTEND:
1445     case ISD::ANY_EXTEND:
1446       RV = PromoteExtend(SDValue(N, 0));
1447       break;
1448     case ISD::LOAD:
1449       if (PromoteLoad(SDValue(N, 0)))
1450         RV = SDValue(N, 0);
1451       break;
1452     }
1453   }
1454
1455   // If N is a commutative binary node, try commuting it to enable more
1456   // sdisel CSE.
1457   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1458       N->getNumValues() == 1) {
1459     SDValue N0 = N->getOperand(0);
1460     SDValue N1 = N->getOperand(1);
1461
1462     // Constant operands are canonicalized to RHS.
1463     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1464       SDValue Ops[] = {N1, N0};
1465       SDNode *CSENode;
1466       if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1467         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1468                                       &BinNode->Flags);
1469       } else {
1470         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1471       }
1472       if (CSENode)
1473         return SDValue(CSENode, 0);
1474     }
1475   }
1476
1477   return RV;
1478 }
1479
1480 /// Given a node, return its input chain if it has one, otherwise return a null
1481 /// sd operand.
1482 static SDValue getInputChainForNode(SDNode *N) {
1483   if (unsigned NumOps = N->getNumOperands()) {
1484     if (N->getOperand(0).getValueType() == MVT::Other)
1485       return N->getOperand(0);
1486     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1487       return N->getOperand(NumOps-1);
1488     for (unsigned i = 1; i < NumOps-1; ++i)
1489       if (N->getOperand(i).getValueType() == MVT::Other)
1490         return N->getOperand(i);
1491   }
1492   return SDValue();
1493 }
1494
1495 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1496   // If N has two operands, where one has an input chain equal to the other,
1497   // the 'other' chain is redundant.
1498   if (N->getNumOperands() == 2) {
1499     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1500       return N->getOperand(0);
1501     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1502       return N->getOperand(1);
1503   }
1504
1505   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1506   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1507   SmallPtrSet<SDNode*, 16> SeenOps;
1508   bool Changed = false;             // If we should replace this token factor.
1509
1510   // Start out with this token factor.
1511   TFs.push_back(N);
1512
1513   // Iterate through token factors.  The TFs grows when new token factors are
1514   // encountered.
1515   for (unsigned i = 0; i < TFs.size(); ++i) {
1516     SDNode *TF = TFs[i];
1517
1518     // Check each of the operands.
1519     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1520       SDValue Op = TF->getOperand(i);
1521
1522       switch (Op.getOpcode()) {
1523       case ISD::EntryToken:
1524         // Entry tokens don't need to be added to the list. They are
1525         // redundant.
1526         Changed = true;
1527         break;
1528
1529       case ISD::TokenFactor:
1530         if (Op.hasOneUse() &&
1531             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1532           // Queue up for processing.
1533           TFs.push_back(Op.getNode());
1534           // Clean up in case the token factor is removed.
1535           AddToWorklist(Op.getNode());
1536           Changed = true;
1537           break;
1538         }
1539         // Fall thru
1540
1541       default:
1542         // Only add if it isn't already in the list.
1543         if (SeenOps.insert(Op.getNode()).second)
1544           Ops.push_back(Op);
1545         else
1546           Changed = true;
1547         break;
1548       }
1549     }
1550   }
1551
1552   SDValue Result;
1553
1554   // If we've changed things around then replace token factor.
1555   if (Changed) {
1556     if (Ops.empty()) {
1557       // The entry token is the only possible outcome.
1558       Result = DAG.getEntryNode();
1559     } else {
1560       // New and improved token factor.
1561       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1562     }
1563
1564     // Add users to worklist if AA is enabled, since it may introduce
1565     // a lot of new chained token factors while removing memory deps.
1566     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1567       : DAG.getSubtarget().useAA();
1568     return CombineTo(N, Result, UseAA /*add to worklist*/);
1569   }
1570
1571   return Result;
1572 }
1573
1574 /// MERGE_VALUES can always be eliminated.
1575 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1576   WorklistRemover DeadNodes(*this);
1577   // Replacing results may cause a different MERGE_VALUES to suddenly
1578   // be CSE'd with N, and carry its uses with it. Iterate until no
1579   // uses remain, to ensure that the node can be safely deleted.
1580   // First add the users of this node to the work list so that they
1581   // can be tried again once they have new operands.
1582   AddUsersToWorklist(N);
1583   do {
1584     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1585       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1586   } while (!N->use_empty());
1587   deleteAndRecombine(N);
1588   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1589 }
1590
1591 static bool isNullConstant(SDValue V) {
1592   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1593   return Const != nullptr && Const->isNullValue();
1594 }
1595
1596 static bool isNullFPConstant(SDValue V) {
1597   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1598   return Const != nullptr && Const->isZero() && !Const->isNegative();
1599 }
1600
1601 static bool isAllOnesConstant(SDValue V) {
1602   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1603   return Const != nullptr && Const->isAllOnesValue();
1604 }
1605
1606 static bool isOneConstant(SDValue V) {
1607   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1608   return Const != nullptr && Const->isOne();
1609 }
1610
1611 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1612 /// ContantSDNode pointer else nullptr.
1613 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1614   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1615   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1616 }
1617
1618 SDValue DAGCombiner::visitADD(SDNode *N) {
1619   SDValue N0 = N->getOperand(0);
1620   SDValue N1 = N->getOperand(1);
1621   EVT VT = N0.getValueType();
1622
1623   // fold vector ops
1624   if (VT.isVector()) {
1625     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1626       return FoldedVOp;
1627
1628     // fold (add x, 0) -> x, vector edition
1629     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1630       return N0;
1631     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1632       return N1;
1633   }
1634
1635   // fold (add x, undef) -> undef
1636   if (N0.getOpcode() == ISD::UNDEF)
1637     return N0;
1638   if (N1.getOpcode() == ISD::UNDEF)
1639     return N1;
1640   // fold (add c1, c2) -> c1+c2
1641   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1642   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1643   if (N0C && N1C)
1644     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1645   // canonicalize constant to RHS
1646   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1647      !isConstantIntBuildVectorOrConstantInt(N1))
1648     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1649   // fold (add x, 0) -> x
1650   if (isNullConstant(N1))
1651     return N0;
1652   // fold (add Sym, c) -> Sym+c
1653   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1654     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1655         GA->getOpcode() == ISD::GlobalAddress)
1656       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1657                                   GA->getOffset() +
1658                                     (uint64_t)N1C->getSExtValue());
1659   // fold ((c1-A)+c2) -> (c1+c2)-A
1660   if (N1C && N0.getOpcode() == ISD::SUB)
1661     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1662       SDLoc DL(N);
1663       return DAG.getNode(ISD::SUB, DL, VT,
1664                          DAG.getConstant(N1C->getAPIntValue()+
1665                                          N0C->getAPIntValue(), DL, VT),
1666                          N0.getOperand(1));
1667     }
1668   // reassociate add
1669   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1670     return RADD;
1671   // fold ((0-A) + B) -> B-A
1672   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1673     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1674   // fold (A + (0-B)) -> A-B
1675   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1676     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1677   // fold (A+(B-A)) -> B
1678   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1679     return N1.getOperand(0);
1680   // fold ((B-A)+A) -> B
1681   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1682     return N0.getOperand(0);
1683   // fold (A+(B-(A+C))) to (B-C)
1684   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1685       N0 == N1.getOperand(1).getOperand(0))
1686     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1687                        N1.getOperand(1).getOperand(1));
1688   // fold (A+(B-(C+A))) to (B-C)
1689   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1690       N0 == N1.getOperand(1).getOperand(1))
1691     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1692                        N1.getOperand(1).getOperand(0));
1693   // fold (A+((B-A)+or-C)) to (B+or-C)
1694   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1695       N1.getOperand(0).getOpcode() == ISD::SUB &&
1696       N0 == N1.getOperand(0).getOperand(1))
1697     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1698                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1699
1700   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1701   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1702     SDValue N00 = N0.getOperand(0);
1703     SDValue N01 = N0.getOperand(1);
1704     SDValue N10 = N1.getOperand(0);
1705     SDValue N11 = N1.getOperand(1);
1706
1707     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1708       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1709                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1710                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1711   }
1712
1713   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1714     return SDValue(N, 0);
1715
1716   // fold (a+b) -> (a|b) iff a and b share no bits.
1717   if (VT.isInteger() && !VT.isVector()) {
1718     APInt LHSZero, LHSOne;
1719     APInt RHSZero, RHSOne;
1720     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1721
1722     if (LHSZero.getBoolValue()) {
1723       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1724
1725       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1726       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1727       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1728         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1729           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1730       }
1731     }
1732   }
1733
1734   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1735   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1736       isNullConstant(N1.getOperand(0).getOperand(0)))
1737     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1738                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1739                                    N1.getOperand(0).getOperand(1),
1740                                    N1.getOperand(1)));
1741   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1742       isNullConstant(N0.getOperand(0).getOperand(0)))
1743     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1744                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745                                    N0.getOperand(0).getOperand(1),
1746                                    N0.getOperand(1)));
1747
1748   if (N1.getOpcode() == ISD::AND) {
1749     SDValue AndOp0 = N1.getOperand(0);
1750     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1751     unsigned DestBits = VT.getScalarType().getSizeInBits();
1752
1753     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1754     // and similar xforms where the inner op is either ~0 or 0.
1755     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1756       SDLoc DL(N);
1757       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1758     }
1759   }
1760
1761   // add (sext i1), X -> sub X, (zext i1)
1762   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1763       N0.getOperand(0).getValueType() == MVT::i1 &&
1764       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1765     SDLoc DL(N);
1766     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1767     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1768   }
1769
1770   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1771   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1772     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1773     if (TN->getVT() == MVT::i1) {
1774       SDLoc DL(N);
1775       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1776                                  DAG.getConstant(1, DL, VT));
1777       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1778     }
1779   }
1780
1781   return SDValue();
1782 }
1783
1784 SDValue DAGCombiner::visitADDC(SDNode *N) {
1785   SDValue N0 = N->getOperand(0);
1786   SDValue N1 = N->getOperand(1);
1787   EVT VT = N0.getValueType();
1788
1789   // If the flag result is dead, turn this into an ADD.
1790   if (!N->hasAnyUseOfValue(1))
1791     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1792                      DAG.getNode(ISD::CARRY_FALSE,
1793                                  SDLoc(N), MVT::Glue));
1794
1795   // canonicalize constant to RHS.
1796   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1797   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1798   if (N0C && !N1C)
1799     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1800
1801   // fold (addc x, 0) -> x + no carry out
1802   if (isNullConstant(N1))
1803     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1804                                         SDLoc(N), MVT::Glue));
1805
1806   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1807   APInt LHSZero, LHSOne;
1808   APInt RHSZero, RHSOne;
1809   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1810
1811   if (LHSZero.getBoolValue()) {
1812     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1813
1814     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1815     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1816     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1817       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1818                        DAG.getNode(ISD::CARRY_FALSE,
1819                                    SDLoc(N), MVT::Glue));
1820   }
1821
1822   return SDValue();
1823 }
1824
1825 SDValue DAGCombiner::visitADDE(SDNode *N) {
1826   SDValue N0 = N->getOperand(0);
1827   SDValue N1 = N->getOperand(1);
1828   SDValue CarryIn = N->getOperand(2);
1829
1830   // canonicalize constant to RHS
1831   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1832   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1833   if (N0C && !N1C)
1834     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1835                        N1, N0, CarryIn);
1836
1837   // fold (adde x, y, false) -> (addc x, y)
1838   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1839     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1840
1841   return SDValue();
1842 }
1843
1844 // Since it may not be valid to emit a fold to zero for vector initializers
1845 // check if we can before folding.
1846 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1847                              SelectionDAG &DAG,
1848                              bool LegalOperations, bool LegalTypes) {
1849   if (!VT.isVector())
1850     return DAG.getConstant(0, DL, VT);
1851   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1852     return DAG.getConstant(0, DL, VT);
1853   return SDValue();
1854 }
1855
1856 SDValue DAGCombiner::visitSUB(SDNode *N) {
1857   SDValue N0 = N->getOperand(0);
1858   SDValue N1 = N->getOperand(1);
1859   EVT VT = N0.getValueType();
1860
1861   // fold vector ops
1862   if (VT.isVector()) {
1863     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1864       return FoldedVOp;
1865
1866     // fold (sub x, 0) -> x, vector edition
1867     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1868       return N0;
1869   }
1870
1871   // fold (sub x, x) -> 0
1872   // FIXME: Refactor this and xor and other similar operations together.
1873   if (N0 == N1)
1874     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1875   // fold (sub c1, c2) -> c1-c2
1876   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1877   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1878   if (N0C && N1C)
1879     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1880   // fold (sub x, c) -> (add x, -c)
1881   if (N1C) {
1882     SDLoc DL(N);
1883     return DAG.getNode(ISD::ADD, DL, VT, N0,
1884                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1885   }
1886   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1887   if (isAllOnesConstant(N0))
1888     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1889   // fold A-(A-B) -> B
1890   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1891     return N1.getOperand(1);
1892   // fold (A+B)-A -> B
1893   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1894     return N0.getOperand(1);
1895   // fold (A+B)-B -> A
1896   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1897     return N0.getOperand(0);
1898   // fold C2-(A+C1) -> (C2-C1)-A
1899   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1900     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1901   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1902     SDLoc DL(N);
1903     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1904                                    DL, VT);
1905     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1906                        N1.getOperand(0));
1907   }
1908   // fold ((A+(B+or-C))-B) -> A+or-C
1909   if (N0.getOpcode() == ISD::ADD &&
1910       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1911        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1912       N0.getOperand(1).getOperand(0) == N1)
1913     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1914                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1915   // fold ((A+(C+B))-B) -> A+C
1916   if (N0.getOpcode() == ISD::ADD &&
1917       N0.getOperand(1).getOpcode() == ISD::ADD &&
1918       N0.getOperand(1).getOperand(1) == N1)
1919     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1920                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1921   // fold ((A-(B-C))-C) -> A-B
1922   if (N0.getOpcode() == ISD::SUB &&
1923       N0.getOperand(1).getOpcode() == ISD::SUB &&
1924       N0.getOperand(1).getOperand(1) == N1)
1925     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1926                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1927
1928   // If either operand of a sub is undef, the result is undef
1929   if (N0.getOpcode() == ISD::UNDEF)
1930     return N0;
1931   if (N1.getOpcode() == ISD::UNDEF)
1932     return N1;
1933
1934   // If the relocation model supports it, consider symbol offsets.
1935   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1936     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1937       // fold (sub Sym, c) -> Sym-c
1938       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1939         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1940                                     GA->getOffset() -
1941                                       (uint64_t)N1C->getSExtValue());
1942       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1943       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1944         if (GA->getGlobal() == GB->getGlobal())
1945           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1946                                  SDLoc(N), VT);
1947     }
1948
1949   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1950   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1951     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1952     if (TN->getVT() == MVT::i1) {
1953       SDLoc DL(N);
1954       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1955                                  DAG.getConstant(1, DL, VT));
1956       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1957     }
1958   }
1959
1960   return SDValue();
1961 }
1962
1963 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1964   SDValue N0 = N->getOperand(0);
1965   SDValue N1 = N->getOperand(1);
1966   EVT VT = N0.getValueType();
1967
1968   // If the flag result is dead, turn this into an SUB.
1969   if (!N->hasAnyUseOfValue(1))
1970     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1971                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1972                                  MVT::Glue));
1973
1974   // fold (subc x, x) -> 0 + no borrow
1975   if (N0 == N1) {
1976     SDLoc DL(N);
1977     return CombineTo(N, DAG.getConstant(0, DL, VT),
1978                      DAG.getNode(ISD::CARRY_FALSE, DL,
1979                                  MVT::Glue));
1980   }
1981
1982   // fold (subc x, 0) -> x + no borrow
1983   if (isNullConstant(N1))
1984     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1985                                         MVT::Glue));
1986
1987   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1988   if (isAllOnesConstant(N0))
1989     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1990                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1991                                  MVT::Glue));
1992
1993   return SDValue();
1994 }
1995
1996 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1997   SDValue N0 = N->getOperand(0);
1998   SDValue N1 = N->getOperand(1);
1999   SDValue CarryIn = N->getOperand(2);
2000
2001   // fold (sube x, y, false) -> (subc x, y)
2002   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2003     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2004
2005   return SDValue();
2006 }
2007
2008 SDValue DAGCombiner::visitMUL(SDNode *N) {
2009   SDValue N0 = N->getOperand(0);
2010   SDValue N1 = N->getOperand(1);
2011   EVT VT = N0.getValueType();
2012
2013   // fold (mul x, undef) -> 0
2014   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2015     return DAG.getConstant(0, SDLoc(N), VT);
2016
2017   bool N0IsConst = false;
2018   bool N1IsConst = false;
2019   bool N1IsOpaqueConst = false;
2020   bool N0IsOpaqueConst = false;
2021   APInt ConstValue0, ConstValue1;
2022   // fold vector ops
2023   if (VT.isVector()) {
2024     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2025       return FoldedVOp;
2026
2027     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2028     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2029   } else {
2030     N0IsConst = isa<ConstantSDNode>(N0);
2031     if (N0IsConst) {
2032       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2033       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2034     }
2035     N1IsConst = isa<ConstantSDNode>(N1);
2036     if (N1IsConst) {
2037       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2038       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2039     }
2040   }
2041
2042   // fold (mul c1, c2) -> c1*c2
2043   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2044     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2045                                       N0.getNode(), N1.getNode());
2046
2047   // canonicalize constant to RHS (vector doesn't have to splat)
2048   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2049      !isConstantIntBuildVectorOrConstantInt(N1))
2050     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2051   // fold (mul x, 0) -> 0
2052   if (N1IsConst && ConstValue1 == 0)
2053     return N1;
2054   // We require a splat of the entire scalar bit width for non-contiguous
2055   // bit patterns.
2056   bool IsFullSplat =
2057     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2058   // fold (mul x, 1) -> x
2059   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2060     return N0;
2061   // fold (mul x, -1) -> 0-x
2062   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2063     SDLoc DL(N);
2064     return DAG.getNode(ISD::SUB, DL, VT,
2065                        DAG.getConstant(0, DL, VT), N0);
2066   }
2067   // fold (mul x, (1 << c)) -> x << c
2068   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2069       IsFullSplat) {
2070     SDLoc DL(N);
2071     return DAG.getNode(ISD::SHL, DL, VT, N0,
2072                        DAG.getConstant(ConstValue1.logBase2(), DL,
2073                                        getShiftAmountTy(N0.getValueType())));
2074   }
2075   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2076   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2077       IsFullSplat) {
2078     unsigned Log2Val = (-ConstValue1).logBase2();
2079     SDLoc DL(N);
2080     // FIXME: If the input is something that is easily negated (e.g. a
2081     // single-use add), we should put the negate there.
2082     return DAG.getNode(ISD::SUB, DL, VT,
2083                        DAG.getConstant(0, DL, VT),
2084                        DAG.getNode(ISD::SHL, DL, VT, N0,
2085                             DAG.getConstant(Log2Val, DL,
2086                                       getShiftAmountTy(N0.getValueType()))));
2087   }
2088
2089   APInt Val;
2090   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2091   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2092       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2093                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2094     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2095                              N1, N0.getOperand(1));
2096     AddToWorklist(C3.getNode());
2097     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2098                        N0.getOperand(0), C3);
2099   }
2100
2101   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2102   // use.
2103   {
2104     SDValue Sh(nullptr,0), Y(nullptr,0);
2105     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2106     if (N0.getOpcode() == ISD::SHL &&
2107         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2108                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2109         N0.getNode()->hasOneUse()) {
2110       Sh = N0; Y = N1;
2111     } else if (N1.getOpcode() == ISD::SHL &&
2112                isa<ConstantSDNode>(N1.getOperand(1)) &&
2113                N1.getNode()->hasOneUse()) {
2114       Sh = N1; Y = N0;
2115     }
2116
2117     if (Sh.getNode()) {
2118       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2119                                 Sh.getOperand(0), Y);
2120       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2121                          Mul, Sh.getOperand(1));
2122     }
2123   }
2124
2125   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2126   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2127       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2128                      isa<ConstantSDNode>(N0.getOperand(1))))
2129     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2130                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2131                                    N0.getOperand(0), N1),
2132                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2133                                    N0.getOperand(1), N1));
2134
2135   // reassociate mul
2136   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2137     return RMUL;
2138
2139   return SDValue();
2140 }
2141
2142 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2143   SDValue N0 = N->getOperand(0);
2144   SDValue N1 = N->getOperand(1);
2145   EVT VT = N->getValueType(0);
2146
2147   // fold vector ops
2148   if (VT.isVector())
2149     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2150       return FoldedVOp;
2151
2152   // fold (sdiv c1, c2) -> c1/c2
2153   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2154   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2155   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2156     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2157   // fold (sdiv X, 1) -> X
2158   if (N1C && N1C->isOne())
2159     return N0;
2160   // fold (sdiv X, -1) -> 0-X
2161   if (N1C && N1C->isAllOnesValue()) {
2162     SDLoc DL(N);
2163     return DAG.getNode(ISD::SUB, DL, VT,
2164                        DAG.getConstant(0, DL, VT), N0);
2165   }
2166   // If we know the sign bits of both operands are zero, strength reduce to a
2167   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2168   if (!VT.isVector()) {
2169     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2170       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2171                          N0, N1);
2172   }
2173
2174   // fold (sdiv X, pow2) -> simple ops after legalize
2175   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2176       (N1C->getAPIntValue().isPowerOf2() ||
2177        (-N1C->getAPIntValue()).isPowerOf2())) {
2178     // If dividing by powers of two is cheap, then don't perform the following
2179     // fold.
2180     if (TLI.isPow2SDivCheap())
2181       return SDValue();
2182
2183     // Target-specific implementation of sdiv x, pow2.
2184     SDValue Res = BuildSDIVPow2(N);
2185     if (Res.getNode())
2186       return Res;
2187
2188     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2189     SDLoc DL(N);
2190
2191     // Splat the sign bit into the register
2192     SDValue SGN =
2193         DAG.getNode(ISD::SRA, DL, VT, N0,
2194                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2195                                     getShiftAmountTy(N0.getValueType())));
2196     AddToWorklist(SGN.getNode());
2197
2198     // Add (N0 < 0) ? abs2 - 1 : 0;
2199     SDValue SRL =
2200         DAG.getNode(ISD::SRL, DL, VT, SGN,
2201                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2202                                     getShiftAmountTy(SGN.getValueType())));
2203     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2204     AddToWorklist(SRL.getNode());
2205     AddToWorklist(ADD.getNode());    // Divide by pow2
2206     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2207                   DAG.getConstant(lg2, DL,
2208                                   getShiftAmountTy(ADD.getValueType())));
2209
2210     // If we're dividing by a positive value, we're done.  Otherwise, we must
2211     // negate the result.
2212     if (N1C->getAPIntValue().isNonNegative())
2213       return SRA;
2214
2215     AddToWorklist(SRA.getNode());
2216     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2217   }
2218
2219   // If integer divide is expensive and we satisfy the requirements, emit an
2220   // alternate sequence.
2221   if (N1C && !TLI.isIntDivCheap()) {
2222     SDValue Op = BuildSDIV(N);
2223     if (Op.getNode()) return Op;
2224   }
2225
2226   // undef / X -> 0
2227   if (N0.getOpcode() == ISD::UNDEF)
2228     return DAG.getConstant(0, SDLoc(N), VT);
2229   // X / undef -> undef
2230   if (N1.getOpcode() == ISD::UNDEF)
2231     return N1;
2232
2233   return SDValue();
2234 }
2235
2236 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2237   SDValue N0 = N->getOperand(0);
2238   SDValue N1 = N->getOperand(1);
2239   EVT VT = N->getValueType(0);
2240
2241   // fold vector ops
2242   if (VT.isVector())
2243     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2244       return FoldedVOp;
2245
2246   // fold (udiv c1, c2) -> c1/c2
2247   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2248   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2249   if (N0C && N1C)
2250     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2251                                                     N0C, N1C))
2252       return Folded;
2253   // fold (udiv x, (1 << c)) -> x >>u c
2254   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2255     SDLoc DL(N);
2256     return DAG.getNode(ISD::SRL, DL, VT, N0,
2257                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2258                                        getShiftAmountTy(N0.getValueType())));
2259   }
2260   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2261   if (N1.getOpcode() == ISD::SHL) {
2262     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2263       if (SHC->getAPIntValue().isPowerOf2()) {
2264         EVT ADDVT = N1.getOperand(1).getValueType();
2265         SDLoc DL(N);
2266         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2267                                   N1.getOperand(1),
2268                                   DAG.getConstant(SHC->getAPIntValue()
2269                                                                   .logBase2(),
2270                                                   DL, ADDVT));
2271         AddToWorklist(Add.getNode());
2272         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2273       }
2274     }
2275   }
2276   // fold (udiv x, c) -> alternate
2277   if (N1C && !TLI.isIntDivCheap()) {
2278     SDValue Op = BuildUDIV(N);
2279     if (Op.getNode()) return Op;
2280   }
2281
2282   // undef / X -> 0
2283   if (N0.getOpcode() == ISD::UNDEF)
2284     return DAG.getConstant(0, SDLoc(N), VT);
2285   // X / undef -> undef
2286   if (N1.getOpcode() == ISD::UNDEF)
2287     return N1;
2288
2289   return SDValue();
2290 }
2291
2292 SDValue DAGCombiner::visitSREM(SDNode *N) {
2293   SDValue N0 = N->getOperand(0);
2294   SDValue N1 = N->getOperand(1);
2295   EVT VT = N->getValueType(0);
2296
2297   // fold (srem c1, c2) -> c1%c2
2298   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2299   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2300   if (N0C && N1C)
2301     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2302                                                     N0C, N1C))
2303       return Folded;
2304   // If we know the sign bits of both operands are zero, strength reduce to a
2305   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2306   if (!VT.isVector()) {
2307     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2308       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2309   }
2310
2311   // If X/C can be simplified by the division-by-constant logic, lower
2312   // X%C to the equivalent of X-X/C*C.
2313   if (N1C && !N1C->isNullValue()) {
2314     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2315     AddToWorklist(Div.getNode());
2316     SDValue OptimizedDiv = combine(Div.getNode());
2317     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2318       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2319                                 OptimizedDiv, N1);
2320       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2321       AddToWorklist(Mul.getNode());
2322       return Sub;
2323     }
2324   }
2325
2326   // undef % X -> 0
2327   if (N0.getOpcode() == ISD::UNDEF)
2328     return DAG.getConstant(0, SDLoc(N), VT);
2329   // X % undef -> undef
2330   if (N1.getOpcode() == ISD::UNDEF)
2331     return N1;
2332
2333   return SDValue();
2334 }
2335
2336 SDValue DAGCombiner::visitUREM(SDNode *N) {
2337   SDValue N0 = N->getOperand(0);
2338   SDValue N1 = N->getOperand(1);
2339   EVT VT = N->getValueType(0);
2340
2341   // fold (urem c1, c2) -> c1%c2
2342   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2343   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2344   if (N0C && N1C)
2345     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2346                                                     N0C, N1C))
2347       return Folded;
2348   // fold (urem x, pow2) -> (and x, pow2-1)
2349   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2350       N1C->getAPIntValue().isPowerOf2()) {
2351     SDLoc DL(N);
2352     return DAG.getNode(ISD::AND, DL, VT, N0,
2353                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2354   }
2355   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2356   if (N1.getOpcode() == ISD::SHL) {
2357     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2358       if (SHC->getAPIntValue().isPowerOf2()) {
2359         SDLoc DL(N);
2360         SDValue Add =
2361           DAG.getNode(ISD::ADD, DL, VT, N1,
2362                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2363                                  VT));
2364         AddToWorklist(Add.getNode());
2365         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2366       }
2367     }
2368   }
2369
2370   // If X/C can be simplified by the division-by-constant logic, lower
2371   // X%C to the equivalent of X-X/C*C.
2372   if (N1C && !N1C->isNullValue()) {
2373     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2374     AddToWorklist(Div.getNode());
2375     SDValue OptimizedDiv = combine(Div.getNode());
2376     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2377       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2378                                 OptimizedDiv, N1);
2379       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2380       AddToWorklist(Mul.getNode());
2381       return Sub;
2382     }
2383   }
2384
2385   // undef % X -> 0
2386   if (N0.getOpcode() == ISD::UNDEF)
2387     return DAG.getConstant(0, SDLoc(N), VT);
2388   // X % undef -> undef
2389   if (N1.getOpcode() == ISD::UNDEF)
2390     return N1;
2391
2392   return SDValue();
2393 }
2394
2395 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2396   SDValue N0 = N->getOperand(0);
2397   SDValue N1 = N->getOperand(1);
2398   EVT VT = N->getValueType(0);
2399   SDLoc DL(N);
2400
2401   // fold (mulhs x, 0) -> 0
2402   if (isNullConstant(N1))
2403     return N1;
2404   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2405   if (isOneConstant(N1)) {
2406     SDLoc DL(N);
2407     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2408                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2409                                        DL,
2410                                        getShiftAmountTy(N0.getValueType())));
2411   }
2412   // fold (mulhs x, undef) -> 0
2413   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2414     return DAG.getConstant(0, SDLoc(N), VT);
2415
2416   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2417   // plus a shift.
2418   if (VT.isSimple() && !VT.isVector()) {
2419     MVT Simple = VT.getSimpleVT();
2420     unsigned SimpleSize = Simple.getSizeInBits();
2421     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2424       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2425       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2426       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2427             DAG.getConstant(SimpleSize, DL,
2428                             getShiftAmountTy(N1.getValueType())));
2429       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2430     }
2431   }
2432
2433   return SDValue();
2434 }
2435
2436 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2437   SDValue N0 = N->getOperand(0);
2438   SDValue N1 = N->getOperand(1);
2439   EVT VT = N->getValueType(0);
2440   SDLoc DL(N);
2441
2442   // fold (mulhu x, 0) -> 0
2443   if (isNullConstant(N1))
2444     return N1;
2445   // fold (mulhu x, 1) -> 0
2446   if (isOneConstant(N1))
2447     return DAG.getConstant(0, DL, N0.getValueType());
2448   // fold (mulhu x, undef) -> 0
2449   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2450     return DAG.getConstant(0, DL, VT);
2451
2452   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2453   // plus a shift.
2454   if (VT.isSimple() && !VT.isVector()) {
2455     MVT Simple = VT.getSimpleVT();
2456     unsigned SimpleSize = Simple.getSizeInBits();
2457     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2458     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2459       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2460       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2461       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2462       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2463             DAG.getConstant(SimpleSize, DL,
2464                             getShiftAmountTy(N1.getValueType())));
2465       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2466     }
2467   }
2468
2469   return SDValue();
2470 }
2471
2472 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2473 /// give the opcodes for the two computations that are being performed. Return
2474 /// true if a simplification was made.
2475 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2476                                                 unsigned HiOp) {
2477   // If the high half is not needed, just compute the low half.
2478   bool HiExists = N->hasAnyUseOfValue(1);
2479   if (!HiExists &&
2480       (!LegalOperations ||
2481        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2482     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2483     return CombineTo(N, Res, Res);
2484   }
2485
2486   // If the low half is not needed, just compute the high half.
2487   bool LoExists = N->hasAnyUseOfValue(0);
2488   if (!LoExists &&
2489       (!LegalOperations ||
2490        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2491     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2492     return CombineTo(N, Res, Res);
2493   }
2494
2495   // If both halves are used, return as it is.
2496   if (LoExists && HiExists)
2497     return SDValue();
2498
2499   // If the two computed results can be simplified separately, separate them.
2500   if (LoExists) {
2501     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2502     AddToWorklist(Lo.getNode());
2503     SDValue LoOpt = combine(Lo.getNode());
2504     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2505         (!LegalOperations ||
2506          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2507       return CombineTo(N, LoOpt, LoOpt);
2508   }
2509
2510   if (HiExists) {
2511     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2512     AddToWorklist(Hi.getNode());
2513     SDValue HiOpt = combine(Hi.getNode());
2514     if (HiOpt.getNode() && HiOpt != Hi &&
2515         (!LegalOperations ||
2516          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2517       return CombineTo(N, HiOpt, HiOpt);
2518   }
2519
2520   return SDValue();
2521 }
2522
2523 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2524   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2525   if (Res.getNode()) return Res;
2526
2527   EVT VT = N->getValueType(0);
2528   SDLoc DL(N);
2529
2530   // If the type is twice as wide is legal, transform the mulhu to a wider
2531   // multiply plus a shift.
2532   if (VT.isSimple() && !VT.isVector()) {
2533     MVT Simple = VT.getSimpleVT();
2534     unsigned SimpleSize = Simple.getSizeInBits();
2535     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2536     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2537       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2538       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2539       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2540       // Compute the high part as N1.
2541       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2542             DAG.getConstant(SimpleSize, DL,
2543                             getShiftAmountTy(Lo.getValueType())));
2544       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2545       // Compute the low part as N0.
2546       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2547       return CombineTo(N, Lo, Hi);
2548     }
2549   }
2550
2551   return SDValue();
2552 }
2553
2554 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2555   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2556   if (Res.getNode()) return Res;
2557
2558   EVT VT = N->getValueType(0);
2559   SDLoc DL(N);
2560
2561   // If the type is twice as wide is legal, transform the mulhu to a wider
2562   // multiply plus a shift.
2563   if (VT.isSimple() && !VT.isVector()) {
2564     MVT Simple = VT.getSimpleVT();
2565     unsigned SimpleSize = Simple.getSizeInBits();
2566     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2567     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2568       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2569       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2570       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2571       // Compute the high part as N1.
2572       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2573             DAG.getConstant(SimpleSize, DL,
2574                             getShiftAmountTy(Lo.getValueType())));
2575       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2576       // Compute the low part as N0.
2577       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2578       return CombineTo(N, Lo, Hi);
2579     }
2580   }
2581
2582   return SDValue();
2583 }
2584
2585 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2586   // (smulo x, 2) -> (saddo x, x)
2587   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2588     if (C2->getAPIntValue() == 2)
2589       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2590                          N->getOperand(0), N->getOperand(0));
2591
2592   return SDValue();
2593 }
2594
2595 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2596   // (umulo x, 2) -> (uaddo x, x)
2597   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2598     if (C2->getAPIntValue() == 2)
2599       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2600                          N->getOperand(0), N->getOperand(0));
2601
2602   return SDValue();
2603 }
2604
2605 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2606   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2607   if (Res.getNode()) return Res;
2608
2609   return SDValue();
2610 }
2611
2612 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2613   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2614   if (Res.getNode()) return Res;
2615
2616   return SDValue();
2617 }
2618
2619 /// If this is a binary operator with two operands of the same opcode, try to
2620 /// simplify it.
2621 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2622   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2623   EVT VT = N0.getValueType();
2624   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2625
2626   // Bail early if none of these transforms apply.
2627   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2628
2629   // For each of OP in AND/OR/XOR:
2630   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2631   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2632   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2633   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2634   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2635   //
2636   // do not sink logical op inside of a vector extend, since it may combine
2637   // into a vsetcc.
2638   EVT Op0VT = N0.getOperand(0).getValueType();
2639   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2640        N0.getOpcode() == ISD::SIGN_EXTEND ||
2641        N0.getOpcode() == ISD::BSWAP ||
2642        // Avoid infinite looping with PromoteIntBinOp.
2643        (N0.getOpcode() == ISD::ANY_EXTEND &&
2644         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2645        (N0.getOpcode() == ISD::TRUNCATE &&
2646         (!TLI.isZExtFree(VT, Op0VT) ||
2647          !TLI.isTruncateFree(Op0VT, VT)) &&
2648         TLI.isTypeLegal(Op0VT))) &&
2649       !VT.isVector() &&
2650       Op0VT == N1.getOperand(0).getValueType() &&
2651       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2652     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2653                                  N0.getOperand(0).getValueType(),
2654                                  N0.getOperand(0), N1.getOperand(0));
2655     AddToWorklist(ORNode.getNode());
2656     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2657   }
2658
2659   // For each of OP in SHL/SRL/SRA/AND...
2660   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2661   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2662   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2663   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2664        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2665       N0.getOperand(1) == N1.getOperand(1)) {
2666     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2667                                  N0.getOperand(0).getValueType(),
2668                                  N0.getOperand(0), N1.getOperand(0));
2669     AddToWorklist(ORNode.getNode());
2670     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2671                        ORNode, N0.getOperand(1));
2672   }
2673
2674   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2675   // Only perform this optimization after type legalization and before
2676   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2677   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2678   // we don't want to undo this promotion.
2679   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2680   // on scalars.
2681   if ((N0.getOpcode() == ISD::BITCAST ||
2682        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2683       Level == AfterLegalizeTypes) {
2684     SDValue In0 = N0.getOperand(0);
2685     SDValue In1 = N1.getOperand(0);
2686     EVT In0Ty = In0.getValueType();
2687     EVT In1Ty = In1.getValueType();
2688     SDLoc DL(N);
2689     // If both incoming values are integers, and the original types are the
2690     // same.
2691     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2692       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2693       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2694       AddToWorklist(Op.getNode());
2695       return BC;
2696     }
2697   }
2698
2699   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2700   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2701   // If both shuffles use the same mask, and both shuffle within a single
2702   // vector, then it is worthwhile to move the swizzle after the operation.
2703   // The type-legalizer generates this pattern when loading illegal
2704   // vector types from memory. In many cases this allows additional shuffle
2705   // optimizations.
2706   // There are other cases where moving the shuffle after the xor/and/or
2707   // is profitable even if shuffles don't perform a swizzle.
2708   // If both shuffles use the same mask, and both shuffles have the same first
2709   // or second operand, then it might still be profitable to move the shuffle
2710   // after the xor/and/or operation.
2711   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2712     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2713     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2714
2715     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2716            "Inputs to shuffles are not the same type");
2717
2718     // Check that both shuffles use the same mask. The masks are known to be of
2719     // the same length because the result vector type is the same.
2720     // Check also that shuffles have only one use to avoid introducing extra
2721     // instructions.
2722     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2723         SVN0->getMask().equals(SVN1->getMask())) {
2724       SDValue ShOp = N0->getOperand(1);
2725
2726       // Don't try to fold this node if it requires introducing a
2727       // build vector of all zeros that might be illegal at this stage.
2728       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2729         if (!LegalTypes)
2730           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2731         else
2732           ShOp = SDValue();
2733       }
2734
2735       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2736       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2737       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2738       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2739         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2740                                       N0->getOperand(0), N1->getOperand(0));
2741         AddToWorklist(NewNode.getNode());
2742         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2743                                     &SVN0->getMask()[0]);
2744       }
2745
2746       // Don't try to fold this node if it requires introducing a
2747       // build vector of all zeros that might be illegal at this stage.
2748       ShOp = N0->getOperand(0);
2749       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2750         if (!LegalTypes)
2751           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2752         else
2753           ShOp = SDValue();
2754       }
2755
2756       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2757       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2758       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2759       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2760         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2761                                       N0->getOperand(1), N1->getOperand(1));
2762         AddToWorklist(NewNode.getNode());
2763         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2764                                     &SVN0->getMask()[0]);
2765       }
2766     }
2767   }
2768
2769   return SDValue();
2770 }
2771
2772 /// This contains all DAGCombine rules which reduce two values combined by
2773 /// an And operation to a single value. This makes them reusable in the context
2774 /// of visitSELECT(). Rules involving constants are not included as
2775 /// visitSELECT() already handles those cases.
2776 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2777                                   SDNode *LocReference) {
2778   EVT VT = N1.getValueType();
2779
2780   // fold (and x, undef) -> 0
2781   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2782     return DAG.getConstant(0, SDLoc(LocReference), VT);
2783   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2784   SDValue LL, LR, RL, RR, CC0, CC1;
2785   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2786     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2787     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2788
2789     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2790         LL.getValueType().isInteger()) {
2791       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2792       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2793         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2794                                      LR.getValueType(), LL, RL);
2795         AddToWorklist(ORNode.getNode());
2796         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2797       }
2798       if (isAllOnesConstant(LR)) {
2799         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2800         if (Op1 == ISD::SETEQ) {
2801           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2802                                         LR.getValueType(), LL, RL);
2803           AddToWorklist(ANDNode.getNode());
2804           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2805         }
2806         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2807         if (Op1 == ISD::SETGT) {
2808           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2809                                        LR.getValueType(), LL, RL);
2810           AddToWorklist(ORNode.getNode());
2811           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2812         }
2813       }
2814     }
2815     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2816     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2817         Op0 == Op1 && LL.getValueType().isInteger() &&
2818       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2819                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2820       SDLoc DL(N0);
2821       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2822                                     LL, DAG.getConstant(1, DL,
2823                                                         LL.getValueType()));
2824       AddToWorklist(ADDNode.getNode());
2825       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2826                           DAG.getConstant(2, DL, LL.getValueType()),
2827                           ISD::SETUGE);
2828     }
2829     // canonicalize equivalent to ll == rl
2830     if (LL == RR && LR == RL) {
2831       Op1 = ISD::getSetCCSwappedOperands(Op1);
2832       std::swap(RL, RR);
2833     }
2834     if (LL == RL && LR == RR) {
2835       bool isInteger = LL.getValueType().isInteger();
2836       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2837       if (Result != ISD::SETCC_INVALID &&
2838           (!LegalOperations ||
2839            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2840             TLI.isOperationLegal(ISD::SETCC,
2841                             getSetCCResultType(N0.getSimpleValueType())))))
2842         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2843                             LL, LR, Result);
2844     }
2845   }
2846
2847   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2848       VT.getSizeInBits() <= 64) {
2849     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2850       APInt ADDC = ADDI->getAPIntValue();
2851       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2852         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2853         // immediate for an add, but it is legal if its top c2 bits are set,
2854         // transform the ADD so the immediate doesn't need to be materialized
2855         // in a register.
2856         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2857           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2858                                              SRLI->getZExtValue());
2859           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2860             ADDC |= Mask;
2861             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2862               SDLoc DL(N0);
2863               SDValue NewAdd =
2864                 DAG.getNode(ISD::ADD, DL, VT,
2865                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2866               CombineTo(N0.getNode(), NewAdd);
2867               // Return N so it doesn't get rechecked!
2868               return SDValue(LocReference, 0);
2869             }
2870           }
2871         }
2872       }
2873     }
2874   }
2875
2876   return SDValue();
2877 }
2878
2879 SDValue DAGCombiner::visitAND(SDNode *N) {
2880   SDValue N0 = N->getOperand(0);
2881   SDValue N1 = N->getOperand(1);
2882   EVT VT = N1.getValueType();
2883
2884   // fold vector ops
2885   if (VT.isVector()) {
2886     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2887       return FoldedVOp;
2888
2889     // fold (and x, 0) -> 0, vector edition
2890     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2891       // do not return N0, because undef node may exist in N0
2892       return DAG.getConstant(
2893           APInt::getNullValue(
2894               N0.getValueType().getScalarType().getSizeInBits()),
2895           SDLoc(N), N0.getValueType());
2896     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2897       // do not return N1, because undef node may exist in N1
2898       return DAG.getConstant(
2899           APInt::getNullValue(
2900               N1.getValueType().getScalarType().getSizeInBits()),
2901           SDLoc(N), N1.getValueType());
2902
2903     // fold (and x, -1) -> x, vector edition
2904     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2905       return N1;
2906     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2907       return N0;
2908   }
2909
2910   // fold (and c1, c2) -> c1&c2
2911   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2912   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2913   if (N0C && N1C && !N1C->isOpaque())
2914     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2915   // canonicalize constant to RHS
2916   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2917      !isConstantIntBuildVectorOrConstantInt(N1))
2918     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2919   // fold (and x, -1) -> x
2920   if (isAllOnesConstant(N1))
2921     return N0;
2922   // if (and x, c) is known to be zero, return 0
2923   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2924   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2925                                    APInt::getAllOnesValue(BitWidth)))
2926     return DAG.getConstant(0, SDLoc(N), VT);
2927   // reassociate and
2928   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2929     return RAND;
2930   // fold (and (or x, C), D) -> D if (C & D) == D
2931   if (N1C && N0.getOpcode() == ISD::OR)
2932     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2933       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2934         return N1;
2935   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2936   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2937     SDValue N0Op0 = N0.getOperand(0);
2938     APInt Mask = ~N1C->getAPIntValue();
2939     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2940     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2941       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2942                                  N0.getValueType(), N0Op0);
2943
2944       // Replace uses of the AND with uses of the Zero extend node.
2945       CombineTo(N, Zext);
2946
2947       // We actually want to replace all uses of the any_extend with the
2948       // zero_extend, to avoid duplicating things.  This will later cause this
2949       // AND to be folded.
2950       CombineTo(N0.getNode(), Zext);
2951       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2952     }
2953   }
2954   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2955   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2956   // already be zero by virtue of the width of the base type of the load.
2957   //
2958   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2959   // more cases.
2960   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2961        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2962       N0.getOpcode() == ISD::LOAD) {
2963     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2964                                          N0 : N0.getOperand(0) );
2965
2966     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2967     // This can be a pure constant or a vector splat, in which case we treat the
2968     // vector as a scalar and use the splat value.
2969     APInt Constant = APInt::getNullValue(1);
2970     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2971       Constant = C->getAPIntValue();
2972     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2973       APInt SplatValue, SplatUndef;
2974       unsigned SplatBitSize;
2975       bool HasAnyUndefs;
2976       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2977                                              SplatBitSize, HasAnyUndefs);
2978       if (IsSplat) {
2979         // Undef bits can contribute to a possible optimisation if set, so
2980         // set them.
2981         SplatValue |= SplatUndef;
2982
2983         // The splat value may be something like "0x00FFFFFF", which means 0 for
2984         // the first vector value and FF for the rest, repeating. We need a mask
2985         // that will apply equally to all members of the vector, so AND all the
2986         // lanes of the constant together.
2987         EVT VT = Vector->getValueType(0);
2988         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2989
2990         // If the splat value has been compressed to a bitlength lower
2991         // than the size of the vector lane, we need to re-expand it to
2992         // the lane size.
2993         if (BitWidth > SplatBitSize)
2994           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2995                SplatBitSize < BitWidth;
2996                SplatBitSize = SplatBitSize * 2)
2997             SplatValue |= SplatValue.shl(SplatBitSize);
2998
2999         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3000         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3001         if (SplatBitSize % BitWidth == 0) {
3002           Constant = APInt::getAllOnesValue(BitWidth);
3003           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3004             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3005         }
3006       }
3007     }
3008
3009     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3010     // actually legal and isn't going to get expanded, else this is a false
3011     // optimisation.
3012     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3013                                                     Load->getValueType(0),
3014                                                     Load->getMemoryVT());
3015
3016     // Resize the constant to the same size as the original memory access before
3017     // extension. If it is still the AllOnesValue then this AND is completely
3018     // unneeded.
3019     Constant =
3020       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3021
3022     bool B;
3023     switch (Load->getExtensionType()) {
3024     default: B = false; break;
3025     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3026     case ISD::ZEXTLOAD:
3027     case ISD::NON_EXTLOAD: B = true; break;
3028     }
3029
3030     if (B && Constant.isAllOnesValue()) {
3031       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3032       // preserve semantics once we get rid of the AND.
3033       SDValue NewLoad(Load, 0);
3034       if (Load->getExtensionType() == ISD::EXTLOAD) {
3035         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3036                               Load->getValueType(0), SDLoc(Load),
3037                               Load->getChain(), Load->getBasePtr(),
3038                               Load->getOffset(), Load->getMemoryVT(),
3039                               Load->getMemOperand());
3040         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3041         if (Load->getNumValues() == 3) {
3042           // PRE/POST_INC loads have 3 values.
3043           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3044                            NewLoad.getValue(2) };
3045           CombineTo(Load, To, 3, true);
3046         } else {
3047           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3048         }
3049       }
3050
3051       // Fold the AND away, taking care not to fold to the old load node if we
3052       // replaced it.
3053       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3054
3055       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3056     }
3057   }
3058
3059   // fold (and (load x), 255) -> (zextload x, i8)
3060   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3061   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3062   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3063               (N0.getOpcode() == ISD::ANY_EXTEND &&
3064                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3065     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3066     LoadSDNode *LN0 = HasAnyExt
3067       ? cast<LoadSDNode>(N0.getOperand(0))
3068       : cast<LoadSDNode>(N0);
3069     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3070         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3071       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3072       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3073         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3074         EVT LoadedVT = LN0->getMemoryVT();
3075         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3076
3077         if (ExtVT == LoadedVT &&
3078             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3079                                                     ExtVT))) {
3080
3081           SDValue NewLoad =
3082             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3083                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3084                            LN0->getMemOperand());
3085           AddToWorklist(N);
3086           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3087           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3088         }
3089
3090         // Do not change the width of a volatile load.
3091         // Do not generate loads of non-round integer types since these can
3092         // be expensive (and would be wrong if the type is not byte sized).
3093         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3094             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3095                                                     ExtVT))) {
3096           EVT PtrType = LN0->getOperand(1).getValueType();
3097
3098           unsigned Alignment = LN0->getAlignment();
3099           SDValue NewPtr = LN0->getBasePtr();
3100
3101           // For big endian targets, we need to add an offset to the pointer
3102           // to load the correct bytes.  For little endian systems, we merely
3103           // need to read fewer bytes from the same pointer.
3104           if (TLI.isBigEndian()) {
3105             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3106             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3107             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3108             SDLoc DL(LN0);
3109             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3110                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3111             Alignment = MinAlign(Alignment, PtrOff);
3112           }
3113
3114           AddToWorklist(NewPtr.getNode());
3115
3116           SDValue Load =
3117             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3118                            LN0->getChain(), NewPtr,
3119                            LN0->getPointerInfo(),
3120                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3121                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3122           AddToWorklist(N);
3123           CombineTo(LN0, Load, Load.getValue(1));
3124           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3125         }
3126       }
3127     }
3128   }
3129
3130   if (SDValue Combined = visitANDLike(N0, N1, N))
3131     return Combined;
3132
3133   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3134   if (N0.getOpcode() == N1.getOpcode()) {
3135     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3136     if (Tmp.getNode()) return Tmp;
3137   }
3138
3139   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3140   // fold (and (sra)) -> (and (srl)) when possible.
3141   if (!VT.isVector() &&
3142       SimplifyDemandedBits(SDValue(N, 0)))
3143     return SDValue(N, 0);
3144
3145   // fold (zext_inreg (extload x)) -> (zextload x)
3146   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3147     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3148     EVT MemVT = LN0->getMemoryVT();
3149     // If we zero all the possible extended bits, then we can turn this into
3150     // a zextload if we are running before legalize or the operation is legal.
3151     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3152     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3153                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3154         ((!LegalOperations && !LN0->isVolatile()) ||
3155          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3156       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3157                                        LN0->getChain(), LN0->getBasePtr(),
3158                                        MemVT, LN0->getMemOperand());
3159       AddToWorklist(N);
3160       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3161       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3162     }
3163   }
3164   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3165   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3166       N0.hasOneUse()) {
3167     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3168     EVT MemVT = LN0->getMemoryVT();
3169     // If we zero all the possible extended bits, then we can turn this into
3170     // a zextload if we are running before legalize or the operation is legal.
3171     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3172     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3173                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3174         ((!LegalOperations && !LN0->isVolatile()) ||
3175          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3176       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3177                                        LN0->getChain(), LN0->getBasePtr(),
3178                                        MemVT, LN0->getMemOperand());
3179       AddToWorklist(N);
3180       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3181       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3182     }
3183   }
3184   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3185   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3186     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3187                                        N0.getOperand(1), false);
3188     if (BSwap.getNode())
3189       return BSwap;
3190   }
3191
3192   return SDValue();
3193 }
3194
3195 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3196 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3197                                         bool DemandHighBits) {
3198   if (!LegalOperations)
3199     return SDValue();
3200
3201   EVT VT = N->getValueType(0);
3202   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3203     return SDValue();
3204   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3205     return SDValue();
3206
3207   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3208   bool LookPassAnd0 = false;
3209   bool LookPassAnd1 = false;
3210   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3211       std::swap(N0, N1);
3212   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3213       std::swap(N0, N1);
3214   if (N0.getOpcode() == ISD::AND) {
3215     if (!N0.getNode()->hasOneUse())
3216       return SDValue();
3217     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3218     if (!N01C || N01C->getZExtValue() != 0xFF00)
3219       return SDValue();
3220     N0 = N0.getOperand(0);
3221     LookPassAnd0 = true;
3222   }
3223
3224   if (N1.getOpcode() == ISD::AND) {
3225     if (!N1.getNode()->hasOneUse())
3226       return SDValue();
3227     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3228     if (!N11C || N11C->getZExtValue() != 0xFF)
3229       return SDValue();
3230     N1 = N1.getOperand(0);
3231     LookPassAnd1 = true;
3232   }
3233
3234   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3235     std::swap(N0, N1);
3236   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3237     return SDValue();
3238   if (!N0.getNode()->hasOneUse() ||
3239       !N1.getNode()->hasOneUse())
3240     return SDValue();
3241
3242   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3243   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3244   if (!N01C || !N11C)
3245     return SDValue();
3246   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3247     return SDValue();
3248
3249   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3250   SDValue N00 = N0->getOperand(0);
3251   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3252     if (!N00.getNode()->hasOneUse())
3253       return SDValue();
3254     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3255     if (!N001C || N001C->getZExtValue() != 0xFF)
3256       return SDValue();
3257     N00 = N00.getOperand(0);
3258     LookPassAnd0 = true;
3259   }
3260
3261   SDValue N10 = N1->getOperand(0);
3262   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3263     if (!N10.getNode()->hasOneUse())
3264       return SDValue();
3265     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3266     if (!N101C || N101C->getZExtValue() != 0xFF00)
3267       return SDValue();
3268     N10 = N10.getOperand(0);
3269     LookPassAnd1 = true;
3270   }
3271
3272   if (N00 != N10)
3273     return SDValue();
3274
3275   // Make sure everything beyond the low halfword gets set to zero since the SRL
3276   // 16 will clear the top bits.
3277   unsigned OpSizeInBits = VT.getSizeInBits();
3278   if (DemandHighBits && OpSizeInBits > 16) {
3279     // If the left-shift isn't masked out then the only way this is a bswap is
3280     // if all bits beyond the low 8 are 0. In that case the entire pattern
3281     // reduces to a left shift anyway: leave it for other parts of the combiner.
3282     if (!LookPassAnd0)
3283       return SDValue();
3284
3285     // However, if the right shift isn't masked out then it might be because
3286     // it's not needed. See if we can spot that too.
3287     if (!LookPassAnd1 &&
3288         !DAG.MaskedValueIsZero(
3289             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3290       return SDValue();
3291   }
3292
3293   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3294   if (OpSizeInBits > 16) {
3295     SDLoc DL(N);
3296     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3297                       DAG.getConstant(OpSizeInBits - 16, DL,
3298                                       getShiftAmountTy(VT)));
3299   }
3300   return Res;
3301 }
3302
3303 /// Return true if the specified node is an element that makes up a 32-bit
3304 /// packed halfword byteswap.
3305 /// ((x & 0x000000ff) << 8) |
3306 /// ((x & 0x0000ff00) >> 8) |
3307 /// ((x & 0x00ff0000) << 8) |
3308 /// ((x & 0xff000000) >> 8)
3309 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3310   if (!N.getNode()->hasOneUse())
3311     return false;
3312
3313   unsigned Opc = N.getOpcode();
3314   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3315     return false;
3316
3317   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3318   if (!N1C)
3319     return false;
3320
3321   unsigned Num;
3322   switch (N1C->getZExtValue()) {
3323   default:
3324     return false;
3325   case 0xFF:       Num = 0; break;
3326   case 0xFF00:     Num = 1; break;
3327   case 0xFF0000:   Num = 2; break;
3328   case 0xFF000000: Num = 3; break;
3329   }
3330
3331   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3332   SDValue N0 = N.getOperand(0);
3333   if (Opc == ISD::AND) {
3334     if (Num == 0 || Num == 2) {
3335       // (x >> 8) & 0xff
3336       // (x >> 8) & 0xff0000
3337       if (N0.getOpcode() != ISD::SRL)
3338         return false;
3339       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3340       if (!C || C->getZExtValue() != 8)
3341         return false;
3342     } else {
3343       // (x << 8) & 0xff00
3344       // (x << 8) & 0xff000000
3345       if (N0.getOpcode() != ISD::SHL)
3346         return false;
3347       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3348       if (!C || C->getZExtValue() != 8)
3349         return false;
3350     }
3351   } else if (Opc == ISD::SHL) {
3352     // (x & 0xff) << 8
3353     // (x & 0xff0000) << 8
3354     if (Num != 0 && Num != 2)
3355       return false;
3356     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3357     if (!C || C->getZExtValue() != 8)
3358       return false;
3359   } else { // Opc == ISD::SRL
3360     // (x & 0xff00) >> 8
3361     // (x & 0xff000000) >> 8
3362     if (Num != 1 && Num != 3)
3363       return false;
3364     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3365     if (!C || C->getZExtValue() != 8)
3366       return false;
3367   }
3368
3369   if (Parts[Num])
3370     return false;
3371
3372   Parts[Num] = N0.getOperand(0).getNode();
3373   return true;
3374 }
3375
3376 /// Match a 32-bit packed halfword bswap. That is
3377 /// ((x & 0x000000ff) << 8) |
3378 /// ((x & 0x0000ff00) >> 8) |
3379 /// ((x & 0x00ff0000) << 8) |
3380 /// ((x & 0xff000000) >> 8)
3381 /// => (rotl (bswap x), 16)
3382 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3383   if (!LegalOperations)
3384     return SDValue();
3385
3386   EVT VT = N->getValueType(0);
3387   if (VT != MVT::i32)
3388     return SDValue();
3389   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3390     return SDValue();
3391
3392   // Look for either
3393   // (or (or (and), (and)), (or (and), (and)))
3394   // (or (or (or (and), (and)), (and)), (and))
3395   if (N0.getOpcode() != ISD::OR)
3396     return SDValue();
3397   SDValue N00 = N0.getOperand(0);
3398   SDValue N01 = N0.getOperand(1);
3399   SDNode *Parts[4] = {};
3400
3401   if (N1.getOpcode() == ISD::OR &&
3402       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3403     // (or (or (and), (and)), (or (and), (and)))
3404     SDValue N000 = N00.getOperand(0);
3405     if (!isBSwapHWordElement(N000, Parts))
3406       return SDValue();
3407
3408     SDValue N001 = N00.getOperand(1);
3409     if (!isBSwapHWordElement(N001, Parts))
3410       return SDValue();
3411     SDValue N010 = N01.getOperand(0);
3412     if (!isBSwapHWordElement(N010, Parts))
3413       return SDValue();
3414     SDValue N011 = N01.getOperand(1);
3415     if (!isBSwapHWordElement(N011, Parts))
3416       return SDValue();
3417   } else {
3418     // (or (or (or (and), (and)), (and)), (and))
3419     if (!isBSwapHWordElement(N1, Parts))
3420       return SDValue();
3421     if (!isBSwapHWordElement(N01, Parts))
3422       return SDValue();
3423     if (N00.getOpcode() != ISD::OR)
3424       return SDValue();
3425     SDValue N000 = N00.getOperand(0);
3426     if (!isBSwapHWordElement(N000, Parts))
3427       return SDValue();
3428     SDValue N001 = N00.getOperand(1);
3429     if (!isBSwapHWordElement(N001, Parts))
3430       return SDValue();
3431   }
3432
3433   // Make sure the parts are all coming from the same node.
3434   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3435     return SDValue();
3436
3437   SDLoc DL(N);
3438   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3439                               SDValue(Parts[0], 0));
3440
3441   // Result of the bswap should be rotated by 16. If it's not legal, then
3442   // do  (x << 16) | (x >> 16).
3443   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3444   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3445     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3446   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3447     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3448   return DAG.getNode(ISD::OR, DL, VT,
3449                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3450                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3451 }
3452
3453 /// This contains all DAGCombine rules which reduce two values combined by
3454 /// an Or operation to a single value \see visitANDLike().
3455 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3456   EVT VT = N1.getValueType();
3457   // fold (or x, undef) -> -1
3458   if (!LegalOperations &&
3459       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3460     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3461     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3462                            SDLoc(LocReference), VT);
3463   }
3464   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3465   SDValue LL, LR, RL, RR, CC0, CC1;
3466   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3467     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3468     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3469
3470     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3471       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3472       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3473       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3474         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3475                                      LR.getValueType(), LL, RL);
3476         AddToWorklist(ORNode.getNode());
3477         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3478       }
3479       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3480       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3481       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3482         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3483                                       LR.getValueType(), LL, RL);
3484         AddToWorklist(ANDNode.getNode());
3485         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3486       }
3487     }
3488     // canonicalize equivalent to ll == rl
3489     if (LL == RR && LR == RL) {
3490       Op1 = ISD::getSetCCSwappedOperands(Op1);
3491       std::swap(RL, RR);
3492     }
3493     if (LL == RL && LR == RR) {
3494       bool isInteger = LL.getValueType().isInteger();
3495       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3496       if (Result != ISD::SETCC_INVALID &&
3497           (!LegalOperations ||
3498            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3499             TLI.isOperationLegal(ISD::SETCC,
3500               getSetCCResultType(N0.getValueType())))))
3501         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3502                             LL, LR, Result);
3503     }
3504   }
3505
3506   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3507   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3508       // Don't increase # computations.
3509       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3510     // We can only do this xform if we know that bits from X that are set in C2
3511     // but not in C1 are already zero.  Likewise for Y.
3512     if (const ConstantSDNode *N0O1C =
3513         getAsNonOpaqueConstant(N0.getOperand(1))) {
3514       if (const ConstantSDNode *N1O1C =
3515           getAsNonOpaqueConstant(N1.getOperand(1))) {
3516         // We can only do this xform if we know that bits from X that are set in
3517         // C2 but not in C1 are already zero.  Likewise for Y.
3518         const APInt &LHSMask = N0O1C->getAPIntValue();
3519         const APInt &RHSMask = N1O1C->getAPIntValue();
3520
3521         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524                                   N0.getOperand(0), N1.getOperand(0));
3525           SDLoc DL(LocReference);
3526           return DAG.getNode(ISD::AND, DL, VT, X,
3527                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3528         }
3529       }
3530     }
3531   }
3532
3533   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3534   if (N0.getOpcode() == ISD::AND &&
3535       N1.getOpcode() == ISD::AND &&
3536       N0.getOperand(0) == N1.getOperand(0) &&
3537       // Don't increase # computations.
3538       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3539     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3540                             N0.getOperand(1), N1.getOperand(1));
3541     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3542   }
3543
3544   return SDValue();
3545 }
3546
3547 SDValue DAGCombiner::visitOR(SDNode *N) {
3548   SDValue N0 = N->getOperand(0);
3549   SDValue N1 = N->getOperand(1);
3550   EVT VT = N1.getValueType();
3551
3552   // fold vector ops
3553   if (VT.isVector()) {
3554     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3555       return FoldedVOp;
3556
3557     // fold (or x, 0) -> x, vector edition
3558     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3559       return N1;
3560     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3561       return N0;
3562
3563     // fold (or x, -1) -> -1, vector edition
3564     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3565       // do not return N0, because undef node may exist in N0
3566       return DAG.getConstant(
3567           APInt::getAllOnesValue(
3568               N0.getValueType().getScalarType().getSizeInBits()),
3569           SDLoc(N), N0.getValueType());
3570     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3571       // do not return N1, because undef node may exist in N1
3572       return DAG.getConstant(
3573           APInt::getAllOnesValue(
3574               N1.getValueType().getScalarType().getSizeInBits()),
3575           SDLoc(N), N1.getValueType());
3576
3577     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3578     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3579     // Do this only if the resulting shuffle is legal.
3580     if (isa<ShuffleVectorSDNode>(N0) &&
3581         isa<ShuffleVectorSDNode>(N1) &&
3582         // Avoid folding a node with illegal type.
3583         TLI.isTypeLegal(VT) &&
3584         N0->getOperand(1) == N1->getOperand(1) &&
3585         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3586       bool CanFold = true;
3587       unsigned NumElts = VT.getVectorNumElements();
3588       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3589       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3590       // We construct two shuffle masks:
3591       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3592       // and N1 as the second operand.
3593       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3594       // and N0 as the second operand.
3595       // We do this because OR is commutable and therefore there might be
3596       // two ways to fold this node into a shuffle.
3597       SmallVector<int,4> Mask1;
3598       SmallVector<int,4> Mask2;
3599
3600       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3601         int M0 = SV0->getMaskElt(i);
3602         int M1 = SV1->getMaskElt(i);
3603
3604         // Both shuffle indexes are undef. Propagate Undef.
3605         if (M0 < 0 && M1 < 0) {
3606           Mask1.push_back(M0);
3607           Mask2.push_back(M0);
3608           continue;
3609         }
3610
3611         if (M0 < 0 || M1 < 0 ||
3612             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3613             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3614           CanFold = false;
3615           break;
3616         }
3617
3618         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3619         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3620       }
3621
3622       if (CanFold) {
3623         // Fold this sequence only if the resulting shuffle is 'legal'.
3624         if (TLI.isShuffleMaskLegal(Mask1, VT))
3625           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3626                                       N1->getOperand(0), &Mask1[0]);
3627         if (TLI.isShuffleMaskLegal(Mask2, VT))
3628           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3629                                       N0->getOperand(0), &Mask2[0]);
3630       }
3631     }
3632   }
3633
3634   // fold (or c1, c2) -> c1|c2
3635   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3636   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3637   if (N0C && N1C && !N1C->isOpaque())
3638     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3639   // canonicalize constant to RHS
3640   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3641      !isConstantIntBuildVectorOrConstantInt(N1))
3642     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3643   // fold (or x, 0) -> x
3644   if (isNullConstant(N1))
3645     return N0;
3646   // fold (or x, -1) -> -1
3647   if (isAllOnesConstant(N1))
3648     return N1;
3649   // fold (or x, c) -> c iff (x & ~c) == 0
3650   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3651     return N1;
3652
3653   if (SDValue Combined = visitORLike(N0, N1, N))
3654     return Combined;
3655
3656   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3657   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3658   if (BSwap.getNode())
3659     return BSwap;
3660   BSwap = MatchBSwapHWordLow(N, N0, N1);
3661   if (BSwap.getNode())
3662     return BSwap;
3663
3664   // reassociate or
3665   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3666     return ROR;
3667   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3668   // iff (c1 & c2) == 0.
3669   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3670              isa<ConstantSDNode>(N0.getOperand(1))) {
3671     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3672     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3673       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3674                                                    N1C, C1))
3675         return DAG.getNode(
3676             ISD::AND, SDLoc(N), VT,
3677             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3678       return SDValue();
3679     }
3680   }
3681   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3682   if (N0.getOpcode() == N1.getOpcode()) {
3683     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3684     if (Tmp.getNode()) return Tmp;
3685   }
3686
3687   // See if this is some rotate idiom.
3688   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3689     return SDValue(Rot, 0);
3690
3691   // Simplify the operands using demanded-bits information.
3692   if (!VT.isVector() &&
3693       SimplifyDemandedBits(SDValue(N, 0)))
3694     return SDValue(N, 0);
3695
3696   return SDValue();
3697 }
3698
3699 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3700 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3701   if (Op.getOpcode() == ISD::AND) {
3702     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3703       Mask = Op.getOperand(1);
3704       Op = Op.getOperand(0);
3705     } else {
3706       return false;
3707     }
3708   }
3709
3710   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3711     Shift = Op;
3712     return true;
3713   }
3714
3715   return false;
3716 }
3717
3718 // Return true if we can prove that, whenever Neg and Pos are both in the
3719 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3720 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3721 //
3722 //     (or (shift1 X, Neg), (shift2 X, Pos))
3723 //
3724 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3725 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3726 // to consider shift amounts with defined behavior.
3727 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3728   // If OpSize is a power of 2 then:
3729   //
3730   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3731   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3732   //
3733   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3734   // for the stronger condition:
3735   //
3736   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3737   //
3738   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3739   // we can just replace Neg with Neg' for the rest of the function.
3740   //
3741   // In other cases we check for the even stronger condition:
3742   //
3743   //     Neg == OpSize - Pos                                    [B]
3744   //
3745   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3746   // behavior if Pos == 0 (and consequently Neg == OpSize).
3747   //
3748   // We could actually use [A] whenever OpSize is a power of 2, but the
3749   // only extra cases that it would match are those uninteresting ones
3750   // where Neg and Pos are never in range at the same time.  E.g. for
3751   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3752   // as well as (sub 32, Pos), but:
3753   //
3754   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3755   //
3756   // always invokes undefined behavior for 32-bit X.
3757   //
3758   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3759   unsigned MaskLoBits = 0;
3760   if (Neg.getOpcode() == ISD::AND &&
3761       isPowerOf2_64(OpSize) &&
3762       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3763       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3764     Neg = Neg.getOperand(0);
3765     MaskLoBits = Log2_64(OpSize);
3766   }
3767
3768   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3769   if (Neg.getOpcode() != ISD::SUB)
3770     return 0;
3771   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3772   if (!NegC)
3773     return 0;
3774   SDValue NegOp1 = Neg.getOperand(1);
3775
3776   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3777   // Pos'.  The truncation is redundant for the purpose of the equality.
3778   if (MaskLoBits &&
3779       Pos.getOpcode() == ISD::AND &&
3780       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3781       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3782     Pos = Pos.getOperand(0);
3783
3784   // The condition we need is now:
3785   //
3786   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3787   //
3788   // If NegOp1 == Pos then we need:
3789   //
3790   //              OpSize & Mask == NegC & Mask
3791   //
3792   // (because "x & Mask" is a truncation and distributes through subtraction).
3793   APInt Width;
3794   if (Pos == NegOp1)
3795     Width = NegC->getAPIntValue();
3796   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3797   // Then the condition we want to prove becomes:
3798   //
3799   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3800   //
3801   // which, again because "x & Mask" is a truncation, becomes:
3802   //
3803   //                NegC & Mask == (OpSize - PosC) & Mask
3804   //              OpSize & Mask == (NegC + PosC) & Mask
3805   else if (Pos.getOpcode() == ISD::ADD &&
3806            Pos.getOperand(0) == NegOp1 &&
3807            Pos.getOperand(1).getOpcode() == ISD::Constant)
3808     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3809              NegC->getAPIntValue());
3810   else
3811     return false;
3812
3813   // Now we just need to check that OpSize & Mask == Width & Mask.
3814   if (MaskLoBits)
3815     // Opsize & Mask is 0 since Mask is Opsize - 1.
3816     return Width.getLoBits(MaskLoBits) == 0;
3817   return Width == OpSize;
3818 }
3819
3820 // A subroutine of MatchRotate used once we have found an OR of two opposite
3821 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3822 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3823 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3824 // Neg with outer conversions stripped away.
3825 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3826                                        SDValue Neg, SDValue InnerPos,
3827                                        SDValue InnerNeg, unsigned PosOpcode,
3828                                        unsigned NegOpcode, SDLoc DL) {
3829   // fold (or (shl x, (*ext y)),
3830   //          (srl x, (*ext (sub 32, y)))) ->
3831   //   (rotl x, y) or (rotr x, (sub 32, y))
3832   //
3833   // fold (or (shl x, (*ext (sub 32, y))),
3834   //          (srl x, (*ext y))) ->
3835   //   (rotr x, y) or (rotl x, (sub 32, y))
3836   EVT VT = Shifted.getValueType();
3837   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3838     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3839     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3840                        HasPos ? Pos : Neg).getNode();
3841   }
3842
3843   return nullptr;
3844 }
3845
3846 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3847 // idioms for rotate, and if the target supports rotation instructions, generate
3848 // a rot[lr].
3849 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3850   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3851   EVT VT = LHS.getValueType();
3852   if (!TLI.isTypeLegal(VT)) return nullptr;
3853
3854   // The target must have at least one rotate flavor.
3855   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3856   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3857   if (!HasROTL && !HasROTR) return nullptr;
3858
3859   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3860   SDValue LHSShift;   // The shift.
3861   SDValue LHSMask;    // AND value if any.
3862   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3863     return nullptr; // Not part of a rotate.
3864
3865   SDValue RHSShift;   // The shift.
3866   SDValue RHSMask;    // AND value if any.
3867   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3868     return nullptr; // Not part of a rotate.
3869
3870   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3871     return nullptr;   // Not shifting the same value.
3872
3873   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3874     return nullptr;   // Shifts must disagree.
3875
3876   // Canonicalize shl to left side in a shl/srl pair.
3877   if (RHSShift.getOpcode() == ISD::SHL) {
3878     std::swap(LHS, RHS);
3879     std::swap(LHSShift, RHSShift);
3880     std::swap(LHSMask , RHSMask );
3881   }
3882
3883   unsigned OpSizeInBits = VT.getSizeInBits();
3884   SDValue LHSShiftArg = LHSShift.getOperand(0);
3885   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3886   SDValue RHSShiftArg = RHSShift.getOperand(0);
3887   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3888
3889   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3890   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3891   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3892       RHSShiftAmt.getOpcode() == ISD::Constant) {
3893     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3894     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3895     if ((LShVal + RShVal) != OpSizeInBits)
3896       return nullptr;
3897
3898     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3899                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3900
3901     // If there is an AND of either shifted operand, apply it to the result.
3902     if (LHSMask.getNode() || RHSMask.getNode()) {
3903       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3904
3905       if (LHSMask.getNode()) {
3906         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3907         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3908       }
3909       if (RHSMask.getNode()) {
3910         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3911         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3912       }
3913
3914       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3915     }
3916
3917     return Rot.getNode();
3918   }
3919
3920   // If there is a mask here, and we have a variable shift, we can't be sure
3921   // that we're masking out the right stuff.
3922   if (LHSMask.getNode() || RHSMask.getNode())
3923     return nullptr;
3924
3925   // If the shift amount is sign/zext/any-extended just peel it off.
3926   SDValue LExtOp0 = LHSShiftAmt;
3927   SDValue RExtOp0 = RHSShiftAmt;
3928   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3929        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3930        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3931        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3932       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3933        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3934        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3935        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3936     LExtOp0 = LHSShiftAmt.getOperand(0);
3937     RExtOp0 = RHSShiftAmt.getOperand(0);
3938   }
3939
3940   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3941                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3942   if (TryL)
3943     return TryL;
3944
3945   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3946                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3947   if (TryR)
3948     return TryR;
3949
3950   return nullptr;
3951 }
3952
3953 SDValue DAGCombiner::visitXOR(SDNode *N) {
3954   SDValue N0 = N->getOperand(0);
3955   SDValue N1 = N->getOperand(1);
3956   EVT VT = N0.getValueType();
3957
3958   // fold vector ops
3959   if (VT.isVector()) {
3960     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3961       return FoldedVOp;
3962
3963     // fold (xor x, 0) -> x, vector edition
3964     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3965       return N1;
3966     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3967       return N0;
3968   }
3969
3970   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3971   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3972     return DAG.getConstant(0, SDLoc(N), VT);
3973   // fold (xor x, undef) -> undef
3974   if (N0.getOpcode() == ISD::UNDEF)
3975     return N0;
3976   if (N1.getOpcode() == ISD::UNDEF)
3977     return N1;
3978   // fold (xor c1, c2) -> c1^c2
3979   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3980   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3981   if (N0C && N1C)
3982     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3983   // canonicalize constant to RHS
3984   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3985      !isConstantIntBuildVectorOrConstantInt(N1))
3986     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3987   // fold (xor x, 0) -> x
3988   if (isNullConstant(N1))
3989     return N0;
3990   // reassociate xor
3991   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3992     return RXOR;
3993
3994   // fold !(x cc y) -> (x !cc y)
3995   SDValue LHS, RHS, CC;
3996   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3997     bool isInt = LHS.getValueType().isInteger();
3998     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3999                                                isInt);
4000
4001     if (!LegalOperations ||
4002         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4003       switch (N0.getOpcode()) {
4004       default:
4005         llvm_unreachable("Unhandled SetCC Equivalent!");
4006       case ISD::SETCC:
4007         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4008       case ISD::SELECT_CC:
4009         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4010                                N0.getOperand(3), NotCC);
4011       }
4012     }
4013   }
4014
4015   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4016   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4017       N0.getNode()->hasOneUse() &&
4018       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4019     SDValue V = N0.getOperand(0);
4020     SDLoc DL(N0);
4021     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4022                     DAG.getConstant(1, DL, V.getValueType()));
4023     AddToWorklist(V.getNode());
4024     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4025   }
4026
4027   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4028   if (isOneConstant(N1) && VT == MVT::i1 &&
4029       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4030     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4031     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4032       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4033       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4034       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4035       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4036       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4037     }
4038   }
4039   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4040   if (isAllOnesConstant(N1) &&
4041       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4042     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4043     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4044       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4045       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4046       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4047       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4048       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4049     }
4050   }
4051   // fold (xor (and x, y), y) -> (and (not x), y)
4052   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4053       N0->getOperand(1) == N1) {
4054     SDValue X = N0->getOperand(0);
4055     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4056     AddToWorklist(NotX.getNode());
4057     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4058   }
4059   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4060   if (N1C && N0.getOpcode() == ISD::XOR) {
4061     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4062       SDLoc DL(N);
4063       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4064                          DAG.getConstant(N1C->getAPIntValue() ^
4065                                          N00C->getAPIntValue(), DL, VT));
4066     }
4067     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4068       SDLoc DL(N);
4069       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4070                          DAG.getConstant(N1C->getAPIntValue() ^
4071                                          N01C->getAPIntValue(), DL, VT));
4072     }
4073   }
4074   // fold (xor x, x) -> 0
4075   if (N0 == N1)
4076     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4077
4078   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4079   // Here is a concrete example of this equivalence:
4080   // i16   x ==  14
4081   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4082   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4083   //
4084   // =>
4085   //
4086   // i16     ~1      == 0b1111111111111110
4087   // i16 rol(~1, 14) == 0b1011111111111111
4088   //
4089   // Some additional tips to help conceptualize this transform:
4090   // - Try to see the operation as placing a single zero in a value of all ones.
4091   // - There exists no value for x which would allow the result to contain zero.
4092   // - Values of x larger than the bitwidth are undefined and do not require a
4093   //   consistent result.
4094   // - Pushing the zero left requires shifting one bits in from the right.
4095   // A rotate left of ~1 is a nice way of achieving the desired result.
4096   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4097       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4098     SDLoc DL(N);
4099     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4100                        N0.getOperand(1));
4101   }
4102
4103   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4104   if (N0.getOpcode() == N1.getOpcode()) {
4105     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4106     if (Tmp.getNode()) return Tmp;
4107   }
4108
4109   // Simplify the expression using non-local knowledge.
4110   if (!VT.isVector() &&
4111       SimplifyDemandedBits(SDValue(N, 0)))
4112     return SDValue(N, 0);
4113
4114   return SDValue();
4115 }
4116
4117 /// Handle transforms common to the three shifts, when the shift amount is a
4118 /// constant.
4119 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4120   SDNode *LHS = N->getOperand(0).getNode();
4121   if (!LHS->hasOneUse()) return SDValue();
4122
4123   // We want to pull some binops through shifts, so that we have (and (shift))
4124   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4125   // thing happens with address calculations, so it's important to canonicalize
4126   // it.
4127   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4128
4129   switch (LHS->getOpcode()) {
4130   default: return SDValue();
4131   case ISD::OR:
4132   case ISD::XOR:
4133     HighBitSet = false; // We can only transform sra if the high bit is clear.
4134     break;
4135   case ISD::AND:
4136     HighBitSet = true;  // We can only transform sra if the high bit is set.
4137     break;
4138   case ISD::ADD:
4139     if (N->getOpcode() != ISD::SHL)
4140       return SDValue(); // only shl(add) not sr[al](add).
4141     HighBitSet = false; // We can only transform sra if the high bit is clear.
4142     break;
4143   }
4144
4145   // We require the RHS of the binop to be a constant and not opaque as well.
4146   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4147   if (!BinOpCst) return SDValue();
4148
4149   // FIXME: disable this unless the input to the binop is a shift by a constant.
4150   // If it is not a shift, it pessimizes some common cases like:
4151   //
4152   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4153   //    int bar(int *X, int i) { return X[i & 255]; }
4154   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4155   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4156        BinOpLHSVal->getOpcode() != ISD::SRA &&
4157        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4158       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4159     return SDValue();
4160
4161   EVT VT = N->getValueType(0);
4162
4163   // If this is a signed shift right, and the high bit is modified by the
4164   // logical operation, do not perform the transformation. The highBitSet
4165   // boolean indicates the value of the high bit of the constant which would
4166   // cause it to be modified for this operation.
4167   if (N->getOpcode() == ISD::SRA) {
4168     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4169     if (BinOpRHSSignSet != HighBitSet)
4170       return SDValue();
4171   }
4172
4173   if (!TLI.isDesirableToCommuteWithShift(LHS))
4174     return SDValue();
4175
4176   // Fold the constants, shifting the binop RHS by the shift amount.
4177   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4178                                N->getValueType(0),
4179                                LHS->getOperand(1), N->getOperand(1));
4180   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4181
4182   // Create the new shift.
4183   SDValue NewShift = DAG.getNode(N->getOpcode(),
4184                                  SDLoc(LHS->getOperand(0)),
4185                                  VT, LHS->getOperand(0), N->getOperand(1));
4186
4187   // Create the new binop.
4188   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4189 }
4190
4191 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4192   assert(N->getOpcode() == ISD::TRUNCATE);
4193   assert(N->getOperand(0).getOpcode() == ISD::AND);
4194
4195   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4196   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4197     SDValue N01 = N->getOperand(0).getOperand(1);
4198
4199     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4200       if (!N01C->isOpaque()) {
4201         EVT TruncVT = N->getValueType(0);
4202         SDValue N00 = N->getOperand(0).getOperand(0);
4203         APInt TruncC = N01C->getAPIntValue();
4204         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4205         SDLoc DL(N);
4206
4207         return DAG.getNode(ISD::AND, DL, TruncVT,
4208                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4209                            DAG.getConstant(TruncC, DL, TruncVT));
4210       }
4211     }
4212   }
4213
4214   return SDValue();
4215 }
4216
4217 SDValue DAGCombiner::visitRotate(SDNode *N) {
4218   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4219   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4220       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4221     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4222     if (NewOp1.getNode())
4223       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4224                          N->getOperand(0), NewOp1);
4225   }
4226   return SDValue();
4227 }
4228
4229 SDValue DAGCombiner::visitSHL(SDNode *N) {
4230   SDValue N0 = N->getOperand(0);
4231   SDValue N1 = N->getOperand(1);
4232   EVT VT = N0.getValueType();
4233   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4234
4235   // fold vector ops
4236   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4237   if (VT.isVector()) {
4238     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4239       return FoldedVOp;
4240
4241     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4242     // If setcc produces all-one true value then:
4243     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4244     if (N1CV && N1CV->isConstant()) {
4245       if (N0.getOpcode() == ISD::AND) {
4246         SDValue N00 = N0->getOperand(0);
4247         SDValue N01 = N0->getOperand(1);
4248         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4249
4250         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4251             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4252                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4253           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4254                                                      N01CV, N1CV))
4255             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4256         }
4257       } else {
4258         N1C = isConstOrConstSplat(N1);
4259       }
4260     }
4261   }
4262
4263   // fold (shl c1, c2) -> c1<<c2
4264   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4265   if (N0C && N1C && !N1C->isOpaque())
4266     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4267   // fold (shl 0, x) -> 0
4268   if (isNullConstant(N0))
4269     return N0;
4270   // fold (shl x, c >= size(x)) -> undef
4271   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4272     return DAG.getUNDEF(VT);
4273   // fold (shl x, 0) -> x
4274   if (N1C && N1C->isNullValue())
4275     return N0;
4276   // fold (shl undef, x) -> 0
4277   if (N0.getOpcode() == ISD::UNDEF)
4278     return DAG.getConstant(0, SDLoc(N), VT);
4279   // if (shl x, c) is known to be zero, return 0
4280   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4281                             APInt::getAllOnesValue(OpSizeInBits)))
4282     return DAG.getConstant(0, SDLoc(N), VT);
4283   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4284   if (N1.getOpcode() == ISD::TRUNCATE &&
4285       N1.getOperand(0).getOpcode() == ISD::AND) {
4286     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4287     if (NewOp1.getNode())
4288       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4289   }
4290
4291   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4292     return SDValue(N, 0);
4293
4294   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4295   if (N1C && N0.getOpcode() == ISD::SHL) {
4296     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4297       uint64_t c1 = N0C1->getZExtValue();
4298       uint64_t c2 = N1C->getZExtValue();
4299       SDLoc DL(N);
4300       if (c1 + c2 >= OpSizeInBits)
4301         return DAG.getConstant(0, DL, VT);
4302       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4303                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4304     }
4305   }
4306
4307   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4308   // For this to be valid, the second form must not preserve any of the bits
4309   // that are shifted out by the inner shift in the first form.  This means
4310   // the outer shift size must be >= the number of bits added by the ext.
4311   // As a corollary, we don't care what kind of ext it is.
4312   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4313               N0.getOpcode() == ISD::ANY_EXTEND ||
4314               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4315       N0.getOperand(0).getOpcode() == ISD::SHL) {
4316     SDValue N0Op0 = N0.getOperand(0);
4317     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4318       uint64_t c1 = N0Op0C1->getZExtValue();
4319       uint64_t c2 = N1C->getZExtValue();
4320       EVT InnerShiftVT = N0Op0.getValueType();
4321       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4322       if (c2 >= OpSizeInBits - InnerShiftSize) {
4323         SDLoc DL(N0);
4324         if (c1 + c2 >= OpSizeInBits)
4325           return DAG.getConstant(0, DL, VT);
4326         return DAG.getNode(ISD::SHL, DL, VT,
4327                            DAG.getNode(N0.getOpcode(), DL, VT,
4328                                        N0Op0->getOperand(0)),
4329                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4330       }
4331     }
4332   }
4333
4334   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4335   // Only fold this if the inner zext has no other uses to avoid increasing
4336   // the total number of instructions.
4337   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4338       N0.getOperand(0).getOpcode() == ISD::SRL) {
4339     SDValue N0Op0 = N0.getOperand(0);
4340     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4341       uint64_t c1 = N0Op0C1->getZExtValue();
4342       if (c1 < VT.getScalarSizeInBits()) {
4343         uint64_t c2 = N1C->getZExtValue();
4344         if (c1 == c2) {
4345           SDValue NewOp0 = N0.getOperand(0);
4346           EVT CountVT = NewOp0.getOperand(1).getValueType();
4347           SDLoc DL(N);
4348           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4349                                        NewOp0,
4350                                        DAG.getConstant(c2, DL, CountVT));
4351           AddToWorklist(NewSHL.getNode());
4352           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4353         }
4354       }
4355     }
4356   }
4357
4358   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4359   //                               (and (srl x, (sub c1, c2), MASK)
4360   // Only fold this if the inner shift has no other uses -- if it does, folding
4361   // this will increase the total number of instructions.
4362   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4363     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4364       uint64_t c1 = N0C1->getZExtValue();
4365       if (c1 < OpSizeInBits) {
4366         uint64_t c2 = N1C->getZExtValue();
4367         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4368         SDValue Shift;
4369         if (c2 > c1) {
4370           Mask = Mask.shl(c2 - c1);
4371           SDLoc DL(N);
4372           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4373                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4374         } else {
4375           Mask = Mask.lshr(c1 - c2);
4376           SDLoc DL(N);
4377           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4378                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4379         }
4380         SDLoc DL(N0);
4381         return DAG.getNode(ISD::AND, DL, VT, Shift,
4382                            DAG.getConstant(Mask, DL, VT));
4383       }
4384     }
4385   }
4386   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4387   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4388     unsigned BitSize = VT.getScalarSizeInBits();
4389     SDLoc DL(N);
4390     SDValue HiBitsMask =
4391       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4392                                             BitSize - N1C->getZExtValue()),
4393                       DL, VT);
4394     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4395                        HiBitsMask);
4396   }
4397
4398   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4399   // Variant of version done on multiply, except mul by a power of 2 is turned
4400   // into a shift.
4401   APInt Val;
4402   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4403       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4404        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4405     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4406     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4407     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4408   }
4409
4410   if (N1C && !N1C->isOpaque()) {
4411     SDValue NewSHL = visitShiftByConstant(N, N1C);
4412     if (NewSHL.getNode())
4413       return NewSHL;
4414   }
4415
4416   return SDValue();
4417 }
4418
4419 SDValue DAGCombiner::visitSRA(SDNode *N) {
4420   SDValue N0 = N->getOperand(0);
4421   SDValue N1 = N->getOperand(1);
4422   EVT VT = N0.getValueType();
4423   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4424
4425   // fold vector ops
4426   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4427   if (VT.isVector()) {
4428     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4429       return FoldedVOp;
4430
4431     N1C = isConstOrConstSplat(N1);
4432   }
4433
4434   // fold (sra c1, c2) -> (sra c1, c2)
4435   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4436   if (N0C && N1C && !N1C->isOpaque())
4437     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4438   // fold (sra 0, x) -> 0
4439   if (isNullConstant(N0))
4440     return N0;
4441   // fold (sra -1, x) -> -1
4442   if (isAllOnesConstant(N0))
4443     return N0;
4444   // fold (sra x, (setge c, size(x))) -> undef
4445   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4446     return DAG.getUNDEF(VT);
4447   // fold (sra x, 0) -> x
4448   if (N1C && N1C->isNullValue())
4449     return N0;
4450   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4451   // sext_inreg.
4452   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4453     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4454     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4455     if (VT.isVector())
4456       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4457                                ExtVT, VT.getVectorNumElements());
4458     if ((!LegalOperations ||
4459          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4460       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4461                          N0.getOperand(0), DAG.getValueType(ExtVT));
4462   }
4463
4464   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4465   if (N1C && N0.getOpcode() == ISD::SRA) {
4466     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4467       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4468       if (Sum >= OpSizeInBits)
4469         Sum = OpSizeInBits - 1;
4470       SDLoc DL(N);
4471       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4472                          DAG.getConstant(Sum, DL, N1.getValueType()));
4473     }
4474   }
4475
4476   // fold (sra (shl X, m), (sub result_size, n))
4477   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4478   // result_size - n != m.
4479   // If truncate is free for the target sext(shl) is likely to result in better
4480   // code.
4481   if (N0.getOpcode() == ISD::SHL && N1C) {
4482     // Get the two constanst of the shifts, CN0 = m, CN = n.
4483     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4484     if (N01C) {
4485       LLVMContext &Ctx = *DAG.getContext();
4486       // Determine what the truncate's result bitsize and type would be.
4487       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4488
4489       if (VT.isVector())
4490         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4491
4492       // Determine the residual right-shift amount.
4493       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4494
4495       // If the shift is not a no-op (in which case this should be just a sign
4496       // extend already), the truncated to type is legal, sign_extend is legal
4497       // on that type, and the truncate to that type is both legal and free,
4498       // perform the transform.
4499       if ((ShiftAmt > 0) &&
4500           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4501           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4502           TLI.isTruncateFree(VT, TruncVT)) {
4503
4504         SDLoc DL(N);
4505         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4506             getShiftAmountTy(N0.getOperand(0).getValueType()));
4507         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4508                                     N0.getOperand(0), Amt);
4509         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4510                                     Shift);
4511         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4512                            N->getValueType(0), Trunc);
4513       }
4514     }
4515   }
4516
4517   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4518   if (N1.getOpcode() == ISD::TRUNCATE &&
4519       N1.getOperand(0).getOpcode() == ISD::AND) {
4520     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4521     if (NewOp1.getNode())
4522       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4523   }
4524
4525   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4526   //      if c1 is equal to the number of bits the trunc removes
4527   if (N0.getOpcode() == ISD::TRUNCATE &&
4528       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4529        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4530       N0.getOperand(0).hasOneUse() &&
4531       N0.getOperand(0).getOperand(1).hasOneUse() &&
4532       N1C) {
4533     SDValue N0Op0 = N0.getOperand(0);
4534     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4535       unsigned LargeShiftVal = LargeShift->getZExtValue();
4536       EVT LargeVT = N0Op0.getValueType();
4537
4538       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4539         SDLoc DL(N);
4540         SDValue Amt =
4541           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4542                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4543         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4544                                   N0Op0.getOperand(0), Amt);
4545         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4546       }
4547     }
4548   }
4549
4550   // Simplify, based on bits shifted out of the LHS.
4551   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4552     return SDValue(N, 0);
4553
4554
4555   // If the sign bit is known to be zero, switch this to a SRL.
4556   if (DAG.SignBitIsZero(N0))
4557     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4558
4559   if (N1C && !N1C->isOpaque()) {
4560     SDValue NewSRA = visitShiftByConstant(N, N1C);
4561     if (NewSRA.getNode())
4562       return NewSRA;
4563   }
4564
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitSRL(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   SDValue N1 = N->getOperand(1);
4571   EVT VT = N0.getValueType();
4572   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4573
4574   // fold vector ops
4575   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4576   if (VT.isVector()) {
4577     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4578       return FoldedVOp;
4579
4580     N1C = isConstOrConstSplat(N1);
4581   }
4582
4583   // fold (srl c1, c2) -> c1 >>u c2
4584   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4585   if (N0C && N1C && !N1C->isOpaque())
4586     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4587   // fold (srl 0, x) -> 0
4588   if (isNullConstant(N0))
4589     return N0;
4590   // fold (srl x, c >= size(x)) -> undef
4591   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4592     return DAG.getUNDEF(VT);
4593   // fold (srl x, 0) -> x
4594   if (N1C && N1C->isNullValue())
4595     return N0;
4596   // if (srl x, c) is known to be zero, return 0
4597   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4598                                    APInt::getAllOnesValue(OpSizeInBits)))
4599     return DAG.getConstant(0, SDLoc(N), VT);
4600
4601   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4602   if (N1C && N0.getOpcode() == ISD::SRL) {
4603     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4604       uint64_t c1 = N01C->getZExtValue();
4605       uint64_t c2 = N1C->getZExtValue();
4606       SDLoc DL(N);
4607       if (c1 + c2 >= OpSizeInBits)
4608         return DAG.getConstant(0, DL, VT);
4609       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4610                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4611     }
4612   }
4613
4614   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4615   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4616       N0.getOperand(0).getOpcode() == ISD::SRL &&
4617       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4618     uint64_t c1 =
4619       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4620     uint64_t c2 = N1C->getZExtValue();
4621     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4622     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4623     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4624     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4625     if (c1 + OpSizeInBits == InnerShiftSize) {
4626       SDLoc DL(N0);
4627       if (c1 + c2 >= InnerShiftSize)
4628         return DAG.getConstant(0, DL, VT);
4629       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4630                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4631                                      N0.getOperand(0)->getOperand(0),
4632                                      DAG.getConstant(c1 + c2, DL,
4633                                                      ShiftCountVT)));
4634     }
4635   }
4636
4637   // fold (srl (shl x, c), c) -> (and x, cst2)
4638   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4639     unsigned BitSize = N0.getScalarValueSizeInBits();
4640     if (BitSize <= 64) {
4641       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4642       SDLoc DL(N);
4643       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4644                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4645     }
4646   }
4647
4648   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4649   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4650     // Shifting in all undef bits?
4651     EVT SmallVT = N0.getOperand(0).getValueType();
4652     unsigned BitSize = SmallVT.getScalarSizeInBits();
4653     if (N1C->getZExtValue() >= BitSize)
4654       return DAG.getUNDEF(VT);
4655
4656     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4657       uint64_t ShiftAmt = N1C->getZExtValue();
4658       SDLoc DL0(N0);
4659       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4660                                        N0.getOperand(0),
4661                           DAG.getConstant(ShiftAmt, DL0,
4662                                           getShiftAmountTy(SmallVT)));
4663       AddToWorklist(SmallShift.getNode());
4664       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4665       SDLoc DL(N);
4666       return DAG.getNode(ISD::AND, DL, VT,
4667                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4668                          DAG.getConstant(Mask, DL, VT));
4669     }
4670   }
4671
4672   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4673   // bit, which is unmodified by sra.
4674   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4675     if (N0.getOpcode() == ISD::SRA)
4676       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4677   }
4678
4679   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4680   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4681       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4682     APInt KnownZero, KnownOne;
4683     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4684
4685     // If any of the input bits are KnownOne, then the input couldn't be all
4686     // zeros, thus the result of the srl will always be zero.
4687     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4688
4689     // If all of the bits input the to ctlz node are known to be zero, then
4690     // the result of the ctlz is "32" and the result of the shift is one.
4691     APInt UnknownBits = ~KnownZero;
4692     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4693
4694     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4695     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4696       // Okay, we know that only that the single bit specified by UnknownBits
4697       // could be set on input to the CTLZ node. If this bit is set, the SRL
4698       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4699       // to an SRL/XOR pair, which is likely to simplify more.
4700       unsigned ShAmt = UnknownBits.countTrailingZeros();
4701       SDValue Op = N0.getOperand(0);
4702
4703       if (ShAmt) {
4704         SDLoc DL(N0);
4705         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4706                   DAG.getConstant(ShAmt, DL,
4707                                   getShiftAmountTy(Op.getValueType())));
4708         AddToWorklist(Op.getNode());
4709       }
4710
4711       SDLoc DL(N);
4712       return DAG.getNode(ISD::XOR, DL, VT,
4713                          Op, DAG.getConstant(1, DL, VT));
4714     }
4715   }
4716
4717   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4718   if (N1.getOpcode() == ISD::TRUNCATE &&
4719       N1.getOperand(0).getOpcode() == ISD::AND) {
4720     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4721     if (NewOp1.getNode())
4722       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4723   }
4724
4725   // fold operands of srl based on knowledge that the low bits are not
4726   // demanded.
4727   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4728     return SDValue(N, 0);
4729
4730   if (N1C && !N1C->isOpaque()) {
4731     SDValue NewSRL = visitShiftByConstant(N, N1C);
4732     if (NewSRL.getNode())
4733       return NewSRL;
4734   }
4735
4736   // Attempt to convert a srl of a load into a narrower zero-extending load.
4737   SDValue NarrowLoad = ReduceLoadWidth(N);
4738   if (NarrowLoad.getNode())
4739     return NarrowLoad;
4740
4741   // Here is a common situation. We want to optimize:
4742   //
4743   //   %a = ...
4744   //   %b = and i32 %a, 2
4745   //   %c = srl i32 %b, 1
4746   //   brcond i32 %c ...
4747   //
4748   // into
4749   //
4750   //   %a = ...
4751   //   %b = and %a, 2
4752   //   %c = setcc eq %b, 0
4753   //   brcond %c ...
4754   //
4755   // However when after the source operand of SRL is optimized into AND, the SRL
4756   // itself may not be optimized further. Look for it and add the BRCOND into
4757   // the worklist.
4758   if (N->hasOneUse()) {
4759     SDNode *Use = *N->use_begin();
4760     if (Use->getOpcode() == ISD::BRCOND)
4761       AddToWorklist(Use);
4762     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4763       // Also look pass the truncate.
4764       Use = *Use->use_begin();
4765       if (Use->getOpcode() == ISD::BRCOND)
4766         AddToWorklist(Use);
4767     }
4768   }
4769
4770   return SDValue();
4771 }
4772
4773 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4774   SDValue N0 = N->getOperand(0);
4775   EVT VT = N->getValueType(0);
4776
4777   // fold (bswap c1) -> c2
4778   if (isConstantIntBuildVectorOrConstantInt(N0))
4779     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4780   // fold (bswap (bswap x)) -> x
4781   if (N0.getOpcode() == ISD::BSWAP)
4782     return N0->getOperand(0);
4783   return SDValue();
4784 }
4785
4786 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4787   SDValue N0 = N->getOperand(0);
4788   EVT VT = N->getValueType(0);
4789
4790   // fold (ctlz c1) -> c2
4791   if (isConstantIntBuildVectorOrConstantInt(N0))
4792     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4793   return SDValue();
4794 }
4795
4796 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4797   SDValue N0 = N->getOperand(0);
4798   EVT VT = N->getValueType(0);
4799
4800   // fold (ctlz_zero_undef c1) -> c2
4801   if (isConstantIntBuildVectorOrConstantInt(N0))
4802     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4803   return SDValue();
4804 }
4805
4806 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4807   SDValue N0 = N->getOperand(0);
4808   EVT VT = N->getValueType(0);
4809
4810   // fold (cttz c1) -> c2
4811   if (isConstantIntBuildVectorOrConstantInt(N0))
4812     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4813   return SDValue();
4814 }
4815
4816 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4817   SDValue N0 = N->getOperand(0);
4818   EVT VT = N->getValueType(0);
4819
4820   // fold (cttz_zero_undef c1) -> c2
4821   if (isConstantIntBuildVectorOrConstantInt(N0))
4822     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4823   return SDValue();
4824 }
4825
4826 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4827   SDValue N0 = N->getOperand(0);
4828   EVT VT = N->getValueType(0);
4829
4830   // fold (ctpop c1) -> c2
4831   if (isConstantIntBuildVectorOrConstantInt(N0))
4832     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4833   return SDValue();
4834 }
4835
4836
4837 /// \brief Generate Min/Max node
4838 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4839                                    SDValue True, SDValue False,
4840                                    ISD::CondCode CC, const TargetLowering &TLI,
4841                                    SelectionDAG &DAG) {
4842   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4843     return SDValue();
4844
4845   switch (CC) {
4846   case ISD::SETOLT:
4847   case ISD::SETOLE:
4848   case ISD::SETLT:
4849   case ISD::SETLE:
4850   case ISD::SETULT:
4851   case ISD::SETULE: {
4852     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4853     if (TLI.isOperationLegal(Opcode, VT))
4854       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4855     return SDValue();
4856   }
4857   case ISD::SETOGT:
4858   case ISD::SETOGE:
4859   case ISD::SETGT:
4860   case ISD::SETGE:
4861   case ISD::SETUGT:
4862   case ISD::SETUGE: {
4863     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4864     if (TLI.isOperationLegal(Opcode, VT))
4865       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4866     return SDValue();
4867   }
4868   default:
4869     return SDValue();
4870   }
4871 }
4872
4873 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4874   SDValue N0 = N->getOperand(0);
4875   SDValue N1 = N->getOperand(1);
4876   SDValue N2 = N->getOperand(2);
4877   EVT VT = N->getValueType(0);
4878   EVT VT0 = N0.getValueType();
4879
4880   // fold (select C, X, X) -> X
4881   if (N1 == N2)
4882     return N1;
4883   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4884     // fold (select true, X, Y) -> X
4885     // fold (select false, X, Y) -> Y
4886     return !N0C->isNullValue() ? N1 : N2;
4887   }
4888   // fold (select C, 1, X) -> (or C, X)
4889   if (VT == MVT::i1 && isOneConstant(N1))
4890     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4891   // fold (select C, 0, 1) -> (xor C, 1)
4892   // We can't do this reliably if integer based booleans have different contents
4893   // to floating point based booleans. This is because we can't tell whether we
4894   // have an integer-based boolean or a floating-point-based boolean unless we
4895   // can find the SETCC that produced it and inspect its operands. This is
4896   // fairly easy if C is the SETCC node, but it can potentially be
4897   // undiscoverable (or not reasonably discoverable). For example, it could be
4898   // in another basic block or it could require searching a complicated
4899   // expression.
4900   if (VT.isInteger() &&
4901       (VT0 == MVT::i1 || (VT0.isInteger() &&
4902                           TLI.getBooleanContents(false, false) ==
4903                               TLI.getBooleanContents(false, true) &&
4904                           TLI.getBooleanContents(false, false) ==
4905                               TargetLowering::ZeroOrOneBooleanContent)) &&
4906       isNullConstant(N1) && isOneConstant(N2)) {
4907     SDValue XORNode;
4908     if (VT == VT0) {
4909       SDLoc DL(N);
4910       return DAG.getNode(ISD::XOR, DL, VT0,
4911                          N0, DAG.getConstant(1, DL, VT0));
4912     }
4913     SDLoc DL0(N0);
4914     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4915                           N0, DAG.getConstant(1, DL0, VT0));
4916     AddToWorklist(XORNode.getNode());
4917     if (VT.bitsGT(VT0))
4918       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4919     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4920   }
4921   // fold (select C, 0, X) -> (and (not C), X)
4922   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4923     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4924     AddToWorklist(NOTNode.getNode());
4925     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4926   }
4927   // fold (select C, X, 1) -> (or (not C), X)
4928   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4929     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4930     AddToWorklist(NOTNode.getNode());
4931     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4932   }
4933   // fold (select C, X, 0) -> (and C, X)
4934   if (VT == MVT::i1 && isNullConstant(N2))
4935     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4936   // fold (select X, X, Y) -> (or X, Y)
4937   // fold (select X, 1, Y) -> (or X, Y)
4938   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4939     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4940   // fold (select X, Y, X) -> (and X, Y)
4941   // fold (select X, Y, 0) -> (and X, Y)
4942   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4943     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4944
4945   // If we can fold this based on the true/false value, do so.
4946   if (SimplifySelectOps(N, N1, N2))
4947     return SDValue(N, 0);  // Don't revisit N.
4948
4949   // fold selects based on a setcc into other things, such as min/max/abs
4950   if (N0.getOpcode() == ISD::SETCC) {
4951     // select x, y (fcmp lt x, y) -> fminnum x, y
4952     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4953     //
4954     // This is OK if we don't care about what happens if either operand is a
4955     // NaN.
4956     //
4957
4958     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4959     // no signed zeros as well as no nans.
4960     const TargetOptions &Options = DAG.getTarget().Options;
4961     if (Options.UnsafeFPMath &&
4962         VT.isFloatingPoint() && N0.hasOneUse() &&
4963         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4964       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4965
4966       SDValue FMinMax =
4967           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4968                               N1, N2, CC, TLI, DAG);
4969       if (FMinMax)
4970         return FMinMax;
4971     }
4972
4973     if ((!LegalOperations &&
4974          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4975         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4976       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4977                          N0.getOperand(0), N0.getOperand(1),
4978                          N1, N2, N0.getOperand(2));
4979     return SimplifySelect(SDLoc(N), N0, N1, N2);
4980   }
4981
4982   if (VT0 == MVT::i1) {
4983     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4984       // select (and Cond0, Cond1), X, Y
4985       //   -> select Cond0, (select Cond1, X, Y), Y
4986       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4987         SDValue Cond0 = N0->getOperand(0);
4988         SDValue Cond1 = N0->getOperand(1);
4989         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4990                                           N1.getValueType(), Cond1, N1, N2);
4991         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4992                            InnerSelect, N2);
4993       }
4994       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4995       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4996         SDValue Cond0 = N0->getOperand(0);
4997         SDValue Cond1 = N0->getOperand(1);
4998         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4999                                           N1.getValueType(), Cond1, N1, N2);
5000         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5001                            InnerSelect);
5002       }
5003     }
5004
5005     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5006     if (N1->getOpcode() == ISD::SELECT) {
5007       SDValue N1_0 = N1->getOperand(0);
5008       SDValue N1_1 = N1->getOperand(1);
5009       SDValue N1_2 = N1->getOperand(2);
5010       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5011         // Create the actual and node if we can generate good code for it.
5012         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5013           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5014                                     N0, N1_0);
5015           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5016                              N1_1, N2);
5017         }
5018         // Otherwise see if we can optimize the "and" to a better pattern.
5019         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5020           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5021                              N1_1, N2);
5022       }
5023     }
5024     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5025     if (N2->getOpcode() == ISD::SELECT) {
5026       SDValue N2_0 = N2->getOperand(0);
5027       SDValue N2_1 = N2->getOperand(1);
5028       SDValue N2_2 = N2->getOperand(2);
5029       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5030         // Create the actual or node if we can generate good code for it.
5031         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5032           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5033                                    N0, N2_0);
5034           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5035                              N1, N2_2);
5036         }
5037         // Otherwise see if we can optimize to a better pattern.
5038         if (SDValue Combined = visitORLike(N0, N2_0, N))
5039           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5040                              N1, N2_2);
5041       }
5042     }
5043   }
5044
5045   return SDValue();
5046 }
5047
5048 static
5049 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5050   SDLoc DL(N);
5051   EVT LoVT, HiVT;
5052   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5053
5054   // Split the inputs.
5055   SDValue Lo, Hi, LL, LH, RL, RH;
5056   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5057   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5058
5059   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5060   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5061
5062   return std::make_pair(Lo, Hi);
5063 }
5064
5065 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5066 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5067 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5068   SDLoc dl(N);
5069   SDValue Cond = N->getOperand(0);
5070   SDValue LHS = N->getOperand(1);
5071   SDValue RHS = N->getOperand(2);
5072   EVT VT = N->getValueType(0);
5073   int NumElems = VT.getVectorNumElements();
5074   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5075          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5076          Cond.getOpcode() == ISD::BUILD_VECTOR);
5077
5078   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5079   // binary ones here.
5080   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5081     return SDValue();
5082
5083   // We're sure we have an even number of elements due to the
5084   // concat_vectors we have as arguments to vselect.
5085   // Skip BV elements until we find one that's not an UNDEF
5086   // After we find an UNDEF element, keep looping until we get to half the
5087   // length of the BV and see if all the non-undef nodes are the same.
5088   ConstantSDNode *BottomHalf = nullptr;
5089   for (int i = 0; i < NumElems / 2; ++i) {
5090     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5091       continue;
5092
5093     if (BottomHalf == nullptr)
5094       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5095     else if (Cond->getOperand(i).getNode() != BottomHalf)
5096       return SDValue();
5097   }
5098
5099   // Do the same for the second half of the BuildVector
5100   ConstantSDNode *TopHalf = nullptr;
5101   for (int i = NumElems / 2; i < NumElems; ++i) {
5102     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5103       continue;
5104
5105     if (TopHalf == nullptr)
5106       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5107     else if (Cond->getOperand(i).getNode() != TopHalf)
5108       return SDValue();
5109   }
5110
5111   assert(TopHalf && BottomHalf &&
5112          "One half of the selector was all UNDEFs and the other was all the "
5113          "same value. This should have been addressed before this function.");
5114   return DAG.getNode(
5115       ISD::CONCAT_VECTORS, dl, VT,
5116       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5117       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5118 }
5119
5120 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5121
5122   if (Level >= AfterLegalizeTypes)
5123     return SDValue();
5124
5125   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5126   SDValue Mask = MSC->getMask();
5127   SDValue Data  = MSC->getValue();
5128   SDLoc DL(N);
5129
5130   // If the MSCATTER data type requires splitting and the mask is provided by a
5131   // SETCC, then split both nodes and its operands before legalization. This
5132   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5133   // and enables future optimizations (e.g. min/max pattern matching on X86).
5134   if (Mask.getOpcode() != ISD::SETCC)
5135     return SDValue();
5136
5137   // Check if any splitting is required.
5138   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5139       TargetLowering::TypeSplitVector)
5140     return SDValue();
5141   SDValue MaskLo, MaskHi, Lo, Hi;
5142   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5143
5144   EVT LoVT, HiVT;
5145   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5146
5147   SDValue Chain = MSC->getChain();
5148
5149   EVT MemoryVT = MSC->getMemoryVT();
5150   unsigned Alignment = MSC->getOriginalAlignment();
5151
5152   EVT LoMemVT, HiMemVT;
5153   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5154
5155   SDValue DataLo, DataHi;
5156   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5157
5158   SDValue BasePtr = MSC->getBasePtr();
5159   SDValue IndexLo, IndexHi;
5160   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5161
5162   MachineMemOperand *MMO = DAG.getMachineFunction().
5163     getMachineMemOperand(MSC->getPointerInfo(),
5164                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5165                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5166
5167   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5168   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5169                             DL, OpsLo, MMO);
5170
5171   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5172   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5173                             DL, OpsHi, MMO);
5174
5175   AddToWorklist(Lo.getNode());
5176   AddToWorklist(Hi.getNode());
5177
5178   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5179 }
5180
5181 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5182
5183   if (Level >= AfterLegalizeTypes)
5184     return SDValue();
5185
5186   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5187   SDValue Mask = MST->getMask();
5188   SDValue Data  = MST->getValue();
5189   SDLoc DL(N);
5190
5191   // If the MSTORE data type requires splitting and the mask is provided by a
5192   // SETCC, then split both nodes and its operands before legalization. This
5193   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5194   // and enables future optimizations (e.g. min/max pattern matching on X86).
5195   if (Mask.getOpcode() == ISD::SETCC) {
5196
5197     // Check if any splitting is required.
5198     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5199         TargetLowering::TypeSplitVector)
5200       return SDValue();
5201
5202     SDValue MaskLo, MaskHi, Lo, Hi;
5203     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5204
5205     EVT LoVT, HiVT;
5206     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5207
5208     SDValue Chain = MST->getChain();
5209     SDValue Ptr   = MST->getBasePtr();
5210
5211     EVT MemoryVT = MST->getMemoryVT();
5212     unsigned Alignment = MST->getOriginalAlignment();
5213
5214     // if Alignment is equal to the vector size,
5215     // take the half of it for the second part
5216     unsigned SecondHalfAlignment =
5217       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5218          Alignment/2 : Alignment;
5219
5220     EVT LoMemVT, HiMemVT;
5221     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5222
5223     SDValue DataLo, DataHi;
5224     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5225
5226     MachineMemOperand *MMO = DAG.getMachineFunction().
5227       getMachineMemOperand(MST->getPointerInfo(),
5228                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5229                            Alignment, MST->getAAInfo(), MST->getRanges());
5230
5231     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5232                             MST->isTruncatingStore());
5233
5234     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5235     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5236                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5237
5238     MMO = DAG.getMachineFunction().
5239       getMachineMemOperand(MST->getPointerInfo(),
5240                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5241                            SecondHalfAlignment, MST->getAAInfo(),
5242                            MST->getRanges());
5243
5244     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5245                             MST->isTruncatingStore());
5246
5247     AddToWorklist(Lo.getNode());
5248     AddToWorklist(Hi.getNode());
5249
5250     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5251   }
5252   return SDValue();
5253 }
5254
5255 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5256
5257   if (Level >= AfterLegalizeTypes)
5258     return SDValue();
5259
5260   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5261   SDValue Mask = MGT->getMask();
5262   SDLoc DL(N);
5263
5264   // If the MGATHER result requires splitting and the mask is provided by a
5265   // SETCC, then split both nodes and its operands before legalization. This
5266   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5267   // and enables future optimizations (e.g. min/max pattern matching on X86).
5268
5269   if (Mask.getOpcode() != ISD::SETCC)
5270     return SDValue();
5271
5272   EVT VT = N->getValueType(0);
5273
5274   // Check if any splitting is required.
5275   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5276       TargetLowering::TypeSplitVector)
5277     return SDValue();
5278
5279   SDValue MaskLo, MaskHi, Lo, Hi;
5280   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5281
5282   SDValue Src0 = MGT->getValue();
5283   SDValue Src0Lo, Src0Hi;
5284   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5285
5286   EVT LoVT, HiVT;
5287   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5288
5289   SDValue Chain = MGT->getChain();
5290   EVT MemoryVT = MGT->getMemoryVT();
5291   unsigned Alignment = MGT->getOriginalAlignment();
5292
5293   EVT LoMemVT, HiMemVT;
5294   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5295
5296   SDValue BasePtr = MGT->getBasePtr();
5297   SDValue Index = MGT->getIndex();
5298   SDValue IndexLo, IndexHi;
5299   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5300
5301   MachineMemOperand *MMO = DAG.getMachineFunction().
5302     getMachineMemOperand(MGT->getPointerInfo(),
5303                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5304                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5305
5306   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5307   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5308                             MMO);
5309
5310   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5311   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5312                             MMO);
5313
5314   AddToWorklist(Lo.getNode());
5315   AddToWorklist(Hi.getNode());
5316
5317   // Build a factor node to remember that this load is independent of the
5318   // other one.
5319   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5320                       Hi.getValue(1));
5321
5322   // Legalized the chain result - switch anything that used the old chain to
5323   // use the new one.
5324   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5325
5326   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5327
5328   SDValue RetOps[] = { GatherRes, Chain };
5329   return DAG.getMergeValues(RetOps, DL);
5330 }
5331
5332 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5333
5334   if (Level >= AfterLegalizeTypes)
5335     return SDValue();
5336
5337   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5338   SDValue Mask = MLD->getMask();
5339   SDLoc DL(N);
5340
5341   // If the MLOAD result requires splitting and the mask is provided by a
5342   // SETCC, then split both nodes and its operands before legalization. This
5343   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5344   // and enables future optimizations (e.g. min/max pattern matching on X86).
5345
5346   if (Mask.getOpcode() == ISD::SETCC) {
5347     EVT VT = N->getValueType(0);
5348
5349     // Check if any splitting is required.
5350     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5351         TargetLowering::TypeSplitVector)
5352       return SDValue();
5353
5354     SDValue MaskLo, MaskHi, Lo, Hi;
5355     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5356
5357     SDValue Src0 = MLD->getSrc0();
5358     SDValue Src0Lo, Src0Hi;
5359     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5360
5361     EVT LoVT, HiVT;
5362     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5363
5364     SDValue Chain = MLD->getChain();
5365     SDValue Ptr   = MLD->getBasePtr();
5366     EVT MemoryVT = MLD->getMemoryVT();
5367     unsigned Alignment = MLD->getOriginalAlignment();
5368
5369     // if Alignment is equal to the vector size,
5370     // take the half of it for the second part
5371     unsigned SecondHalfAlignment =
5372       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5373          Alignment/2 : Alignment;
5374
5375     EVT LoMemVT, HiMemVT;
5376     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5377
5378     MachineMemOperand *MMO = DAG.getMachineFunction().
5379     getMachineMemOperand(MLD->getPointerInfo(),
5380                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5381                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5382
5383     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5384                            ISD::NON_EXTLOAD);
5385
5386     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5387     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5388                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5389
5390     MMO = DAG.getMachineFunction().
5391     getMachineMemOperand(MLD->getPointerInfo(),
5392                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5393                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5394
5395     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5396                            ISD::NON_EXTLOAD);
5397
5398     AddToWorklist(Lo.getNode());
5399     AddToWorklist(Hi.getNode());
5400
5401     // Build a factor node to remember that this load is independent of the
5402     // other one.
5403     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5404                         Hi.getValue(1));
5405
5406     // Legalized the chain result - switch anything that used the old chain to
5407     // use the new one.
5408     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5409
5410     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5411
5412     SDValue RetOps[] = { LoadRes, Chain };
5413     return DAG.getMergeValues(RetOps, DL);
5414   }
5415   return SDValue();
5416 }
5417
5418 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5419   SDValue N0 = N->getOperand(0);
5420   SDValue N1 = N->getOperand(1);
5421   SDValue N2 = N->getOperand(2);
5422   SDLoc DL(N);
5423
5424   // Canonicalize integer abs.
5425   // vselect (setg[te] X,  0),  X, -X ->
5426   // vselect (setgt    X, -1),  X, -X ->
5427   // vselect (setl[te] X,  0), -X,  X ->
5428   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5429   if (N0.getOpcode() == ISD::SETCC) {
5430     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5431     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5432     bool isAbs = false;
5433     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5434
5435     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5436          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5437         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5438       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5439     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5440              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5441       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5442
5443     if (isAbs) {
5444       EVT VT = LHS.getValueType();
5445       SDValue Shift = DAG.getNode(
5446           ISD::SRA, DL, VT, LHS,
5447           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5448       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5449       AddToWorklist(Shift.getNode());
5450       AddToWorklist(Add.getNode());
5451       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5452     }
5453   }
5454
5455   if (SimplifySelectOps(N, N1, N2))
5456     return SDValue(N, 0);  // Don't revisit N.
5457
5458   // If the VSELECT result requires splitting and the mask is provided by a
5459   // SETCC, then split both nodes and its operands before legalization. This
5460   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5461   // and enables future optimizations (e.g. min/max pattern matching on X86).
5462   if (N0.getOpcode() == ISD::SETCC) {
5463     EVT VT = N->getValueType(0);
5464
5465     // Check if any splitting is required.
5466     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5467         TargetLowering::TypeSplitVector)
5468       return SDValue();
5469
5470     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5471     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5472     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5473     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5474
5475     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5476     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5477
5478     // Add the new VSELECT nodes to the work list in case they need to be split
5479     // again.
5480     AddToWorklist(Lo.getNode());
5481     AddToWorklist(Hi.getNode());
5482
5483     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5484   }
5485
5486   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5487   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5488     return N1;
5489   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5490   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5491     return N2;
5492
5493   // The ConvertSelectToConcatVector function is assuming both the above
5494   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5495   // and addressed.
5496   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5497       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5498       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5499     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5500     if (CV.getNode())
5501       return CV;
5502   }
5503
5504   return SDValue();
5505 }
5506
5507 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5508   SDValue N0 = N->getOperand(0);
5509   SDValue N1 = N->getOperand(1);
5510   SDValue N2 = N->getOperand(2);
5511   SDValue N3 = N->getOperand(3);
5512   SDValue N4 = N->getOperand(4);
5513   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5514
5515   // fold select_cc lhs, rhs, x, x, cc -> x
5516   if (N2 == N3)
5517     return N2;
5518
5519   // Determine if the condition we're dealing with is constant
5520   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5521                               N0, N1, CC, SDLoc(N), false);
5522   if (SCC.getNode()) {
5523     AddToWorklist(SCC.getNode());
5524
5525     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5526       if (!SCCC->isNullValue())
5527         return N2;    // cond always true -> true val
5528       else
5529         return N3;    // cond always false -> false val
5530     } else if (SCC->getOpcode() == ISD::UNDEF) {
5531       // When the condition is UNDEF, just return the first operand. This is
5532       // coherent the DAG creation, no setcc node is created in this case
5533       return N2;
5534     } else if (SCC.getOpcode() == ISD::SETCC) {
5535       // Fold to a simpler select_cc
5536       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5537                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5538                          SCC.getOperand(2));
5539     }
5540   }
5541
5542   // If we can fold this based on the true/false value, do so.
5543   if (SimplifySelectOps(N, N2, N3))
5544     return SDValue(N, 0);  // Don't revisit N.
5545
5546   // fold select_cc into other things, such as min/max/abs
5547   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5548 }
5549
5550 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5551   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5552                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5553                        SDLoc(N));
5554 }
5555
5556 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5557 // dag node into a ConstantSDNode or a build_vector of constants.
5558 // This function is called by the DAGCombiner when visiting sext/zext/aext
5559 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5560 // Vector extends are not folded if operations are legal; this is to
5561 // avoid introducing illegal build_vector dag nodes.
5562 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5563                                          SelectionDAG &DAG, bool LegalTypes,
5564                                          bool LegalOperations) {
5565   unsigned Opcode = N->getOpcode();
5566   SDValue N0 = N->getOperand(0);
5567   EVT VT = N->getValueType(0);
5568
5569   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5570          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5571          && "Expected EXTEND dag node in input!");
5572
5573   // fold (sext c1) -> c1
5574   // fold (zext c1) -> c1
5575   // fold (aext c1) -> c1
5576   if (isa<ConstantSDNode>(N0))
5577     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5578
5579   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5580   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5581   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5582   EVT SVT = VT.getScalarType();
5583   if (!(VT.isVector() &&
5584       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5585       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5586     return nullptr;
5587
5588   // We can fold this node into a build_vector.
5589   unsigned VTBits = SVT.getSizeInBits();
5590   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5591   unsigned ShAmt = VTBits - EVTBits;
5592   SmallVector<SDValue, 8> Elts;
5593   unsigned NumElts = VT.getVectorNumElements();
5594   SDLoc DL(N);
5595
5596   for (unsigned i=0; i != NumElts; ++i) {
5597     SDValue Op = N0->getOperand(i);
5598     if (Op->getOpcode() == ISD::UNDEF) {
5599       Elts.push_back(DAG.getUNDEF(SVT));
5600       continue;
5601     }
5602
5603     SDLoc DL(Op);
5604     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5605     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5606     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5607       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5608                                      DL, SVT));
5609     else
5610       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5611                                      DL, SVT));
5612   }
5613
5614   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5615 }
5616
5617 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5618 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5619 // transformation. Returns true if extension are possible and the above
5620 // mentioned transformation is profitable.
5621 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5622                                     unsigned ExtOpc,
5623                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5624                                     const TargetLowering &TLI) {
5625   bool HasCopyToRegUses = false;
5626   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5627   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5628                             UE = N0.getNode()->use_end();
5629        UI != UE; ++UI) {
5630     SDNode *User = *UI;
5631     if (User == N)
5632       continue;
5633     if (UI.getUse().getResNo() != N0.getResNo())
5634       continue;
5635     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5636     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5637       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5638       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5639         // Sign bits will be lost after a zext.
5640         return false;
5641       bool Add = false;
5642       for (unsigned i = 0; i != 2; ++i) {
5643         SDValue UseOp = User->getOperand(i);
5644         if (UseOp == N0)
5645           continue;
5646         if (!isa<ConstantSDNode>(UseOp))
5647           return false;
5648         Add = true;
5649       }
5650       if (Add)
5651         ExtendNodes.push_back(User);
5652       continue;
5653     }
5654     // If truncates aren't free and there are users we can't
5655     // extend, it isn't worthwhile.
5656     if (!isTruncFree)
5657       return false;
5658     // Remember if this value is live-out.
5659     if (User->getOpcode() == ISD::CopyToReg)
5660       HasCopyToRegUses = true;
5661   }
5662
5663   if (HasCopyToRegUses) {
5664     bool BothLiveOut = false;
5665     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5666          UI != UE; ++UI) {
5667       SDUse &Use = UI.getUse();
5668       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5669         BothLiveOut = true;
5670         break;
5671       }
5672     }
5673     if (BothLiveOut)
5674       // Both unextended and extended values are live out. There had better be
5675       // a good reason for the transformation.
5676       return ExtendNodes.size();
5677   }
5678   return true;
5679 }
5680
5681 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5682                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5683                                   ISD::NodeType ExtType) {
5684   // Extend SetCC uses if necessary.
5685   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5686     SDNode *SetCC = SetCCs[i];
5687     SmallVector<SDValue, 4> Ops;
5688
5689     for (unsigned j = 0; j != 2; ++j) {
5690       SDValue SOp = SetCC->getOperand(j);
5691       if (SOp == Trunc)
5692         Ops.push_back(ExtLoad);
5693       else
5694         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5695     }
5696
5697     Ops.push_back(SetCC->getOperand(2));
5698     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5699   }
5700 }
5701
5702 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5703 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5704   SDValue N0 = N->getOperand(0);
5705   EVT DstVT = N->getValueType(0);
5706   EVT SrcVT = N0.getValueType();
5707
5708   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5709           N->getOpcode() == ISD::ZERO_EXTEND) &&
5710          "Unexpected node type (not an extend)!");
5711
5712   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5713   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5714   //   (v8i32 (sext (v8i16 (load x))))
5715   // into:
5716   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5717   //                          (v4i32 (sextload (x + 16)))))
5718   // Where uses of the original load, i.e.:
5719   //   (v8i16 (load x))
5720   // are replaced with:
5721   //   (v8i16 (truncate
5722   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5723   //                            (v4i32 (sextload (x + 16)))))))
5724   //
5725   // This combine is only applicable to illegal, but splittable, vectors.
5726   // All legal types, and illegal non-vector types, are handled elsewhere.
5727   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5728   //
5729   if (N0->getOpcode() != ISD::LOAD)
5730     return SDValue();
5731
5732   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5733
5734   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5735       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5736       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5737     return SDValue();
5738
5739   SmallVector<SDNode *, 4> SetCCs;
5740   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5741     return SDValue();
5742
5743   ISD::LoadExtType ExtType =
5744       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5745
5746   // Try to split the vector types to get down to legal types.
5747   EVT SplitSrcVT = SrcVT;
5748   EVT SplitDstVT = DstVT;
5749   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5750          SplitSrcVT.getVectorNumElements() > 1) {
5751     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5752     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5753   }
5754
5755   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5756     return SDValue();
5757
5758   SDLoc DL(N);
5759   const unsigned NumSplits =
5760       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5761   const unsigned Stride = SplitSrcVT.getStoreSize();
5762   SmallVector<SDValue, 4> Loads;
5763   SmallVector<SDValue, 4> Chains;
5764
5765   SDValue BasePtr = LN0->getBasePtr();
5766   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5767     const unsigned Offset = Idx * Stride;
5768     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5769
5770     SDValue SplitLoad = DAG.getExtLoad(
5771         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5772         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5773         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5774         Align, LN0->getAAInfo());
5775
5776     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5777                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5778
5779     Loads.push_back(SplitLoad.getValue(0));
5780     Chains.push_back(SplitLoad.getValue(1));
5781   }
5782
5783   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5784   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5785
5786   CombineTo(N, NewValue);
5787
5788   // Replace uses of the original load (before extension)
5789   // with a truncate of the concatenated sextloaded vectors.
5790   SDValue Trunc =
5791       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5792   CombineTo(N0.getNode(), Trunc, NewChain);
5793   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5794                   (ISD::NodeType)N->getOpcode());
5795   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5796 }
5797
5798 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5799   SDValue N0 = N->getOperand(0);
5800   EVT VT = N->getValueType(0);
5801
5802   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5803                                               LegalOperations))
5804     return SDValue(Res, 0);
5805
5806   // fold (sext (sext x)) -> (sext x)
5807   // fold (sext (aext x)) -> (sext x)
5808   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5809     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5810                        N0.getOperand(0));
5811
5812   if (N0.getOpcode() == ISD::TRUNCATE) {
5813     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5814     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5815     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5816     if (NarrowLoad.getNode()) {
5817       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5818       if (NarrowLoad.getNode() != N0.getNode()) {
5819         CombineTo(N0.getNode(), NarrowLoad);
5820         // CombineTo deleted the truncate, if needed, but not what's under it.
5821         AddToWorklist(oye);
5822       }
5823       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5824     }
5825
5826     // See if the value being truncated is already sign extended.  If so, just
5827     // eliminate the trunc/sext pair.
5828     SDValue Op = N0.getOperand(0);
5829     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5830     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5831     unsigned DestBits = VT.getScalarType().getSizeInBits();
5832     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5833
5834     if (OpBits == DestBits) {
5835       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5836       // bits, it is already ready.
5837       if (NumSignBits > DestBits-MidBits)
5838         return Op;
5839     } else if (OpBits < DestBits) {
5840       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5841       // bits, just sext from i32.
5842       if (NumSignBits > OpBits-MidBits)
5843         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5844     } else {
5845       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5846       // bits, just truncate to i32.
5847       if (NumSignBits > OpBits-MidBits)
5848         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5849     }
5850
5851     // fold (sext (truncate x)) -> (sextinreg x).
5852     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5853                                                  N0.getValueType())) {
5854       if (OpBits < DestBits)
5855         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5856       else if (OpBits > DestBits)
5857         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5858       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5859                          DAG.getValueType(N0.getValueType()));
5860     }
5861   }
5862
5863   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5864   // Only generate vector extloads when 1) they're legal, and 2) they are
5865   // deemed desirable by the target.
5866   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5867       ((!LegalOperations && !VT.isVector() &&
5868         !cast<LoadSDNode>(N0)->isVolatile()) ||
5869        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5870     bool DoXform = true;
5871     SmallVector<SDNode*, 4> SetCCs;
5872     if (!N0.hasOneUse())
5873       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5874     if (VT.isVector())
5875       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5876     if (DoXform) {
5877       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5878       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5879                                        LN0->getChain(),
5880                                        LN0->getBasePtr(), N0.getValueType(),
5881                                        LN0->getMemOperand());
5882       CombineTo(N, ExtLoad);
5883       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5884                                   N0.getValueType(), ExtLoad);
5885       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5886       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5887                       ISD::SIGN_EXTEND);
5888       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5889     }
5890   }
5891
5892   // fold (sext (load x)) to multiple smaller sextloads.
5893   // Only on illegal but splittable vectors.
5894   if (SDValue ExtLoad = CombineExtLoad(N))
5895     return ExtLoad;
5896
5897   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5898   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5899   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5900       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5901     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5902     EVT MemVT = LN0->getMemoryVT();
5903     if ((!LegalOperations && !LN0->isVolatile()) ||
5904         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5905       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5906                                        LN0->getChain(),
5907                                        LN0->getBasePtr(), MemVT,
5908                                        LN0->getMemOperand());
5909       CombineTo(N, ExtLoad);
5910       CombineTo(N0.getNode(),
5911                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5912                             N0.getValueType(), ExtLoad),
5913                 ExtLoad.getValue(1));
5914       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5915     }
5916   }
5917
5918   // fold (sext (and/or/xor (load x), cst)) ->
5919   //      (and/or/xor (sextload x), (sext cst))
5920   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5921        N0.getOpcode() == ISD::XOR) &&
5922       isa<LoadSDNode>(N0.getOperand(0)) &&
5923       N0.getOperand(1).getOpcode() == ISD::Constant &&
5924       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5925       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5926     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5927     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5928       bool DoXform = true;
5929       SmallVector<SDNode*, 4> SetCCs;
5930       if (!N0.hasOneUse())
5931         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5932                                           SetCCs, TLI);
5933       if (DoXform) {
5934         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5935                                          LN0->getChain(), LN0->getBasePtr(),
5936                                          LN0->getMemoryVT(),
5937                                          LN0->getMemOperand());
5938         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5939         Mask = Mask.sext(VT.getSizeInBits());
5940         SDLoc DL(N);
5941         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5942                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5943         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5944                                     SDLoc(N0.getOperand(0)),
5945                                     N0.getOperand(0).getValueType(), ExtLoad);
5946         CombineTo(N, And);
5947         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5948         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5949                         ISD::SIGN_EXTEND);
5950         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5951       }
5952     }
5953   }
5954
5955   if (N0.getOpcode() == ISD::SETCC) {
5956     EVT N0VT = N0.getOperand(0).getValueType();
5957     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5958     // Only do this before legalize for now.
5959     if (VT.isVector() && !LegalOperations &&
5960         TLI.getBooleanContents(N0VT) ==
5961             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5962       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5963       // of the same size as the compared operands. Only optimize sext(setcc())
5964       // if this is the case.
5965       EVT SVT = getSetCCResultType(N0VT);
5966
5967       // We know that the # elements of the results is the same as the
5968       // # elements of the compare (and the # elements of the compare result
5969       // for that matter).  Check to see that they are the same size.  If so,
5970       // we know that the element size of the sext'd result matches the
5971       // element size of the compare operands.
5972       if (VT.getSizeInBits() == SVT.getSizeInBits())
5973         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5974                              N0.getOperand(1),
5975                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5976
5977       // If the desired elements are smaller or larger than the source
5978       // elements we can use a matching integer vector type and then
5979       // truncate/sign extend
5980       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5981       if (SVT == MatchingVectorType) {
5982         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5983                                N0.getOperand(0), N0.getOperand(1),
5984                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5985         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5986       }
5987     }
5988
5989     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5990     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5991     SDLoc DL(N);
5992     SDValue NegOne =
5993       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5994     SDValue SCC =
5995       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5996                        NegOne, DAG.getConstant(0, DL, VT),
5997                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5998     if (SCC.getNode()) return SCC;
5999
6000     if (!VT.isVector()) {
6001       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6002       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6003         SDLoc DL(N);
6004         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6005         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6006                                      N0.getOperand(0), N0.getOperand(1), CC);
6007         return DAG.getSelect(DL, VT, SetCC,
6008                              NegOne, DAG.getConstant(0, DL, VT));
6009       }
6010     }
6011   }
6012
6013   // fold (sext x) -> (zext x) if the sign bit is known zero.
6014   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6015       DAG.SignBitIsZero(N0))
6016     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6017
6018   return SDValue();
6019 }
6020
6021 // isTruncateOf - If N is a truncate of some other value, return true, record
6022 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6023 // This function computes KnownZero to avoid a duplicated call to
6024 // computeKnownBits in the caller.
6025 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6026                          APInt &KnownZero) {
6027   APInt KnownOne;
6028   if (N->getOpcode() == ISD::TRUNCATE) {
6029     Op = N->getOperand(0);
6030     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6031     return true;
6032   }
6033
6034   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6035       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6036     return false;
6037
6038   SDValue Op0 = N->getOperand(0);
6039   SDValue Op1 = N->getOperand(1);
6040   assert(Op0.getValueType() == Op1.getValueType());
6041
6042   if (isNullConstant(Op0))
6043     Op = Op1;
6044   else if (isNullConstant(Op1))
6045     Op = Op0;
6046   else
6047     return false;
6048
6049   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6050
6051   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6052     return false;
6053
6054   return true;
6055 }
6056
6057 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6058   SDValue N0 = N->getOperand(0);
6059   EVT VT = N->getValueType(0);
6060
6061   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6062                                               LegalOperations))
6063     return SDValue(Res, 0);
6064
6065   // fold (zext (zext x)) -> (zext x)
6066   // fold (zext (aext x)) -> (zext x)
6067   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6068     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6069                        N0.getOperand(0));
6070
6071   // fold (zext (truncate x)) -> (zext x) or
6072   //      (zext (truncate x)) -> (truncate x)
6073   // This is valid when the truncated bits of x are already zero.
6074   // FIXME: We should extend this to work for vectors too.
6075   SDValue Op;
6076   APInt KnownZero;
6077   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6078     APInt TruncatedBits =
6079       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6080       APInt(Op.getValueSizeInBits(), 0) :
6081       APInt::getBitsSet(Op.getValueSizeInBits(),
6082                         N0.getValueSizeInBits(),
6083                         std::min(Op.getValueSizeInBits(),
6084                                  VT.getSizeInBits()));
6085     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6086       if (VT.bitsGT(Op.getValueType()))
6087         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6088       if (VT.bitsLT(Op.getValueType()))
6089         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6090
6091       return Op;
6092     }
6093   }
6094
6095   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6096   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6097   if (N0.getOpcode() == ISD::TRUNCATE) {
6098     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6099     if (NarrowLoad.getNode()) {
6100       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6101       if (NarrowLoad.getNode() != N0.getNode()) {
6102         CombineTo(N0.getNode(), NarrowLoad);
6103         // CombineTo deleted the truncate, if needed, but not what's under it.
6104         AddToWorklist(oye);
6105       }
6106       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6107     }
6108   }
6109
6110   // fold (zext (truncate x)) -> (and x, mask)
6111   if (N0.getOpcode() == ISD::TRUNCATE &&
6112       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6113
6114     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6115     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6116     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6117     if (NarrowLoad.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     SDValue Op = N0.getOperand(0);
6128     if (Op.getValueType().bitsLT(VT)) {
6129       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6130       AddToWorklist(Op.getNode());
6131     } else if (Op.getValueType().bitsGT(VT)) {
6132       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6133       AddToWorklist(Op.getNode());
6134     }
6135     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6136                                   N0.getValueType().getScalarType());
6137   }
6138
6139   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6140   // if either of the casts is not free.
6141   if (N0.getOpcode() == ISD::AND &&
6142       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6143       N0.getOperand(1).getOpcode() == ISD::Constant &&
6144       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6145                            N0.getValueType()) ||
6146        !TLI.isZExtFree(N0.getValueType(), VT))) {
6147     SDValue X = N0.getOperand(0).getOperand(0);
6148     if (X.getValueType().bitsLT(VT)) {
6149       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6150     } else if (X.getValueType().bitsGT(VT)) {
6151       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6152     }
6153     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6154     Mask = Mask.zext(VT.getSizeInBits());
6155     SDLoc DL(N);
6156     return DAG.getNode(ISD::AND, DL, VT,
6157                        X, DAG.getConstant(Mask, DL, VT));
6158   }
6159
6160   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6161   // Only generate vector extloads when 1) they're legal, and 2) they are
6162   // deemed desirable by the target.
6163   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6164       ((!LegalOperations && !VT.isVector() &&
6165         !cast<LoadSDNode>(N0)->isVolatile()) ||
6166        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6167     bool DoXform = true;
6168     SmallVector<SDNode*, 4> SetCCs;
6169     if (!N0.hasOneUse())
6170       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6171     if (VT.isVector())
6172       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6173     if (DoXform) {
6174       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6175       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6176                                        LN0->getChain(),
6177                                        LN0->getBasePtr(), N0.getValueType(),
6178                                        LN0->getMemOperand());
6179       CombineTo(N, ExtLoad);
6180       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6181                                   N0.getValueType(), ExtLoad);
6182       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6183
6184       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6185                       ISD::ZERO_EXTEND);
6186       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6187     }
6188   }
6189
6190   // fold (zext (load x)) to multiple smaller zextloads.
6191   // Only on illegal but splittable vectors.
6192   if (SDValue ExtLoad = CombineExtLoad(N))
6193     return ExtLoad;
6194
6195   // fold (zext (and/or/xor (load x), cst)) ->
6196   //      (and/or/xor (zextload x), (zext cst))
6197   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6198        N0.getOpcode() == ISD::XOR) &&
6199       isa<LoadSDNode>(N0.getOperand(0)) &&
6200       N0.getOperand(1).getOpcode() == ISD::Constant &&
6201       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6202       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6203     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6204     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6205       bool DoXform = true;
6206       SmallVector<SDNode*, 4> SetCCs;
6207       if (!N0.hasOneUse())
6208         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6209                                           SetCCs, TLI);
6210       if (DoXform) {
6211         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6212                                          LN0->getChain(), LN0->getBasePtr(),
6213                                          LN0->getMemoryVT(),
6214                                          LN0->getMemOperand());
6215         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6216         Mask = Mask.zext(VT.getSizeInBits());
6217         SDLoc DL(N);
6218         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6219                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6220         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6221                                     SDLoc(N0.getOperand(0)),
6222                                     N0.getOperand(0).getValueType(), ExtLoad);
6223         CombineTo(N, And);
6224         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6225         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6226                         ISD::ZERO_EXTEND);
6227         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6228       }
6229     }
6230   }
6231
6232   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6233   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6234   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6235       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6236     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6237     EVT MemVT = LN0->getMemoryVT();
6238     if ((!LegalOperations && !LN0->isVolatile()) ||
6239         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6240       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6241                                        LN0->getChain(),
6242                                        LN0->getBasePtr(), MemVT,
6243                                        LN0->getMemOperand());
6244       CombineTo(N, ExtLoad);
6245       CombineTo(N0.getNode(),
6246                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6247                             ExtLoad),
6248                 ExtLoad.getValue(1));
6249       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6250     }
6251   }
6252
6253   if (N0.getOpcode() == ISD::SETCC) {
6254     if (!LegalOperations && VT.isVector() &&
6255         N0.getValueType().getVectorElementType() == MVT::i1) {
6256       EVT N0VT = N0.getOperand(0).getValueType();
6257       if (getSetCCResultType(N0VT) == N0.getValueType())
6258         return SDValue();
6259
6260       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6261       // Only do this before legalize for now.
6262       EVT EltVT = VT.getVectorElementType();
6263       SDLoc DL(N);
6264       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6265                                     DAG.getConstant(1, DL, EltVT));
6266       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6267         // We know that the # elements of the results is the same as the
6268         // # elements of the compare (and the # elements of the compare result
6269         // for that matter).  Check to see that they are the same size.  If so,
6270         // we know that the element size of the sext'd result matches the
6271         // element size of the compare operands.
6272         return DAG.getNode(ISD::AND, DL, VT,
6273                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6274                                          N0.getOperand(1),
6275                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6276                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6277                                        OneOps));
6278
6279       // If the desired elements are smaller or larger than the source
6280       // elements we can use a matching integer vector type and then
6281       // truncate/sign extend
6282       EVT MatchingElementType =
6283         EVT::getIntegerVT(*DAG.getContext(),
6284                           N0VT.getScalarType().getSizeInBits());
6285       EVT MatchingVectorType =
6286         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6287                          N0VT.getVectorNumElements());
6288       SDValue VsetCC =
6289         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6290                       N0.getOperand(1),
6291                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6292       return DAG.getNode(ISD::AND, DL, VT,
6293                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6294                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6295     }
6296
6297     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6298     SDLoc DL(N);
6299     SDValue SCC =
6300       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6301                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6302                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6303     if (SCC.getNode()) return SCC;
6304   }
6305
6306   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6307   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6308       isa<ConstantSDNode>(N0.getOperand(1)) &&
6309       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6310       N0.hasOneUse()) {
6311     SDValue ShAmt = N0.getOperand(1);
6312     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6313     if (N0.getOpcode() == ISD::SHL) {
6314       SDValue InnerZExt = N0.getOperand(0);
6315       // If the original shl may be shifting out bits, do not perform this
6316       // transformation.
6317       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6318         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6319       if (ShAmtVal > KnownZeroBits)
6320         return SDValue();
6321     }
6322
6323     SDLoc DL(N);
6324
6325     // Ensure that the shift amount is wide enough for the shifted value.
6326     if (VT.getSizeInBits() >= 256)
6327       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6328
6329     return DAG.getNode(N0.getOpcode(), DL, VT,
6330                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6331                        ShAmt);
6332   }
6333
6334   return SDValue();
6335 }
6336
6337 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6338   SDValue N0 = N->getOperand(0);
6339   EVT VT = N->getValueType(0);
6340
6341   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6342                                               LegalOperations))
6343     return SDValue(Res, 0);
6344
6345   // fold (aext (aext x)) -> (aext x)
6346   // fold (aext (zext x)) -> (zext x)
6347   // fold (aext (sext x)) -> (sext x)
6348   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6349       N0.getOpcode() == ISD::ZERO_EXTEND ||
6350       N0.getOpcode() == ISD::SIGN_EXTEND)
6351     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6352
6353   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6354   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6355   if (N0.getOpcode() == ISD::TRUNCATE) {
6356     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6357     if (NarrowLoad.getNode()) {
6358       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6359       if (NarrowLoad.getNode() != N0.getNode()) {
6360         CombineTo(N0.getNode(), NarrowLoad);
6361         // CombineTo deleted the truncate, if needed, but not what's under it.
6362         AddToWorklist(oye);
6363       }
6364       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6365     }
6366   }
6367
6368   // fold (aext (truncate x))
6369   if (N0.getOpcode() == ISD::TRUNCATE) {
6370     SDValue TruncOp = N0.getOperand(0);
6371     if (TruncOp.getValueType() == VT)
6372       return TruncOp; // x iff x size == zext size.
6373     if (TruncOp.getValueType().bitsGT(VT))
6374       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6375     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6376   }
6377
6378   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6379   // if the trunc is not free.
6380   if (N0.getOpcode() == ISD::AND &&
6381       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6382       N0.getOperand(1).getOpcode() == ISD::Constant &&
6383       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6384                           N0.getValueType())) {
6385     SDValue X = N0.getOperand(0).getOperand(0);
6386     if (X.getValueType().bitsLT(VT)) {
6387       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6388     } else if (X.getValueType().bitsGT(VT)) {
6389       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6390     }
6391     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6392     Mask = Mask.zext(VT.getSizeInBits());
6393     SDLoc DL(N);
6394     return DAG.getNode(ISD::AND, DL, VT,
6395                        X, DAG.getConstant(Mask, DL, VT));
6396   }
6397
6398   // fold (aext (load x)) -> (aext (truncate (extload x)))
6399   // None of the supported targets knows how to perform load and any_ext
6400   // on vectors in one instruction.  We only perform this transformation on
6401   // scalars.
6402   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6403       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6404       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6405     bool DoXform = true;
6406     SmallVector<SDNode*, 4> SetCCs;
6407     if (!N0.hasOneUse())
6408       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6409     if (DoXform) {
6410       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6411       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6412                                        LN0->getChain(),
6413                                        LN0->getBasePtr(), N0.getValueType(),
6414                                        LN0->getMemOperand());
6415       CombineTo(N, ExtLoad);
6416       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6417                                   N0.getValueType(), ExtLoad);
6418       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6419       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6420                       ISD::ANY_EXTEND);
6421       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6422     }
6423   }
6424
6425   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6426   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6427   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6428   if (N0.getOpcode() == ISD::LOAD &&
6429       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6430       N0.hasOneUse()) {
6431     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6432     ISD::LoadExtType ExtType = LN0->getExtensionType();
6433     EVT MemVT = LN0->getMemoryVT();
6434     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6435       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6436                                        VT, LN0->getChain(), LN0->getBasePtr(),
6437                                        MemVT, LN0->getMemOperand());
6438       CombineTo(N, ExtLoad);
6439       CombineTo(N0.getNode(),
6440                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6441                             N0.getValueType(), ExtLoad),
6442                 ExtLoad.getValue(1));
6443       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6444     }
6445   }
6446
6447   if (N0.getOpcode() == ISD::SETCC) {
6448     // For vectors:
6449     // aext(setcc) -> vsetcc
6450     // aext(setcc) -> truncate(vsetcc)
6451     // aext(setcc) -> aext(vsetcc)
6452     // Only do this before legalize for now.
6453     if (VT.isVector() && !LegalOperations) {
6454       EVT N0VT = N0.getOperand(0).getValueType();
6455         // We know that the # elements of the results is the same as the
6456         // # elements of the compare (and the # elements of the compare result
6457         // for that matter).  Check to see that they are the same size.  If so,
6458         // we know that the element size of the sext'd result matches the
6459         // element size of the compare operands.
6460       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6461         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6462                              N0.getOperand(1),
6463                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6464       // If the desired elements are smaller or larger than the source
6465       // elements we can use a matching integer vector type and then
6466       // truncate/any extend
6467       else {
6468         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6469         SDValue VsetCC =
6470           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6471                         N0.getOperand(1),
6472                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6473         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6474       }
6475     }
6476
6477     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6478     SDLoc DL(N);
6479     SDValue SCC =
6480       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6481                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6482                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6483     if (SCC.getNode())
6484       return SCC;
6485   }
6486
6487   return SDValue();
6488 }
6489
6490 /// See if the specified operand can be simplified with the knowledge that only
6491 /// the bits specified by Mask are used.  If so, return the simpler operand,
6492 /// otherwise return a null SDValue.
6493 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6494   switch (V.getOpcode()) {
6495   default: break;
6496   case ISD::Constant: {
6497     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6498     assert(CV && "Const value should be ConstSDNode.");
6499     const APInt &CVal = CV->getAPIntValue();
6500     APInt NewVal = CVal & Mask;
6501     if (NewVal != CVal)
6502       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6503     break;
6504   }
6505   case ISD::OR:
6506   case ISD::XOR:
6507     // If the LHS or RHS don't contribute bits to the or, drop them.
6508     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6509       return V.getOperand(1);
6510     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6511       return V.getOperand(0);
6512     break;
6513   case ISD::SRL:
6514     // Only look at single-use SRLs.
6515     if (!V.getNode()->hasOneUse())
6516       break;
6517     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6518       // See if we can recursively simplify the LHS.
6519       unsigned Amt = RHSC->getZExtValue();
6520
6521       // Watch out for shift count overflow though.
6522       if (Amt >= Mask.getBitWidth()) break;
6523       APInt NewMask = Mask << Amt;
6524       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6525       if (SimplifyLHS.getNode())
6526         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6527                            SimplifyLHS, V.getOperand(1));
6528     }
6529   }
6530   return SDValue();
6531 }
6532
6533 /// If the result of a wider load is shifted to right of N  bits and then
6534 /// truncated to a narrower type and where N is a multiple of number of bits of
6535 /// the narrower type, transform it to a narrower load from address + N / num of
6536 /// bits of new type. If the result is to be extended, also fold the extension
6537 /// to form a extending load.
6538 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6539   unsigned Opc = N->getOpcode();
6540
6541   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6542   SDValue N0 = N->getOperand(0);
6543   EVT VT = N->getValueType(0);
6544   EVT ExtVT = VT;
6545
6546   // This transformation isn't valid for vector loads.
6547   if (VT.isVector())
6548     return SDValue();
6549
6550   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6551   // extended to VT.
6552   if (Opc == ISD::SIGN_EXTEND_INREG) {
6553     ExtType = ISD::SEXTLOAD;
6554     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6555   } else if (Opc == ISD::SRL) {
6556     // Another special-case: SRL is basically zero-extending a narrower value.
6557     ExtType = ISD::ZEXTLOAD;
6558     N0 = SDValue(N, 0);
6559     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6560     if (!N01) return SDValue();
6561     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6562                               VT.getSizeInBits() - N01->getZExtValue());
6563   }
6564   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6565     return SDValue();
6566
6567   unsigned EVTBits = ExtVT.getSizeInBits();
6568
6569   // Do not generate loads of non-round integer types since these can
6570   // be expensive (and would be wrong if the type is not byte sized).
6571   if (!ExtVT.isRound())
6572     return SDValue();
6573
6574   unsigned ShAmt = 0;
6575   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6576     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6577       ShAmt = N01->getZExtValue();
6578       // Is the shift amount a multiple of size of VT?
6579       if ((ShAmt & (EVTBits-1)) == 0) {
6580         N0 = N0.getOperand(0);
6581         // Is the load width a multiple of size of VT?
6582         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6583           return SDValue();
6584       }
6585
6586       // At this point, we must have a load or else we can't do the transform.
6587       if (!isa<LoadSDNode>(N0)) return SDValue();
6588
6589       // Because a SRL must be assumed to *need* to zero-extend the high bits
6590       // (as opposed to anyext the high bits), we can't combine the zextload
6591       // lowering of SRL and an sextload.
6592       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6593         return SDValue();
6594
6595       // If the shift amount is larger than the input type then we're not
6596       // accessing any of the loaded bytes.  If the load was a zextload/extload
6597       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6598       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6599         return SDValue();
6600     }
6601   }
6602
6603   // If the load is shifted left (and the result isn't shifted back right),
6604   // we can fold the truncate through the shift.
6605   unsigned ShLeftAmt = 0;
6606   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6607       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6608     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6609       ShLeftAmt = N01->getZExtValue();
6610       N0 = N0.getOperand(0);
6611     }
6612   }
6613
6614   // If we haven't found a load, we can't narrow it.  Don't transform one with
6615   // multiple uses, this would require adding a new load.
6616   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6617     return SDValue();
6618
6619   // Don't change the width of a volatile load.
6620   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6621   if (LN0->isVolatile())
6622     return SDValue();
6623
6624   // Verify that we are actually reducing a load width here.
6625   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6626     return SDValue();
6627
6628   // For the transform to be legal, the load must produce only two values
6629   // (the value loaded and the chain).  Don't transform a pre-increment
6630   // load, for example, which produces an extra value.  Otherwise the
6631   // transformation is not equivalent, and the downstream logic to replace
6632   // uses gets things wrong.
6633   if (LN0->getNumValues() > 2)
6634     return SDValue();
6635
6636   // If the load that we're shrinking is an extload and we're not just
6637   // discarding the extension we can't simply shrink the load. Bail.
6638   // TODO: It would be possible to merge the extensions in some cases.
6639   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6640       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6641     return SDValue();
6642
6643   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6644     return SDValue();
6645
6646   EVT PtrType = N0.getOperand(1).getValueType();
6647
6648   if (PtrType == MVT::Untyped || PtrType.isExtended())
6649     // It's not possible to generate a constant of extended or untyped type.
6650     return SDValue();
6651
6652   // For big endian targets, we need to adjust the offset to the pointer to
6653   // load the correct bytes.
6654   if (TLI.isBigEndian()) {
6655     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6656     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6657     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6658   }
6659
6660   uint64_t PtrOff = ShAmt / 8;
6661   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6662   SDLoc DL(LN0);
6663   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6664                                PtrType, LN0->getBasePtr(),
6665                                DAG.getConstant(PtrOff, DL, PtrType));
6666   AddToWorklist(NewPtr.getNode());
6667
6668   SDValue Load;
6669   if (ExtType == ISD::NON_EXTLOAD)
6670     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6671                         LN0->getPointerInfo().getWithOffset(PtrOff),
6672                         LN0->isVolatile(), LN0->isNonTemporal(),
6673                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6674   else
6675     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6676                           LN0->getPointerInfo().getWithOffset(PtrOff),
6677                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6678                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6679
6680   // Replace the old load's chain with the new load's chain.
6681   WorklistRemover DeadNodes(*this);
6682   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6683
6684   // Shift the result left, if we've swallowed a left shift.
6685   SDValue Result = Load;
6686   if (ShLeftAmt != 0) {
6687     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6688     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6689       ShImmTy = VT;
6690     // If the shift amount is as large as the result size (but, presumably,
6691     // no larger than the source) then the useful bits of the result are
6692     // zero; we can't simply return the shortened shift, because the result
6693     // of that operation is undefined.
6694     SDLoc DL(N0);
6695     if (ShLeftAmt >= VT.getSizeInBits())
6696       Result = DAG.getConstant(0, DL, VT);
6697     else
6698       Result = DAG.getNode(ISD::SHL, DL, VT,
6699                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6700   }
6701
6702   // Return the new loaded value.
6703   return Result;
6704 }
6705
6706 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6707   SDValue N0 = N->getOperand(0);
6708   SDValue N1 = N->getOperand(1);
6709   EVT VT = N->getValueType(0);
6710   EVT EVT = cast<VTSDNode>(N1)->getVT();
6711   unsigned VTBits = VT.getScalarType().getSizeInBits();
6712   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6713
6714   // fold (sext_in_reg c1) -> c1
6715   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6716     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6717
6718   // If the input is already sign extended, just drop the extension.
6719   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6720     return N0;
6721
6722   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6723   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6724       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6725     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6726                        N0.getOperand(0), N1);
6727
6728   // fold (sext_in_reg (sext x)) -> (sext x)
6729   // fold (sext_in_reg (aext x)) -> (sext x)
6730   // if x is small enough.
6731   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6732     SDValue N00 = N0.getOperand(0);
6733     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6734         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6735       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6736   }
6737
6738   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6739   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6740     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6741
6742   // fold operands of sext_in_reg based on knowledge that the top bits are not
6743   // demanded.
6744   if (SimplifyDemandedBits(SDValue(N, 0)))
6745     return SDValue(N, 0);
6746
6747   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6748   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6749   SDValue NarrowLoad = ReduceLoadWidth(N);
6750   if (NarrowLoad.getNode())
6751     return NarrowLoad;
6752
6753   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6754   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6755   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6756   if (N0.getOpcode() == ISD::SRL) {
6757     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6758       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6759         // We can turn this into an SRA iff the input to the SRL is already sign
6760         // extended enough.
6761         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6762         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6763           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6764                              N0.getOperand(0), N0.getOperand(1));
6765       }
6766   }
6767
6768   // fold (sext_inreg (extload x)) -> (sextload x)
6769   if (ISD::isEXTLoad(N0.getNode()) &&
6770       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6771       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6772       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6773        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6774     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6775     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6776                                      LN0->getChain(),
6777                                      LN0->getBasePtr(), EVT,
6778                                      LN0->getMemOperand());
6779     CombineTo(N, ExtLoad);
6780     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6781     AddToWorklist(ExtLoad.getNode());
6782     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6783   }
6784   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6785   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6786       N0.hasOneUse() &&
6787       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6788       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6789        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6790     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6791     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6792                                      LN0->getChain(),
6793                                      LN0->getBasePtr(), EVT,
6794                                      LN0->getMemOperand());
6795     CombineTo(N, ExtLoad);
6796     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6797     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6798   }
6799
6800   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6801   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6802     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6803                                        N0.getOperand(1), false);
6804     if (BSwap.getNode())
6805       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6806                          BSwap, N1);
6807   }
6808
6809   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6810   // into a build_vector.
6811   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6812     SmallVector<SDValue, 8> Elts;
6813     unsigned NumElts = N0->getNumOperands();
6814     unsigned ShAmt = VTBits - EVTBits;
6815
6816     for (unsigned i = 0; i != NumElts; ++i) {
6817       SDValue Op = N0->getOperand(i);
6818       if (Op->getOpcode() == ISD::UNDEF) {
6819         Elts.push_back(Op);
6820         continue;
6821       }
6822
6823       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6824       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6825       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6826                                      SDLoc(Op), Op.getValueType()));
6827     }
6828
6829     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6830   }
6831
6832   return SDValue();
6833 }
6834
6835 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6836   SDValue N0 = N->getOperand(0);
6837   EVT VT = N->getValueType(0);
6838
6839   if (N0.getOpcode() == ISD::UNDEF)
6840     return DAG.getUNDEF(VT);
6841
6842   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6843                                               LegalOperations))
6844     return SDValue(Res, 0);
6845
6846   return SDValue();
6847 }
6848
6849 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6850   SDValue N0 = N->getOperand(0);
6851   EVT VT = N->getValueType(0);
6852   bool isLE = TLI.isLittleEndian();
6853
6854   // noop truncate
6855   if (N0.getValueType() == N->getValueType(0))
6856     return N0;
6857   // fold (truncate c1) -> c1
6858   if (isConstantIntBuildVectorOrConstantInt(N0))
6859     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6860   // fold (truncate (truncate x)) -> (truncate x)
6861   if (N0.getOpcode() == ISD::TRUNCATE)
6862     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6863   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6864   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6865       N0.getOpcode() == ISD::SIGN_EXTEND ||
6866       N0.getOpcode() == ISD::ANY_EXTEND) {
6867     if (N0.getOperand(0).getValueType().bitsLT(VT))
6868       // if the source is smaller than the dest, we still need an extend
6869       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6870                          N0.getOperand(0));
6871     if (N0.getOperand(0).getValueType().bitsGT(VT))
6872       // if the source is larger than the dest, than we just need the truncate
6873       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6874     // if the source and dest are the same type, we can drop both the extend
6875     // and the truncate.
6876     return N0.getOperand(0);
6877   }
6878
6879   // Fold extract-and-trunc into a narrow extract. For example:
6880   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6881   //   i32 y = TRUNCATE(i64 x)
6882   //        -- becomes --
6883   //   v16i8 b = BITCAST (v2i64 val)
6884   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6885   //
6886   // Note: We only run this optimization after type legalization (which often
6887   // creates this pattern) and before operation legalization after which
6888   // we need to be more careful about the vector instructions that we generate.
6889   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6890       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6891
6892     EVT VecTy = N0.getOperand(0).getValueType();
6893     EVT ExTy = N0.getValueType();
6894     EVT TrTy = N->getValueType(0);
6895
6896     unsigned NumElem = VecTy.getVectorNumElements();
6897     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6898
6899     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6900     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6901
6902     SDValue EltNo = N0->getOperand(1);
6903     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6904       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6905       EVT IndexTy = TLI.getVectorIdxTy();
6906       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6907
6908       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6909                               NVT, N0.getOperand(0));
6910
6911       SDLoc DL(N);
6912       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6913                          DL, TrTy, V,
6914                          DAG.getConstant(Index, DL, IndexTy));
6915     }
6916   }
6917
6918   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6919   if (N0.getOpcode() == ISD::SELECT) {
6920     EVT SrcVT = N0.getValueType();
6921     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6922         TLI.isTruncateFree(SrcVT, VT)) {
6923       SDLoc SL(N0);
6924       SDValue Cond = N0.getOperand(0);
6925       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6926       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6927       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6928     }
6929   }
6930
6931   // Fold a series of buildvector, bitcast, and truncate if possible.
6932   // For example fold
6933   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6934   //   (2xi32 (buildvector x, y)).
6935   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6936       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6937       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6938       N0.getOperand(0).hasOneUse()) {
6939
6940     SDValue BuildVect = N0.getOperand(0);
6941     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6942     EVT TruncVecEltTy = VT.getVectorElementType();
6943
6944     // Check that the element types match.
6945     if (BuildVectEltTy == TruncVecEltTy) {
6946       // Now we only need to compute the offset of the truncated elements.
6947       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6948       unsigned TruncVecNumElts = VT.getVectorNumElements();
6949       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6950
6951       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6952              "Invalid number of elements");
6953
6954       SmallVector<SDValue, 8> Opnds;
6955       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6956         Opnds.push_back(BuildVect.getOperand(i));
6957
6958       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6959     }
6960   }
6961
6962   // See if we can simplify the input to this truncate through knowledge that
6963   // only the low bits are being used.
6964   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6965   // Currently we only perform this optimization on scalars because vectors
6966   // may have different active low bits.
6967   if (!VT.isVector()) {
6968     SDValue Shorter =
6969       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6970                                                VT.getSizeInBits()));
6971     if (Shorter.getNode())
6972       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6973   }
6974   // fold (truncate (load x)) -> (smaller load x)
6975   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6976   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6977     SDValue Reduced = ReduceLoadWidth(N);
6978     if (Reduced.getNode())
6979       return Reduced;
6980     // Handle the case where the load remains an extending load even
6981     // after truncation.
6982     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6983       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6984       if (!LN0->isVolatile() &&
6985           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6986         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6987                                          VT, LN0->getChain(), LN0->getBasePtr(),
6988                                          LN0->getMemoryVT(),
6989                                          LN0->getMemOperand());
6990         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6991         return NewLoad;
6992       }
6993     }
6994   }
6995   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6996   // where ... are all 'undef'.
6997   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6998     SmallVector<EVT, 8> VTs;
6999     SDValue V;
7000     unsigned Idx = 0;
7001     unsigned NumDefs = 0;
7002
7003     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7004       SDValue X = N0.getOperand(i);
7005       if (X.getOpcode() != ISD::UNDEF) {
7006         V = X;
7007         Idx = i;
7008         NumDefs++;
7009       }
7010       // Stop if more than one members are non-undef.
7011       if (NumDefs > 1)
7012         break;
7013       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7014                                      VT.getVectorElementType(),
7015                                      X.getValueType().getVectorNumElements()));
7016     }
7017
7018     if (NumDefs == 0)
7019       return DAG.getUNDEF(VT);
7020
7021     if (NumDefs == 1) {
7022       assert(V.getNode() && "The single defined operand is empty!");
7023       SmallVector<SDValue, 8> Opnds;
7024       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7025         if (i != Idx) {
7026           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7027           continue;
7028         }
7029         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7030         AddToWorklist(NV.getNode());
7031         Opnds.push_back(NV);
7032       }
7033       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7034     }
7035   }
7036
7037   // Simplify the operands using demanded-bits information.
7038   if (!VT.isVector() &&
7039       SimplifyDemandedBits(SDValue(N, 0)))
7040     return SDValue(N, 0);
7041
7042   return SDValue();
7043 }
7044
7045 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7046   SDValue Elt = N->getOperand(i);
7047   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7048     return Elt.getNode();
7049   return Elt.getOperand(Elt.getResNo()).getNode();
7050 }
7051
7052 /// build_pair (load, load) -> load
7053 /// if load locations are consecutive.
7054 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7055   assert(N->getOpcode() == ISD::BUILD_PAIR);
7056
7057   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7058   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7059   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7060       LD1->getAddressSpace() != LD2->getAddressSpace())
7061     return SDValue();
7062   EVT LD1VT = LD1->getValueType(0);
7063
7064   if (ISD::isNON_EXTLoad(LD2) &&
7065       LD2->hasOneUse() &&
7066       // If both are volatile this would reduce the number of volatile loads.
7067       // If one is volatile it might be ok, but play conservative and bail out.
7068       !LD1->isVolatile() &&
7069       !LD2->isVolatile() &&
7070       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7071     unsigned Align = LD1->getAlignment();
7072     unsigned NewAlign = TLI.getDataLayout()->
7073       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7074
7075     if (NewAlign <= Align &&
7076         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7077       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7078                          LD1->getBasePtr(), LD1->getPointerInfo(),
7079                          false, false, false, Align);
7080   }
7081
7082   return SDValue();
7083 }
7084
7085 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7086   SDValue N0 = N->getOperand(0);
7087   EVT VT = N->getValueType(0);
7088
7089   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7090   // Only do this before legalize, since afterward the target may be depending
7091   // on the bitconvert.
7092   // First check to see if this is all constant.
7093   if (!LegalTypes &&
7094       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7095       VT.isVector()) {
7096     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7097
7098     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7099     assert(!DestEltVT.isVector() &&
7100            "Element type of vector ValueType must not be vector!");
7101     if (isSimple)
7102       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7103   }
7104
7105   // If the input is a constant, let getNode fold it.
7106   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7107     // If we can't allow illegal operations, we need to check that this is just
7108     // a fp -> int or int -> conversion and that the resulting operation will
7109     // be legal.
7110     if (!LegalOperations ||
7111         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7112          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7113         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7114          TLI.isOperationLegal(ISD::Constant, VT)))
7115       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7116   }
7117
7118   // (conv (conv x, t1), t2) -> (conv x, t2)
7119   if (N0.getOpcode() == ISD::BITCAST)
7120     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7121                        N0.getOperand(0));
7122
7123   // fold (conv (load x)) -> (load (conv*)x)
7124   // If the resultant load doesn't need a higher alignment than the original!
7125   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7126       // Do not change the width of a volatile load.
7127       !cast<LoadSDNode>(N0)->isVolatile() &&
7128       // Do not remove the cast if the types differ in endian layout.
7129       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7130       TLI.hasBigEndianPartOrdering(VT) &&
7131       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7132       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7133     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7134     unsigned Align = TLI.getDataLayout()->
7135       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7136     unsigned OrigAlign = LN0->getAlignment();
7137
7138     if (Align <= OrigAlign) {
7139       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7140                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7141                                  LN0->isVolatile(), LN0->isNonTemporal(),
7142                                  LN0->isInvariant(), OrigAlign,
7143                                  LN0->getAAInfo());
7144       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7145       return Load;
7146     }
7147   }
7148
7149   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7150   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7151   // This often reduces constant pool loads.
7152   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7153        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7154       N0.getNode()->hasOneUse() && VT.isInteger() &&
7155       !VT.isVector() && !N0.getValueType().isVector()) {
7156     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7157                                   N0.getOperand(0));
7158     AddToWorklist(NewConv.getNode());
7159
7160     SDLoc DL(N);
7161     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7162     if (N0.getOpcode() == ISD::FNEG)
7163       return DAG.getNode(ISD::XOR, DL, VT,
7164                          NewConv, DAG.getConstant(SignBit, DL, VT));
7165     assert(N0.getOpcode() == ISD::FABS);
7166     return DAG.getNode(ISD::AND, DL, VT,
7167                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7168   }
7169
7170   // fold (bitconvert (fcopysign cst, x)) ->
7171   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7172   // Note that we don't handle (copysign x, cst) because this can always be
7173   // folded to an fneg or fabs.
7174   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7175       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7176       VT.isInteger() && !VT.isVector()) {
7177     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7178     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7179     if (isTypeLegal(IntXVT)) {
7180       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7181                               IntXVT, N0.getOperand(1));
7182       AddToWorklist(X.getNode());
7183
7184       // If X has a different width than the result/lhs, sext it or truncate it.
7185       unsigned VTWidth = VT.getSizeInBits();
7186       if (OrigXWidth < VTWidth) {
7187         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7188         AddToWorklist(X.getNode());
7189       } else if (OrigXWidth > VTWidth) {
7190         // To get the sign bit in the right place, we have to shift it right
7191         // before truncating.
7192         SDLoc DL(X);
7193         X = DAG.getNode(ISD::SRL, DL,
7194                         X.getValueType(), X,
7195                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7196                                         X.getValueType()));
7197         AddToWorklist(X.getNode());
7198         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7199         AddToWorklist(X.getNode());
7200       }
7201
7202       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7203       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7204                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7205       AddToWorklist(X.getNode());
7206
7207       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7208                                 VT, N0.getOperand(0));
7209       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7210                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7211       AddToWorklist(Cst.getNode());
7212
7213       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7214     }
7215   }
7216
7217   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7218   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7219     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7220     if (CombineLD.getNode())
7221       return CombineLD;
7222   }
7223
7224   // Remove double bitcasts from shuffles - this is often a legacy of
7225   // XformToShuffleWithZero being used to combine bitmaskings (of
7226   // float vectors bitcast to integer vectors) into shuffles.
7227   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7228   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7229       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7230       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7231       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7232     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7233
7234     // If operands are a bitcast, peek through if it casts the original VT.
7235     // If operands are a UNDEF or constant, just bitcast back to original VT.
7236     auto PeekThroughBitcast = [&](SDValue Op) {
7237       if (Op.getOpcode() == ISD::BITCAST &&
7238           Op.getOperand(0)->getValueType(0) == VT)
7239         return SDValue(Op.getOperand(0));
7240       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7241           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7242         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7243       return SDValue();
7244     };
7245
7246     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7247     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7248     if (!(SV0 && SV1))
7249       return SDValue();
7250
7251     int MaskScale =
7252         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7253     SmallVector<int, 8> NewMask;
7254     for (int M : SVN->getMask())
7255       for (int i = 0; i != MaskScale; ++i)
7256         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7257
7258     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7259     if (!LegalMask) {
7260       std::swap(SV0, SV1);
7261       ShuffleVectorSDNode::commuteMask(NewMask);
7262       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7263     }
7264
7265     if (LegalMask)
7266       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7267   }
7268
7269   return SDValue();
7270 }
7271
7272 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7273   EVT VT = N->getValueType(0);
7274   return CombineConsecutiveLoads(N, VT);
7275 }
7276
7277 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7278 /// operands. DstEltVT indicates the destination element value type.
7279 SDValue DAGCombiner::
7280 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7281   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7282
7283   // If this is already the right type, we're done.
7284   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7285
7286   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7287   unsigned DstBitSize = DstEltVT.getSizeInBits();
7288
7289   // If this is a conversion of N elements of one type to N elements of another
7290   // type, convert each element.  This handles FP<->INT cases.
7291   if (SrcBitSize == DstBitSize) {
7292     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7293                               BV->getValueType(0).getVectorNumElements());
7294
7295     // Due to the FP element handling below calling this routine recursively,
7296     // we can end up with a scalar-to-vector node here.
7297     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7298       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7299                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7300                                      DstEltVT, BV->getOperand(0)));
7301
7302     SmallVector<SDValue, 8> Ops;
7303     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7304       SDValue Op = BV->getOperand(i);
7305       // If the vector element type is not legal, the BUILD_VECTOR operands
7306       // are promoted and implicitly truncated.  Make that explicit here.
7307       if (Op.getValueType() != SrcEltVT)
7308         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7309       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7310                                 DstEltVT, Op));
7311       AddToWorklist(Ops.back().getNode());
7312     }
7313     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7314   }
7315
7316   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7317   // handle annoying details of growing/shrinking FP values, we convert them to
7318   // int first.
7319   if (SrcEltVT.isFloatingPoint()) {
7320     // Convert the input float vector to a int vector where the elements are the
7321     // same sizes.
7322     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7323     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7324     SrcEltVT = IntVT;
7325   }
7326
7327   // Now we know the input is an integer vector.  If the output is a FP type,
7328   // convert to integer first, then to FP of the right size.
7329   if (DstEltVT.isFloatingPoint()) {
7330     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7331     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7332
7333     // Next, convert to FP elements of the same size.
7334     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7335   }
7336
7337   SDLoc DL(BV);
7338
7339   // Okay, we know the src/dst types are both integers of differing types.
7340   // Handling growing first.
7341   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7342   if (SrcBitSize < DstBitSize) {
7343     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7344
7345     SmallVector<SDValue, 8> Ops;
7346     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7347          i += NumInputsPerOutput) {
7348       bool isLE = TLI.isLittleEndian();
7349       APInt NewBits = APInt(DstBitSize, 0);
7350       bool EltIsUndef = true;
7351       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7352         // Shift the previously computed bits over.
7353         NewBits <<= SrcBitSize;
7354         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7355         if (Op.getOpcode() == ISD::UNDEF) continue;
7356         EltIsUndef = false;
7357
7358         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7359                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7360       }
7361
7362       if (EltIsUndef)
7363         Ops.push_back(DAG.getUNDEF(DstEltVT));
7364       else
7365         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7366     }
7367
7368     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7369     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7370   }
7371
7372   // Finally, this must be the case where we are shrinking elements: each input
7373   // turns into multiple outputs.
7374   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7375   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7376                             NumOutputsPerInput*BV->getNumOperands());
7377   SmallVector<SDValue, 8> Ops;
7378
7379   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7380     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7381       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7382       continue;
7383     }
7384
7385     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7386                   getAPIntValue().zextOrTrunc(SrcBitSize);
7387
7388     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7389       APInt ThisVal = OpVal.trunc(DstBitSize);
7390       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7391       OpVal = OpVal.lshr(DstBitSize);
7392     }
7393
7394     // For big endian targets, swap the order of the pieces of each element.
7395     if (TLI.isBigEndian())
7396       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7397   }
7398
7399   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7400 }
7401
7402 /// Try to perform FMA combining on a given FADD node.
7403 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7404   SDValue N0 = N->getOperand(0);
7405   SDValue N1 = N->getOperand(1);
7406   EVT VT = N->getValueType(0);
7407   SDLoc SL(N);
7408
7409   const TargetOptions &Options = DAG.getTarget().Options;
7410   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7411                        Options.UnsafeFPMath);
7412
7413   // Floating-point multiply-add with intermediate rounding.
7414   bool HasFMAD = (LegalOperations &&
7415                   TLI.isOperationLegal(ISD::FMAD, VT));
7416
7417   // Floating-point multiply-add without intermediate rounding.
7418   bool HasFMA = ((!LegalOperations ||
7419                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7420                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7421                  UnsafeFPMath);
7422
7423   // No valid opcode, do not combine.
7424   if (!HasFMAD && !HasFMA)
7425     return SDValue();
7426
7427   // Always prefer FMAD to FMA for precision.
7428   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7429   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7430   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7431
7432   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7433   if (N0.getOpcode() == ISD::FMUL &&
7434       (Aggressive || N0->hasOneUse())) {
7435     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7436                        N0.getOperand(0), N0.getOperand(1), N1);
7437   }
7438
7439   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7440   // Note: Commutes FADD operands.
7441   if (N1.getOpcode() == ISD::FMUL &&
7442       (Aggressive || N1->hasOneUse())) {
7443     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7444                        N1.getOperand(0), N1.getOperand(1), N0);
7445   }
7446
7447   // Look through FP_EXTEND nodes to do more combining.
7448   if (UnsafeFPMath && LookThroughFPExt) {
7449     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7450     if (N0.getOpcode() == ISD::FP_EXTEND) {
7451       SDValue N00 = N0.getOperand(0);
7452       if (N00.getOpcode() == ISD::FMUL)
7453         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7454                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7455                                        N00.getOperand(0)),
7456                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7457                                        N00.getOperand(1)), N1);
7458     }
7459
7460     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7461     // Note: Commutes FADD operands.
7462     if (N1.getOpcode() == ISD::FP_EXTEND) {
7463       SDValue N10 = N1.getOperand(0);
7464       if (N10.getOpcode() == ISD::FMUL)
7465         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7466                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7467                                        N10.getOperand(0)),
7468                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7469                                        N10.getOperand(1)), N0);
7470     }
7471   }
7472
7473   // More folding opportunities when target permits.
7474   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7475     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7476     if (N0.getOpcode() == PreferredFusedOpcode &&
7477         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7478       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7479                          N0.getOperand(0), N0.getOperand(1),
7480                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7481                                      N0.getOperand(2).getOperand(0),
7482                                      N0.getOperand(2).getOperand(1),
7483                                      N1));
7484     }
7485
7486     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7487     if (N1->getOpcode() == PreferredFusedOpcode &&
7488         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7489       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7490                          N1.getOperand(0), N1.getOperand(1),
7491                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7492                                      N1.getOperand(2).getOperand(0),
7493                                      N1.getOperand(2).getOperand(1),
7494                                      N0));
7495     }
7496
7497     if (UnsafeFPMath && LookThroughFPExt) {
7498       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7499       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7500       auto FoldFAddFMAFPExtFMul = [&] (
7501           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7502         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7503                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7504                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7505                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7506                                        Z));
7507       };
7508       if (N0.getOpcode() == PreferredFusedOpcode) {
7509         SDValue N02 = N0.getOperand(2);
7510         if (N02.getOpcode() == ISD::FP_EXTEND) {
7511           SDValue N020 = N02.getOperand(0);
7512           if (N020.getOpcode() == ISD::FMUL)
7513             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7514                                         N020.getOperand(0), N020.getOperand(1),
7515                                         N1);
7516         }
7517       }
7518
7519       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7520       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7521       // FIXME: This turns two single-precision and one double-precision
7522       // operation into two double-precision operations, which might not be
7523       // interesting for all targets, especially GPUs.
7524       auto FoldFAddFPExtFMAFMul = [&] (
7525           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7526         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7527                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7528                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7529                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7530                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7531                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7532                                        Z));
7533       };
7534       if (N0.getOpcode() == ISD::FP_EXTEND) {
7535         SDValue N00 = N0.getOperand(0);
7536         if (N00.getOpcode() == PreferredFusedOpcode) {
7537           SDValue N002 = N00.getOperand(2);
7538           if (N002.getOpcode() == ISD::FMUL)
7539             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7540                                         N002.getOperand(0), N002.getOperand(1),
7541                                         N1);
7542         }
7543       }
7544
7545       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7546       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7547       if (N1.getOpcode() == PreferredFusedOpcode) {
7548         SDValue N12 = N1.getOperand(2);
7549         if (N12.getOpcode() == ISD::FP_EXTEND) {
7550           SDValue N120 = N12.getOperand(0);
7551           if (N120.getOpcode() == ISD::FMUL)
7552             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7553                                         N120.getOperand(0), N120.getOperand(1),
7554                                         N0);
7555         }
7556       }
7557
7558       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7559       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7560       // FIXME: This turns two single-precision and one double-precision
7561       // operation into two double-precision operations, which might not be
7562       // interesting for all targets, especially GPUs.
7563       if (N1.getOpcode() == ISD::FP_EXTEND) {
7564         SDValue N10 = N1.getOperand(0);
7565         if (N10.getOpcode() == PreferredFusedOpcode) {
7566           SDValue N102 = N10.getOperand(2);
7567           if (N102.getOpcode() == ISD::FMUL)
7568             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7569                                         N102.getOperand(0), N102.getOperand(1),
7570                                         N0);
7571         }
7572       }
7573     }
7574   }
7575
7576   return SDValue();
7577 }
7578
7579 /// Try to perform FMA combining on a given FSUB node.
7580 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7581   SDValue N0 = N->getOperand(0);
7582   SDValue N1 = N->getOperand(1);
7583   EVT VT = N->getValueType(0);
7584   SDLoc SL(N);
7585
7586   const TargetOptions &Options = DAG.getTarget().Options;
7587   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7588                        Options.UnsafeFPMath);
7589
7590   // Floating-point multiply-add with intermediate rounding.
7591   bool HasFMAD = (LegalOperations &&
7592                   TLI.isOperationLegal(ISD::FMAD, VT));
7593
7594   // Floating-point multiply-add without intermediate rounding.
7595   bool HasFMA = ((!LegalOperations ||
7596                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7597                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7598                  UnsafeFPMath);
7599
7600   // No valid opcode, do not combine.
7601   if (!HasFMAD && !HasFMA)
7602     return SDValue();
7603
7604   // Always prefer FMAD to FMA for precision.
7605   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7606   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7607   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7608
7609   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7610   if (N0.getOpcode() == ISD::FMUL &&
7611       (Aggressive || N0->hasOneUse())) {
7612     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7613                        N0.getOperand(0), N0.getOperand(1),
7614                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7615   }
7616
7617   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7618   // Note: Commutes FSUB operands.
7619   if (N1.getOpcode() == ISD::FMUL &&
7620       (Aggressive || N1->hasOneUse()))
7621     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7622                        DAG.getNode(ISD::FNEG, SL, VT,
7623                                    N1.getOperand(0)),
7624                        N1.getOperand(1), N0);
7625
7626   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7627   if (N0.getOpcode() == ISD::FNEG &&
7628       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7629       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7630     SDValue N00 = N0.getOperand(0).getOperand(0);
7631     SDValue N01 = N0.getOperand(0).getOperand(1);
7632     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7633                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7634                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7635   }
7636
7637   // Look through FP_EXTEND nodes to do more combining.
7638   if (UnsafeFPMath && LookThroughFPExt) {
7639     // fold (fsub (fpext (fmul x, y)), z)
7640     //   -> (fma (fpext x), (fpext y), (fneg z))
7641     if (N0.getOpcode() == ISD::FP_EXTEND) {
7642       SDValue N00 = N0.getOperand(0);
7643       if (N00.getOpcode() == ISD::FMUL)
7644         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7645                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7646                                        N00.getOperand(0)),
7647                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7648                                        N00.getOperand(1)),
7649                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7650     }
7651
7652     // fold (fsub x, (fpext (fmul y, z)))
7653     //   -> (fma (fneg (fpext y)), (fpext z), x)
7654     // Note: Commutes FSUB operands.
7655     if (N1.getOpcode() == ISD::FP_EXTEND) {
7656       SDValue N10 = N1.getOperand(0);
7657       if (N10.getOpcode() == ISD::FMUL)
7658         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7659                            DAG.getNode(ISD::FNEG, SL, VT,
7660                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7661                                                    N10.getOperand(0))),
7662                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7663                                        N10.getOperand(1)),
7664                            N0);
7665     }
7666
7667     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7668     //   -> (fneg (fma (fpext x), (fpext y), z))
7669     // Note: This could be removed with appropriate canonicalization of the
7670     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7671     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7672     // from implementing the canonicalization in visitFSUB.
7673     if (N0.getOpcode() == ISD::FP_EXTEND) {
7674       SDValue N00 = N0.getOperand(0);
7675       if (N00.getOpcode() == ISD::FNEG) {
7676         SDValue N000 = N00.getOperand(0);
7677         if (N000.getOpcode() == ISD::FMUL) {
7678           return DAG.getNode(ISD::FNEG, SL, VT,
7679                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7680                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7681                                                      N000.getOperand(0)),
7682                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7683                                                      N000.getOperand(1)),
7684                                          N1));
7685         }
7686       }
7687     }
7688
7689     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7690     //   -> (fneg (fma (fpext x)), (fpext y), z)
7691     // Note: This could be removed with appropriate canonicalization of the
7692     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7693     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7694     // from implementing the canonicalization in visitFSUB.
7695     if (N0.getOpcode() == ISD::FNEG) {
7696       SDValue N00 = N0.getOperand(0);
7697       if (N00.getOpcode() == ISD::FP_EXTEND) {
7698         SDValue N000 = N00.getOperand(0);
7699         if (N000.getOpcode() == ISD::FMUL) {
7700           return DAG.getNode(ISD::FNEG, SL, VT,
7701                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7702                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7703                                                      N000.getOperand(0)),
7704                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7705                                                      N000.getOperand(1)),
7706                                          N1));
7707         }
7708       }
7709     }
7710
7711   }
7712
7713   // More folding opportunities when target permits.
7714   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7715     // fold (fsub (fma x, y, (fmul u, v)), z)
7716     //   -> (fma x, y (fma u, v, (fneg z)))
7717     if (N0.getOpcode() == PreferredFusedOpcode &&
7718         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7719       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7720                          N0.getOperand(0), N0.getOperand(1),
7721                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7722                                      N0.getOperand(2).getOperand(0),
7723                                      N0.getOperand(2).getOperand(1),
7724                                      DAG.getNode(ISD::FNEG, SL, VT,
7725                                                  N1)));
7726     }
7727
7728     // fold (fsub x, (fma y, z, (fmul u, v)))
7729     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7730     if (N1.getOpcode() == PreferredFusedOpcode &&
7731         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7732       SDValue N20 = N1.getOperand(2).getOperand(0);
7733       SDValue N21 = N1.getOperand(2).getOperand(1);
7734       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7735                          DAG.getNode(ISD::FNEG, SL, VT,
7736                                      N1.getOperand(0)),
7737                          N1.getOperand(1),
7738                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7739                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7740
7741                                      N21, N0));
7742     }
7743
7744     if (UnsafeFPMath && LookThroughFPExt) {
7745       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7746       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7747       if (N0.getOpcode() == PreferredFusedOpcode) {
7748         SDValue N02 = N0.getOperand(2);
7749         if (N02.getOpcode() == ISD::FP_EXTEND) {
7750           SDValue N020 = N02.getOperand(0);
7751           if (N020.getOpcode() == ISD::FMUL)
7752             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7753                                N0.getOperand(0), N0.getOperand(1),
7754                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7755                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7756                                                        N020.getOperand(0)),
7757                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7758                                                        N020.getOperand(1)),
7759                                            DAG.getNode(ISD::FNEG, SL, VT,
7760                                                        N1)));
7761         }
7762       }
7763
7764       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7765       //   -> (fma (fpext x), (fpext y),
7766       //           (fma (fpext u), (fpext v), (fneg z)))
7767       // FIXME: This turns two single-precision and one double-precision
7768       // operation into two double-precision operations, which might not be
7769       // interesting for all targets, especially GPUs.
7770       if (N0.getOpcode() == ISD::FP_EXTEND) {
7771         SDValue N00 = N0.getOperand(0);
7772         if (N00.getOpcode() == PreferredFusedOpcode) {
7773           SDValue N002 = N00.getOperand(2);
7774           if (N002.getOpcode() == ISD::FMUL)
7775             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7776                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777                                            N00.getOperand(0)),
7778                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                            N00.getOperand(1)),
7780                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7781                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782                                                        N002.getOperand(0)),
7783                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784                                                        N002.getOperand(1)),
7785                                            DAG.getNode(ISD::FNEG, SL, VT,
7786                                                        N1)));
7787         }
7788       }
7789
7790       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7791       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7792       if (N1.getOpcode() == PreferredFusedOpcode &&
7793         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7794         SDValue N120 = N1.getOperand(2).getOperand(0);
7795         if (N120.getOpcode() == ISD::FMUL) {
7796           SDValue N1200 = N120.getOperand(0);
7797           SDValue N1201 = N120.getOperand(1);
7798           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7799                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7800                              N1.getOperand(1),
7801                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                                          DAG.getNode(ISD::FNEG, SL, VT,
7803                                              DAG.getNode(ISD::FP_EXTEND, SL,
7804                                                          VT, N1200)),
7805                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7806                                                      N1201),
7807                                          N0));
7808         }
7809       }
7810
7811       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7812       //   -> (fma (fneg (fpext y)), (fpext z),
7813       //           (fma (fneg (fpext u)), (fpext v), x))
7814       // FIXME: This turns two single-precision and one double-precision
7815       // operation into two double-precision operations, which might not be
7816       // interesting for all targets, especially GPUs.
7817       if (N1.getOpcode() == ISD::FP_EXTEND &&
7818         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7819         SDValue N100 = N1.getOperand(0).getOperand(0);
7820         SDValue N101 = N1.getOperand(0).getOperand(1);
7821         SDValue N102 = N1.getOperand(0).getOperand(2);
7822         if (N102.getOpcode() == ISD::FMUL) {
7823           SDValue N1020 = N102.getOperand(0);
7824           SDValue N1021 = N102.getOperand(1);
7825           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7826                              DAG.getNode(ISD::FNEG, SL, VT,
7827                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7828                                                      N100)),
7829                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7830                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7831                                          DAG.getNode(ISD::FNEG, SL, VT,
7832                                              DAG.getNode(ISD::FP_EXTEND, SL,
7833                                                          VT, N1020)),
7834                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7835                                                      N1021),
7836                                          N0));
7837         }
7838       }
7839     }
7840   }
7841
7842   return SDValue();
7843 }
7844
7845 SDValue DAGCombiner::visitFADD(SDNode *N) {
7846   SDValue N0 = N->getOperand(0);
7847   SDValue N1 = N->getOperand(1);
7848   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7849   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7850   EVT VT = N->getValueType(0);
7851   SDLoc DL(N);
7852   const TargetOptions &Options = DAG.getTarget().Options;
7853
7854   // fold vector ops
7855   if (VT.isVector())
7856     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7857       return FoldedVOp;
7858
7859   // fold (fadd c1, c2) -> c1 + c2
7860   if (N0CFP && N1CFP)
7861     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7862
7863   // canonicalize constant to RHS
7864   if (N0CFP && !N1CFP)
7865     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7866
7867   // fold (fadd A, (fneg B)) -> (fsub A, B)
7868   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7869       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7870     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7871                        GetNegatedExpression(N1, DAG, LegalOperations));
7872
7873   // fold (fadd (fneg A), B) -> (fsub B, A)
7874   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7875       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7876     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7877                        GetNegatedExpression(N0, DAG, LegalOperations));
7878
7879   // If 'unsafe math' is enabled, fold lots of things.
7880   if (Options.UnsafeFPMath) {
7881     // No FP constant should be created after legalization as Instruction
7882     // Selection pass has a hard time dealing with FP constants.
7883     bool AllowNewConst = (Level < AfterLegalizeDAG);
7884
7885     // fold (fadd A, 0) -> A
7886     if (N1CFP && N1CFP->isZero())
7887       return N0;
7888
7889     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7890     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7891         isa<ConstantFPSDNode>(N0.getOperand(1)))
7892       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7893                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7894
7895     // If allowed, fold (fadd (fneg x), x) -> 0.0
7896     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7897       return DAG.getConstantFP(0.0, DL, VT);
7898
7899     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7900     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7901       return DAG.getConstantFP(0.0, DL, VT);
7902
7903     // We can fold chains of FADD's of the same value into multiplications.
7904     // This transform is not safe in general because we are reducing the number
7905     // of rounding steps.
7906     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7907       if (N0.getOpcode() == ISD::FMUL) {
7908         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7909         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7910
7911         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7912         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7913           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7914                                        DAG.getConstantFP(1.0, DL, VT));
7915           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7916         }
7917
7918         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7919         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7920             N1.getOperand(0) == N1.getOperand(1) &&
7921             N0.getOperand(0) == N1.getOperand(0)) {
7922           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7923                                        DAG.getConstantFP(2.0, DL, VT));
7924           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7925         }
7926       }
7927
7928       if (N1.getOpcode() == ISD::FMUL) {
7929         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7930         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7931
7932         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7933         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7934           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7935                                        DAG.getConstantFP(1.0, DL, VT));
7936           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7937         }
7938
7939         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7940         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7941             N0.getOperand(0) == N0.getOperand(1) &&
7942             N1.getOperand(0) == N0.getOperand(0)) {
7943           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7944                                        DAG.getConstantFP(2.0, DL, VT));
7945           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7946         }
7947       }
7948
7949       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7950         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7951         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7952         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7953             (N0.getOperand(0) == N1)) {
7954           return DAG.getNode(ISD::FMUL, DL, VT,
7955                              N1, DAG.getConstantFP(3.0, DL, VT));
7956         }
7957       }
7958
7959       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7960         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7961         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7962         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7963             N1.getOperand(0) == N0) {
7964           return DAG.getNode(ISD::FMUL, DL, VT,
7965                              N0, DAG.getConstantFP(3.0, DL, VT));
7966         }
7967       }
7968
7969       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7970       if (AllowNewConst &&
7971           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7972           N0.getOperand(0) == N0.getOperand(1) &&
7973           N1.getOperand(0) == N1.getOperand(1) &&
7974           N0.getOperand(0) == N1.getOperand(0)) {
7975         return DAG.getNode(ISD::FMUL, DL, VT,
7976                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7977       }
7978     }
7979   } // enable-unsafe-fp-math
7980
7981   // FADD -> FMA combines:
7982   SDValue Fused = visitFADDForFMACombine(N);
7983   if (Fused) {
7984     AddToWorklist(Fused.getNode());
7985     return Fused;
7986   }
7987
7988   return SDValue();
7989 }
7990
7991 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7992   SDValue N0 = N->getOperand(0);
7993   SDValue N1 = N->getOperand(1);
7994   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7995   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7996   EVT VT = N->getValueType(0);
7997   SDLoc dl(N);
7998   const TargetOptions &Options = DAG.getTarget().Options;
7999
8000   // fold vector ops
8001   if (VT.isVector())
8002     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8003       return FoldedVOp;
8004
8005   // fold (fsub c1, c2) -> c1-c2
8006   if (N0CFP && N1CFP)
8007     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8008
8009   // fold (fsub A, (fneg B)) -> (fadd A, B)
8010   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8011     return DAG.getNode(ISD::FADD, dl, VT, N0,
8012                        GetNegatedExpression(N1, DAG, LegalOperations));
8013
8014   // If 'unsafe math' is enabled, fold lots of things.
8015   if (Options.UnsafeFPMath) {
8016     // (fsub A, 0) -> A
8017     if (N1CFP && N1CFP->isZero())
8018       return N0;
8019
8020     // (fsub 0, B) -> -B
8021     if (N0CFP && N0CFP->isZero()) {
8022       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8023         return GetNegatedExpression(N1, DAG, LegalOperations);
8024       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8025         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8026     }
8027
8028     // (fsub x, x) -> 0.0
8029     if (N0 == N1)
8030       return DAG.getConstantFP(0.0f, dl, VT);
8031
8032     // (fsub x, (fadd x, y)) -> (fneg y)
8033     // (fsub x, (fadd y, x)) -> (fneg y)
8034     if (N1.getOpcode() == ISD::FADD) {
8035       SDValue N10 = N1->getOperand(0);
8036       SDValue N11 = N1->getOperand(1);
8037
8038       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8039         return GetNegatedExpression(N11, DAG, LegalOperations);
8040
8041       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8042         return GetNegatedExpression(N10, DAG, LegalOperations);
8043     }
8044   }
8045
8046   // FSUB -> FMA combines:
8047   SDValue Fused = visitFSUBForFMACombine(N);
8048   if (Fused) {
8049     AddToWorklist(Fused.getNode());
8050     return Fused;
8051   }
8052
8053   return SDValue();
8054 }
8055
8056 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8057   SDValue N0 = N->getOperand(0);
8058   SDValue N1 = N->getOperand(1);
8059   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8060   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8061   EVT VT = N->getValueType(0);
8062   SDLoc DL(N);
8063   const TargetOptions &Options = DAG.getTarget().Options;
8064
8065   // fold vector ops
8066   if (VT.isVector()) {
8067     // This just handles C1 * C2 for vectors. Other vector folds are below.
8068     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8069       return FoldedVOp;
8070   }
8071
8072   // fold (fmul c1, c2) -> c1*c2
8073   if (N0CFP && N1CFP)
8074     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8075
8076   // canonicalize constant to RHS
8077   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8078      !isConstantFPBuildVectorOrConstantFP(N1))
8079     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8080
8081   // fold (fmul A, 1.0) -> A
8082   if (N1CFP && N1CFP->isExactlyValue(1.0))
8083     return N0;
8084
8085   if (Options.UnsafeFPMath) {
8086     // fold (fmul A, 0) -> 0
8087     if (N1CFP && N1CFP->isZero())
8088       return N1;
8089
8090     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8091     if (N0.getOpcode() == ISD::FMUL) {
8092       // Fold scalars or any vector constants (not just splats).
8093       // This fold is done in general by InstCombine, but extra fmul insts
8094       // may have been generated during lowering.
8095       SDValue N00 = N0.getOperand(0);
8096       SDValue N01 = N0.getOperand(1);
8097       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8098       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8099       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8100
8101       // Check 1: Make sure that the first operand of the inner multiply is NOT
8102       // a constant. Otherwise, we may induce infinite looping.
8103       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8104         // Check 2: Make sure that the second operand of the inner multiply and
8105         // the second operand of the outer multiply are constants.
8106         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8107             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8108           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8109           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8110         }
8111       }
8112     }
8113
8114     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8115     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8116     // during an early run of DAGCombiner can prevent folding with fmuls
8117     // inserted during lowering.
8118     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8119       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8120       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8121       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8122     }
8123   }
8124
8125   // fold (fmul X, 2.0) -> (fadd X, X)
8126   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8127     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8128
8129   // fold (fmul X, -1.0) -> (fneg X)
8130   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8131     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8132       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8133
8134   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8135   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8136     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8137       // Both can be negated for free, check to see if at least one is cheaper
8138       // negated.
8139       if (LHSNeg == 2 || RHSNeg == 2)
8140         return DAG.getNode(ISD::FMUL, DL, VT,
8141                            GetNegatedExpression(N0, DAG, LegalOperations),
8142                            GetNegatedExpression(N1, DAG, LegalOperations));
8143     }
8144   }
8145
8146   return SDValue();
8147 }
8148
8149 SDValue DAGCombiner::visitFMA(SDNode *N) {
8150   SDValue N0 = N->getOperand(0);
8151   SDValue N1 = N->getOperand(1);
8152   SDValue N2 = N->getOperand(2);
8153   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8154   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8155   EVT VT = N->getValueType(0);
8156   SDLoc dl(N);
8157   const TargetOptions &Options = DAG.getTarget().Options;
8158
8159   // Constant fold FMA.
8160   if (isa<ConstantFPSDNode>(N0) &&
8161       isa<ConstantFPSDNode>(N1) &&
8162       isa<ConstantFPSDNode>(N2)) {
8163     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8164   }
8165
8166   if (Options.UnsafeFPMath) {
8167     if (N0CFP && N0CFP->isZero())
8168       return N2;
8169     if (N1CFP && N1CFP->isZero())
8170       return N2;
8171   }
8172   if (N0CFP && N0CFP->isExactlyValue(1.0))
8173     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8174   if (N1CFP && N1CFP->isExactlyValue(1.0))
8175     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8176
8177   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8178   if (N0CFP && !N1CFP)
8179     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8180
8181   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8182   if (Options.UnsafeFPMath && N1CFP &&
8183       N2.getOpcode() == ISD::FMUL &&
8184       N0 == N2.getOperand(0) &&
8185       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8186     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8187                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8188   }
8189
8190
8191   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8192   if (Options.UnsafeFPMath &&
8193       N0.getOpcode() == ISD::FMUL && N1CFP &&
8194       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8195     return DAG.getNode(ISD::FMA, dl, VT,
8196                        N0.getOperand(0),
8197                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8198                        N2);
8199   }
8200
8201   // (fma x, 1, y) -> (fadd x, y)
8202   // (fma x, -1, y) -> (fadd (fneg x), y)
8203   if (N1CFP) {
8204     if (N1CFP->isExactlyValue(1.0))
8205       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8206
8207     if (N1CFP->isExactlyValue(-1.0) &&
8208         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8209       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8210       AddToWorklist(RHSNeg.getNode());
8211       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8212     }
8213   }
8214
8215   // (fma x, c, x) -> (fmul x, (c+1))
8216   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8217     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8218                        DAG.getNode(ISD::FADD, dl, VT,
8219                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8220
8221   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8222   if (Options.UnsafeFPMath && N1CFP &&
8223       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8224     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8225                        DAG.getNode(ISD::FADD, dl, VT,
8226                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8227
8228
8229   return SDValue();
8230 }
8231
8232 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8233   SDValue N0 = N->getOperand(0);
8234   SDValue N1 = N->getOperand(1);
8235   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8236   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8237   EVT VT = N->getValueType(0);
8238   SDLoc DL(N);
8239   const TargetOptions &Options = DAG.getTarget().Options;
8240
8241   // fold vector ops
8242   if (VT.isVector())
8243     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8244       return FoldedVOp;
8245
8246   // fold (fdiv c1, c2) -> c1/c2
8247   if (N0CFP && N1CFP)
8248     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8249
8250   if (Options.UnsafeFPMath) {
8251     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8252     if (N1CFP) {
8253       // Compute the reciprocal 1.0 / c2.
8254       APFloat N1APF = N1CFP->getValueAPF();
8255       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8256       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8257       // Only do the transform if the reciprocal is a legal fp immediate that
8258       // isn't too nasty (eg NaN, denormal, ...).
8259       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8260           (!LegalOperations ||
8261            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8262            // backend)... we should handle this gracefully after Legalize.
8263            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8264            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8265            TLI.isFPImmLegal(Recip, VT)))
8266         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8267                            DAG.getConstantFP(Recip, DL, VT));
8268     }
8269
8270     // If this FDIV is part of a reciprocal square root, it may be folded
8271     // into a target-specific square root estimate instruction.
8272     if (N1.getOpcode() == ISD::FSQRT) {
8273       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8274         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8275       }
8276     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8277                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8278       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8279         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8280         AddToWorklist(RV.getNode());
8281         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8282       }
8283     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8284                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8285       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8286         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8287         AddToWorklist(RV.getNode());
8288         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8289       }
8290     } else if (N1.getOpcode() == ISD::FMUL) {
8291       // Look through an FMUL. Even though this won't remove the FDIV directly,
8292       // it's still worthwhile to get rid of the FSQRT if possible.
8293       SDValue SqrtOp;
8294       SDValue OtherOp;
8295       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8296         SqrtOp = N1.getOperand(0);
8297         OtherOp = N1.getOperand(1);
8298       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8299         SqrtOp = N1.getOperand(1);
8300         OtherOp = N1.getOperand(0);
8301       }
8302       if (SqrtOp.getNode()) {
8303         // We found a FSQRT, so try to make this fold:
8304         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8305         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8306           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8307           AddToWorklist(RV.getNode());
8308           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8309         }
8310       }
8311     }
8312
8313     // Fold into a reciprocal estimate and multiply instead of a real divide.
8314     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8315       AddToWorklist(RV.getNode());
8316       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8317     }
8318   }
8319
8320   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8321   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8322     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8323       // Both can be negated for free, check to see if at least one is cheaper
8324       // negated.
8325       if (LHSNeg == 2 || RHSNeg == 2)
8326         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8327                            GetNegatedExpression(N0, DAG, LegalOperations),
8328                            GetNegatedExpression(N1, DAG, LegalOperations));
8329     }
8330   }
8331
8332   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8333   // reciprocal.
8334   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8335   // Notice that this is not always beneficial. One reason is different target
8336   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8337   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8338   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8339   if (Options.UnsafeFPMath) {
8340     // Skip if current node is a reciprocal.
8341     if (N0CFP && N0CFP->isExactlyValue(1.0))
8342       return SDValue();
8343
8344     SmallVector<SDNode *, 4> Users;
8345     // Find all FDIV users of the same divisor.
8346     for (auto *U : N1->uses()) {
8347       if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8348         Users.push_back(U);
8349     }
8350
8351     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8352       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8353       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8354
8355       // Dividend / Divisor -> Dividend * Reciprocal
8356       for (auto *U : Users) {
8357         SDValue Dividend = U->getOperand(0);
8358         if (Dividend != FPOne) {
8359           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8360                                         Reciprocal);
8361           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8362         }
8363       }
8364       return SDValue();
8365     }
8366   }
8367
8368   return SDValue();
8369 }
8370
8371 SDValue DAGCombiner::visitFREM(SDNode *N) {
8372   SDValue N0 = N->getOperand(0);
8373   SDValue N1 = N->getOperand(1);
8374   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8375   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8376   EVT VT = N->getValueType(0);
8377
8378   // fold (frem c1, c2) -> fmod(c1,c2)
8379   if (N0CFP && N1CFP)
8380     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8381
8382   return SDValue();
8383 }
8384
8385 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8386   if (DAG.getTarget().Options.UnsafeFPMath &&
8387       !TLI.isFsqrtCheap()) {
8388     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8389     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8390       EVT VT = RV.getValueType();
8391       SDLoc DL(N);
8392       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8393       AddToWorklist(RV.getNode());
8394
8395       // Unfortunately, RV is now NaN if the input was exactly 0.
8396       // Select out this case and force the answer to 0.
8397       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8398       SDValue ZeroCmp =
8399         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8400                      N->getOperand(0), Zero, ISD::SETEQ);
8401       AddToWorklist(ZeroCmp.getNode());
8402       AddToWorklist(RV.getNode());
8403
8404       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8405                        DL, VT, ZeroCmp, Zero, RV);
8406       return RV;
8407     }
8408   }
8409   return SDValue();
8410 }
8411
8412 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8413   SDValue N0 = N->getOperand(0);
8414   SDValue N1 = N->getOperand(1);
8415   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8416   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8417   EVT VT = N->getValueType(0);
8418
8419   if (N0CFP && N1CFP)  // Constant fold
8420     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8421
8422   if (N1CFP) {
8423     const APFloat& V = N1CFP->getValueAPF();
8424     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8425     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8426     if (!V.isNegative()) {
8427       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8428         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8429     } else {
8430       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8431         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8432                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8433     }
8434   }
8435
8436   // copysign(fabs(x), y) -> copysign(x, y)
8437   // copysign(fneg(x), y) -> copysign(x, y)
8438   // copysign(copysign(x,z), y) -> copysign(x, y)
8439   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8440       N0.getOpcode() == ISD::FCOPYSIGN)
8441     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8442                        N0.getOperand(0), N1);
8443
8444   // copysign(x, abs(y)) -> abs(x)
8445   if (N1.getOpcode() == ISD::FABS)
8446     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8447
8448   // copysign(x, copysign(y,z)) -> copysign(x, z)
8449   if (N1.getOpcode() == ISD::FCOPYSIGN)
8450     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8451                        N0, N1.getOperand(1));
8452
8453   // copysign(x, fp_extend(y)) -> copysign(x, y)
8454   // copysign(x, fp_round(y)) -> copysign(x, y)
8455   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8456     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8457                        N0, N1.getOperand(0));
8458
8459   return SDValue();
8460 }
8461
8462 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8463   SDValue N0 = N->getOperand(0);
8464   EVT VT = N->getValueType(0);
8465   EVT OpVT = N0.getValueType();
8466
8467   // fold (sint_to_fp c1) -> c1fp
8468   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8469       // ...but only if the target supports immediate floating-point values
8470       (!LegalOperations ||
8471        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8472     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8473
8474   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8475   // but UINT_TO_FP is legal on this target, try to convert.
8476   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8477       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8478     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8479     if (DAG.SignBitIsZero(N0))
8480       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8481   }
8482
8483   // The next optimizations are desirable only if SELECT_CC can be lowered.
8484   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8485     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8486     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8487         !VT.isVector() &&
8488         (!LegalOperations ||
8489          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8490       SDLoc DL(N);
8491       SDValue Ops[] =
8492         { N0.getOperand(0), N0.getOperand(1),
8493           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8494           N0.getOperand(2) };
8495       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8496     }
8497
8498     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8499     //      (select_cc x, y, 1.0, 0.0,, cc)
8500     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8501         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8502         (!LegalOperations ||
8503          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8504       SDLoc DL(N);
8505       SDValue Ops[] =
8506         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8507           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8508           N0.getOperand(0).getOperand(2) };
8509       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8510     }
8511   }
8512
8513   return SDValue();
8514 }
8515
8516 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8517   SDValue N0 = N->getOperand(0);
8518   EVT VT = N->getValueType(0);
8519   EVT OpVT = N0.getValueType();
8520
8521   // fold (uint_to_fp c1) -> c1fp
8522   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8523       // ...but only if the target supports immediate floating-point values
8524       (!LegalOperations ||
8525        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8526     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8527
8528   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8529   // but SINT_TO_FP is legal on this target, try to convert.
8530   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8531       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8532     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8533     if (DAG.SignBitIsZero(N0))
8534       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8535   }
8536
8537   // The next optimizations are desirable only if SELECT_CC can be lowered.
8538   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8539     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8540
8541     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8542         (!LegalOperations ||
8543          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8544       SDLoc DL(N);
8545       SDValue Ops[] =
8546         { N0.getOperand(0), N0.getOperand(1),
8547           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8548           N0.getOperand(2) };
8549       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8550     }
8551   }
8552
8553   return SDValue();
8554 }
8555
8556 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8557 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8558   SDValue N0 = N->getOperand(0);
8559   EVT VT = N->getValueType(0);
8560
8561   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8562     return SDValue();
8563
8564   SDValue Src = N0.getOperand(0);
8565   EVT SrcVT = Src.getValueType();
8566   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8567   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8568
8569   // We can safely assume the conversion won't overflow the output range,
8570   // because (for example) (uint8_t)18293.f is undefined behavior.
8571
8572   // Since we can assume the conversion won't overflow, our decision as to
8573   // whether the input will fit in the float should depend on the minimum
8574   // of the input range and output range.
8575
8576   // This means this is also safe for a signed input and unsigned output, since
8577   // a negative input would lead to undefined behavior.
8578   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8579   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8580   unsigned ActualSize = std::min(InputSize, OutputSize);
8581   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8582
8583   // We can only fold away the float conversion if the input range can be
8584   // represented exactly in the float range.
8585   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8586     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8587       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8588                                                        : ISD::ZERO_EXTEND;
8589       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8590     }
8591     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8592       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8593     if (SrcVT == VT)
8594       return Src;
8595     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8596   }
8597   return SDValue();
8598 }
8599
8600 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8601   SDValue N0 = N->getOperand(0);
8602   EVT VT = N->getValueType(0);
8603
8604   // fold (fp_to_sint c1fp) -> c1
8605   if (isConstantFPBuildVectorOrConstantFP(N0))
8606     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8607
8608   return FoldIntToFPToInt(N, DAG);
8609 }
8610
8611 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8612   SDValue N0 = N->getOperand(0);
8613   EVT VT = N->getValueType(0);
8614
8615   // fold (fp_to_uint c1fp) -> c1
8616   if (isConstantFPBuildVectorOrConstantFP(N0))
8617     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8618
8619   return FoldIntToFPToInt(N, DAG);
8620 }
8621
8622 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8623   SDValue N0 = N->getOperand(0);
8624   SDValue N1 = N->getOperand(1);
8625   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8626   EVT VT = N->getValueType(0);
8627
8628   // fold (fp_round c1fp) -> c1fp
8629   if (N0CFP)
8630     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8631
8632   // fold (fp_round (fp_extend x)) -> x
8633   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8634     return N0.getOperand(0);
8635
8636   // fold (fp_round (fp_round x)) -> (fp_round x)
8637   if (N0.getOpcode() == ISD::FP_ROUND) {
8638     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8639     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8640     // If the first fp_round isn't a value preserving truncation, it might
8641     // introduce a tie in the second fp_round, that wouldn't occur in the
8642     // single-step fp_round we want to fold to.
8643     // In other words, double rounding isn't the same as rounding.
8644     // Also, this is a value preserving truncation iff both fp_round's are.
8645     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8646       SDLoc DL(N);
8647       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8648                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8649     }
8650   }
8651
8652   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8653   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8654     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8655                               N0.getOperand(0), N1);
8656     AddToWorklist(Tmp.getNode());
8657     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8658                        Tmp, N0.getOperand(1));
8659   }
8660
8661   return SDValue();
8662 }
8663
8664 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8665   SDValue N0 = N->getOperand(0);
8666   EVT VT = N->getValueType(0);
8667   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8668   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8669
8670   // fold (fp_round_inreg c1fp) -> c1fp
8671   if (N0CFP && isTypeLegal(EVT)) {
8672     SDLoc DL(N);
8673     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8674     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8675   }
8676
8677   return SDValue();
8678 }
8679
8680 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8681   SDValue N0 = N->getOperand(0);
8682   EVT VT = N->getValueType(0);
8683
8684   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8685   if (N->hasOneUse() &&
8686       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8687     return SDValue();
8688
8689   // fold (fp_extend c1fp) -> c1fp
8690   if (isConstantFPBuildVectorOrConstantFP(N0))
8691     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8692
8693   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8694   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8695       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8696     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8697
8698   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8699   // value of X.
8700   if (N0.getOpcode() == ISD::FP_ROUND
8701       && N0.getNode()->getConstantOperandVal(1) == 1) {
8702     SDValue In = N0.getOperand(0);
8703     if (In.getValueType() == VT) return In;
8704     if (VT.bitsLT(In.getValueType()))
8705       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8706                          In, N0.getOperand(1));
8707     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8708   }
8709
8710   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8711   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8712        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8713     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8714     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8715                                      LN0->getChain(),
8716                                      LN0->getBasePtr(), N0.getValueType(),
8717                                      LN0->getMemOperand());
8718     CombineTo(N, ExtLoad);
8719     CombineTo(N0.getNode(),
8720               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8721                           N0.getValueType(), ExtLoad,
8722                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8723               ExtLoad.getValue(1));
8724     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8725   }
8726
8727   return SDValue();
8728 }
8729
8730 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8731   SDValue N0 = N->getOperand(0);
8732   EVT VT = N->getValueType(0);
8733
8734   // fold (fceil c1) -> fceil(c1)
8735   if (isConstantFPBuildVectorOrConstantFP(N0))
8736     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8737
8738   return SDValue();
8739 }
8740
8741 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8742   SDValue N0 = N->getOperand(0);
8743   EVT VT = N->getValueType(0);
8744
8745   // fold (ftrunc c1) -> ftrunc(c1)
8746   if (isConstantFPBuildVectorOrConstantFP(N0))
8747     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8748
8749   return SDValue();
8750 }
8751
8752 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8753   SDValue N0 = N->getOperand(0);
8754   EVT VT = N->getValueType(0);
8755
8756   // fold (ffloor c1) -> ffloor(c1)
8757   if (isConstantFPBuildVectorOrConstantFP(N0))
8758     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8759
8760   return SDValue();
8761 }
8762
8763 // FIXME: FNEG and FABS have a lot in common; refactor.
8764 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8765   SDValue N0 = N->getOperand(0);
8766   EVT VT = N->getValueType(0);
8767
8768   // Constant fold FNEG.
8769   if (isConstantFPBuildVectorOrConstantFP(N0))
8770     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8771
8772   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8773                          &DAG.getTarget().Options))
8774     return GetNegatedExpression(N0, DAG, LegalOperations);
8775
8776   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8777   // constant pool values.
8778   if (!TLI.isFNegFree(VT) &&
8779       N0.getOpcode() == ISD::BITCAST &&
8780       N0.getNode()->hasOneUse()) {
8781     SDValue Int = N0.getOperand(0);
8782     EVT IntVT = Int.getValueType();
8783     if (IntVT.isInteger() && !IntVT.isVector()) {
8784       APInt SignMask;
8785       if (N0.getValueType().isVector()) {
8786         // For a vector, get a mask such as 0x80... per scalar element
8787         // and splat it.
8788         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8789         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8790       } else {
8791         // For a scalar, just generate 0x80...
8792         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8793       }
8794       SDLoc DL0(N0);
8795       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8796                         DAG.getConstant(SignMask, DL0, IntVT));
8797       AddToWorklist(Int.getNode());
8798       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8799     }
8800   }
8801
8802   // (fneg (fmul c, x)) -> (fmul -c, x)
8803   if (N0.getOpcode() == ISD::FMUL &&
8804       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8805     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8806     if (CFP1) {
8807       APFloat CVal = CFP1->getValueAPF();
8808       CVal.changeSign();
8809       if (Level >= AfterLegalizeDAG &&
8810           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8811            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8812         return DAG.getNode(
8813             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8814             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8815     }
8816   }
8817
8818   return SDValue();
8819 }
8820
8821 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8822   SDValue N0 = N->getOperand(0);
8823   SDValue N1 = N->getOperand(1);
8824   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8825   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8826
8827   if (N0CFP && N1CFP) {
8828     const APFloat &C0 = N0CFP->getValueAPF();
8829     const APFloat &C1 = N1CFP->getValueAPF();
8830     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8831   }
8832
8833   if (N0CFP) {
8834     EVT VT = N->getValueType(0);
8835     // Canonicalize to constant on RHS.
8836     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8837   }
8838
8839   return SDValue();
8840 }
8841
8842 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8843   SDValue N0 = N->getOperand(0);
8844   SDValue N1 = N->getOperand(1);
8845   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8846   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8847
8848   if (N0CFP && N1CFP) {
8849     const APFloat &C0 = N0CFP->getValueAPF();
8850     const APFloat &C1 = N1CFP->getValueAPF();
8851     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8852   }
8853
8854   if (N0CFP) {
8855     EVT VT = N->getValueType(0);
8856     // Canonicalize to constant on RHS.
8857     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8858   }
8859
8860   return SDValue();
8861 }
8862
8863 SDValue DAGCombiner::visitFABS(SDNode *N) {
8864   SDValue N0 = N->getOperand(0);
8865   EVT VT = N->getValueType(0);
8866
8867   // fold (fabs c1) -> fabs(c1)
8868   if (isConstantFPBuildVectorOrConstantFP(N0))
8869     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8870
8871   // fold (fabs (fabs x)) -> (fabs x)
8872   if (N0.getOpcode() == ISD::FABS)
8873     return N->getOperand(0);
8874
8875   // fold (fabs (fneg x)) -> (fabs x)
8876   // fold (fabs (fcopysign x, y)) -> (fabs x)
8877   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8878     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8879
8880   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8881   // constant pool values.
8882   if (!TLI.isFAbsFree(VT) &&
8883       N0.getOpcode() == ISD::BITCAST &&
8884       N0.getNode()->hasOneUse()) {
8885     SDValue Int = N0.getOperand(0);
8886     EVT IntVT = Int.getValueType();
8887     if (IntVT.isInteger() && !IntVT.isVector()) {
8888       APInt SignMask;
8889       if (N0.getValueType().isVector()) {
8890         // For a vector, get a mask such as 0x7f... per scalar element
8891         // and splat it.
8892         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8893         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8894       } else {
8895         // For a scalar, just generate 0x7f...
8896         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8897       }
8898       SDLoc DL(N0);
8899       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8900                         DAG.getConstant(SignMask, DL, IntVT));
8901       AddToWorklist(Int.getNode());
8902       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8903     }
8904   }
8905
8906   return SDValue();
8907 }
8908
8909 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8910   SDValue Chain = N->getOperand(0);
8911   SDValue N1 = N->getOperand(1);
8912   SDValue N2 = N->getOperand(2);
8913
8914   // If N is a constant we could fold this into a fallthrough or unconditional
8915   // branch. However that doesn't happen very often in normal code, because
8916   // Instcombine/SimplifyCFG should have handled the available opportunities.
8917   // If we did this folding here, it would be necessary to update the
8918   // MachineBasicBlock CFG, which is awkward.
8919
8920   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8921   // on the target.
8922   if (N1.getOpcode() == ISD::SETCC &&
8923       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8924                                    N1.getOperand(0).getValueType())) {
8925     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8926                        Chain, N1.getOperand(2),
8927                        N1.getOperand(0), N1.getOperand(1), N2);
8928   }
8929
8930   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8931       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8932        (N1.getOperand(0).hasOneUse() &&
8933         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8934     SDNode *Trunc = nullptr;
8935     if (N1.getOpcode() == ISD::TRUNCATE) {
8936       // Look pass the truncate.
8937       Trunc = N1.getNode();
8938       N1 = N1.getOperand(0);
8939     }
8940
8941     // Match this pattern so that we can generate simpler code:
8942     //
8943     //   %a = ...
8944     //   %b = and i32 %a, 2
8945     //   %c = srl i32 %b, 1
8946     //   brcond i32 %c ...
8947     //
8948     // into
8949     //
8950     //   %a = ...
8951     //   %b = and i32 %a, 2
8952     //   %c = setcc eq %b, 0
8953     //   brcond %c ...
8954     //
8955     // This applies only when the AND constant value has one bit set and the
8956     // SRL constant is equal to the log2 of the AND constant. The back-end is
8957     // smart enough to convert the result into a TEST/JMP sequence.
8958     SDValue Op0 = N1.getOperand(0);
8959     SDValue Op1 = N1.getOperand(1);
8960
8961     if (Op0.getOpcode() == ISD::AND &&
8962         Op1.getOpcode() == ISD::Constant) {
8963       SDValue AndOp1 = Op0.getOperand(1);
8964
8965       if (AndOp1.getOpcode() == ISD::Constant) {
8966         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8967
8968         if (AndConst.isPowerOf2() &&
8969             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8970           SDLoc DL(N);
8971           SDValue SetCC =
8972             DAG.getSetCC(DL,
8973                          getSetCCResultType(Op0.getValueType()),
8974                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8975                          ISD::SETNE);
8976
8977           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8978                                           MVT::Other, Chain, SetCC, N2);
8979           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8980           // will convert it back to (X & C1) >> C2.
8981           CombineTo(N, NewBRCond, false);
8982           // Truncate is dead.
8983           if (Trunc)
8984             deleteAndRecombine(Trunc);
8985           // Replace the uses of SRL with SETCC
8986           WorklistRemover DeadNodes(*this);
8987           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8988           deleteAndRecombine(N1.getNode());
8989           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8990         }
8991       }
8992     }
8993
8994     if (Trunc)
8995       // Restore N1 if the above transformation doesn't match.
8996       N1 = N->getOperand(1);
8997   }
8998
8999   // Transform br(xor(x, y)) -> br(x != y)
9000   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9001   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9002     SDNode *TheXor = N1.getNode();
9003     SDValue Op0 = TheXor->getOperand(0);
9004     SDValue Op1 = TheXor->getOperand(1);
9005     if (Op0.getOpcode() == Op1.getOpcode()) {
9006       // Avoid missing important xor optimizations.
9007       SDValue Tmp = visitXOR(TheXor);
9008       if (Tmp.getNode()) {
9009         if (Tmp.getNode() != TheXor) {
9010           DEBUG(dbgs() << "\nReplacing.8 ";
9011                 TheXor->dump(&DAG);
9012                 dbgs() << "\nWith: ";
9013                 Tmp.getNode()->dump(&DAG);
9014                 dbgs() << '\n');
9015           WorklistRemover DeadNodes(*this);
9016           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9017           deleteAndRecombine(TheXor);
9018           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9019                              MVT::Other, Chain, Tmp, N2);
9020         }
9021
9022         // visitXOR has changed XOR's operands or replaced the XOR completely,
9023         // bail out.
9024         return SDValue(N, 0);
9025       }
9026     }
9027
9028     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9029       bool Equal = false;
9030       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9031           Op0.getOpcode() == ISD::XOR) {
9032         TheXor = Op0.getNode();
9033         Equal = true;
9034       }
9035
9036       EVT SetCCVT = N1.getValueType();
9037       if (LegalTypes)
9038         SetCCVT = getSetCCResultType(SetCCVT);
9039       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9040                                    SetCCVT,
9041                                    Op0, Op1,
9042                                    Equal ? ISD::SETEQ : ISD::SETNE);
9043       // Replace the uses of XOR with SETCC
9044       WorklistRemover DeadNodes(*this);
9045       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9046       deleteAndRecombine(N1.getNode());
9047       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9048                          MVT::Other, Chain, SetCC, N2);
9049     }
9050   }
9051
9052   return SDValue();
9053 }
9054
9055 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9056 //
9057 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9058   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9059   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9060
9061   // If N is a constant we could fold this into a fallthrough or unconditional
9062   // branch. However that doesn't happen very often in normal code, because
9063   // Instcombine/SimplifyCFG should have handled the available opportunities.
9064   // If we did this folding here, it would be necessary to update the
9065   // MachineBasicBlock CFG, which is awkward.
9066
9067   // Use SimplifySetCC to simplify SETCC's.
9068   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9069                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9070                                false);
9071   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9072
9073   // fold to a simpler setcc
9074   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9075     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9076                        N->getOperand(0), Simp.getOperand(2),
9077                        Simp.getOperand(0), Simp.getOperand(1),
9078                        N->getOperand(4));
9079
9080   return SDValue();
9081 }
9082
9083 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9084 /// and that N may be folded in the load / store addressing mode.
9085 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9086                                     SelectionDAG &DAG,
9087                                     const TargetLowering &TLI) {
9088   EVT VT;
9089   unsigned AS;
9090
9091   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9092     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9093       return false;
9094     VT = LD->getMemoryVT();
9095     AS = LD->getAddressSpace();
9096   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9097     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9098       return false;
9099     VT = ST->getMemoryVT();
9100     AS = ST->getAddressSpace();
9101   } else
9102     return false;
9103
9104   TargetLowering::AddrMode AM;
9105   if (N->getOpcode() == ISD::ADD) {
9106     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9107     if (Offset)
9108       // [reg +/- imm]
9109       AM.BaseOffs = Offset->getSExtValue();
9110     else
9111       // [reg +/- reg]
9112       AM.Scale = 1;
9113   } else if (N->getOpcode() == ISD::SUB) {
9114     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9115     if (Offset)
9116       // [reg +/- imm]
9117       AM.BaseOffs = -Offset->getSExtValue();
9118     else
9119       // [reg +/- reg]
9120       AM.Scale = 1;
9121   } else
9122     return false;
9123
9124   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9125 }
9126
9127 /// Try turning a load/store into a pre-indexed load/store when the base
9128 /// pointer is an add or subtract and it has other uses besides the load/store.
9129 /// After the transformation, the new indexed load/store has effectively folded
9130 /// the add/subtract in and all of its other uses are redirected to the
9131 /// new load/store.
9132 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9133   if (Level < AfterLegalizeDAG)
9134     return false;
9135
9136   bool isLoad = true;
9137   SDValue Ptr;
9138   EVT VT;
9139   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9140     if (LD->isIndexed())
9141       return false;
9142     VT = LD->getMemoryVT();
9143     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9144         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9145       return false;
9146     Ptr = LD->getBasePtr();
9147   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9148     if (ST->isIndexed())
9149       return false;
9150     VT = ST->getMemoryVT();
9151     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9152         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9153       return false;
9154     Ptr = ST->getBasePtr();
9155     isLoad = false;
9156   } else {
9157     return false;
9158   }
9159
9160   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9161   // out.  There is no reason to make this a preinc/predec.
9162   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9163       Ptr.getNode()->hasOneUse())
9164     return false;
9165
9166   // Ask the target to do addressing mode selection.
9167   SDValue BasePtr;
9168   SDValue Offset;
9169   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9170   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9171     return false;
9172
9173   // Backends without true r+i pre-indexed forms may need to pass a
9174   // constant base with a variable offset so that constant coercion
9175   // will work with the patterns in canonical form.
9176   bool Swapped = false;
9177   if (isa<ConstantSDNode>(BasePtr)) {
9178     std::swap(BasePtr, Offset);
9179     Swapped = true;
9180   }
9181
9182   // Don't create a indexed load / store with zero offset.
9183   if (isNullConstant(Offset))
9184     return false;
9185
9186   // Try turning it into a pre-indexed load / store except when:
9187   // 1) The new base ptr is a frame index.
9188   // 2) If N is a store and the new base ptr is either the same as or is a
9189   //    predecessor of the value being stored.
9190   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9191   //    that would create a cycle.
9192   // 4) All uses are load / store ops that use it as old base ptr.
9193
9194   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9195   // (plus the implicit offset) to a register to preinc anyway.
9196   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9197     return false;
9198
9199   // Check #2.
9200   if (!isLoad) {
9201     SDValue Val = cast<StoreSDNode>(N)->getValue();
9202     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9203       return false;
9204   }
9205
9206   // If the offset is a constant, there may be other adds of constants that
9207   // can be folded with this one. We should do this to avoid having to keep
9208   // a copy of the original base pointer.
9209   SmallVector<SDNode *, 16> OtherUses;
9210   if (isa<ConstantSDNode>(Offset))
9211     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9212                               UE = BasePtr.getNode()->use_end();
9213          UI != UE; ++UI) {
9214       SDUse &Use = UI.getUse();
9215       // Skip the use that is Ptr and uses of other results from BasePtr's
9216       // node (important for nodes that return multiple results).
9217       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9218         continue;
9219
9220       if (Use.getUser()->isPredecessorOf(N))
9221         continue;
9222
9223       if (Use.getUser()->getOpcode() != ISD::ADD &&
9224           Use.getUser()->getOpcode() != ISD::SUB) {
9225         OtherUses.clear();
9226         break;
9227       }
9228
9229       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9230       if (!isa<ConstantSDNode>(Op1)) {
9231         OtherUses.clear();
9232         break;
9233       }
9234
9235       // FIXME: In some cases, we can be smarter about this.
9236       if (Op1.getValueType() != Offset.getValueType()) {
9237         OtherUses.clear();
9238         break;
9239       }
9240
9241       OtherUses.push_back(Use.getUser());
9242     }
9243
9244   if (Swapped)
9245     std::swap(BasePtr, Offset);
9246
9247   // Now check for #3 and #4.
9248   bool RealUse = false;
9249
9250   // Caches for hasPredecessorHelper
9251   SmallPtrSet<const SDNode *, 32> Visited;
9252   SmallVector<const SDNode *, 16> Worklist;
9253
9254   for (SDNode *Use : Ptr.getNode()->uses()) {
9255     if (Use == N)
9256       continue;
9257     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9258       return false;
9259
9260     // If Ptr may be folded in addressing mode of other use, then it's
9261     // not profitable to do this transformation.
9262     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9263       RealUse = true;
9264   }
9265
9266   if (!RealUse)
9267     return false;
9268
9269   SDValue Result;
9270   if (isLoad)
9271     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9272                                 BasePtr, Offset, AM);
9273   else
9274     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9275                                  BasePtr, Offset, AM);
9276   ++PreIndexedNodes;
9277   ++NodesCombined;
9278   DEBUG(dbgs() << "\nReplacing.4 ";
9279         N->dump(&DAG);
9280         dbgs() << "\nWith: ";
9281         Result.getNode()->dump(&DAG);
9282         dbgs() << '\n');
9283   WorklistRemover DeadNodes(*this);
9284   if (isLoad) {
9285     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9286     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9287   } else {
9288     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9289   }
9290
9291   // Finally, since the node is now dead, remove it from the graph.
9292   deleteAndRecombine(N);
9293
9294   if (Swapped)
9295     std::swap(BasePtr, Offset);
9296
9297   // Replace other uses of BasePtr that can be updated to use Ptr
9298   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9299     unsigned OffsetIdx = 1;
9300     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9301       OffsetIdx = 0;
9302     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9303            BasePtr.getNode() && "Expected BasePtr operand");
9304
9305     // We need to replace ptr0 in the following expression:
9306     //   x0 * offset0 + y0 * ptr0 = t0
9307     // knowing that
9308     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9309     //
9310     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9311     // indexed load/store and the expresion that needs to be re-written.
9312     //
9313     // Therefore, we have:
9314     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9315
9316     ConstantSDNode *CN =
9317       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9318     int X0, X1, Y0, Y1;
9319     APInt Offset0 = CN->getAPIntValue();
9320     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9321
9322     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9323     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9324     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9325     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9326
9327     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9328
9329     APInt CNV = Offset0;
9330     if (X0 < 0) CNV = -CNV;
9331     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9332     else CNV = CNV - Offset1;
9333
9334     SDLoc DL(OtherUses[i]);
9335
9336     // We can now generate the new expression.
9337     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9338     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9339
9340     SDValue NewUse = DAG.getNode(Opcode,
9341                                  DL,
9342                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9343     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9344     deleteAndRecombine(OtherUses[i]);
9345   }
9346
9347   // Replace the uses of Ptr with uses of the updated base value.
9348   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9349   deleteAndRecombine(Ptr.getNode());
9350
9351   return true;
9352 }
9353
9354 /// Try to combine a load/store with a add/sub of the base pointer node into a
9355 /// post-indexed load/store. The transformation folded the add/subtract into the
9356 /// new indexed load/store effectively and all of its uses are redirected to the
9357 /// new load/store.
9358 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9359   if (Level < AfterLegalizeDAG)
9360     return false;
9361
9362   bool isLoad = true;
9363   SDValue Ptr;
9364   EVT VT;
9365   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9366     if (LD->isIndexed())
9367       return false;
9368     VT = LD->getMemoryVT();
9369     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9370         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9371       return false;
9372     Ptr = LD->getBasePtr();
9373   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9374     if (ST->isIndexed())
9375       return false;
9376     VT = ST->getMemoryVT();
9377     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9378         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9379       return false;
9380     Ptr = ST->getBasePtr();
9381     isLoad = false;
9382   } else {
9383     return false;
9384   }
9385
9386   if (Ptr.getNode()->hasOneUse())
9387     return false;
9388
9389   for (SDNode *Op : Ptr.getNode()->uses()) {
9390     if (Op == N ||
9391         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9392       continue;
9393
9394     SDValue BasePtr;
9395     SDValue Offset;
9396     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9397     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9398       // Don't create a indexed load / store with zero offset.
9399       if (isNullConstant(Offset))
9400         continue;
9401
9402       // Try turning it into a post-indexed load / store except when
9403       // 1) All uses are load / store ops that use it as base ptr (and
9404       //    it may be folded as addressing mmode).
9405       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9406       //    nor a successor of N. Otherwise, if Op is folded that would
9407       //    create a cycle.
9408
9409       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9410         continue;
9411
9412       // Check for #1.
9413       bool TryNext = false;
9414       for (SDNode *Use : BasePtr.getNode()->uses()) {
9415         if (Use == Ptr.getNode())
9416           continue;
9417
9418         // If all the uses are load / store addresses, then don't do the
9419         // transformation.
9420         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9421           bool RealUse = false;
9422           for (SDNode *UseUse : Use->uses()) {
9423             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9424               RealUse = true;
9425           }
9426
9427           if (!RealUse) {
9428             TryNext = true;
9429             break;
9430           }
9431         }
9432       }
9433
9434       if (TryNext)
9435         continue;
9436
9437       // Check for #2
9438       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9439         SDValue Result = isLoad
9440           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9441                                BasePtr, Offset, AM)
9442           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9443                                 BasePtr, Offset, AM);
9444         ++PostIndexedNodes;
9445         ++NodesCombined;
9446         DEBUG(dbgs() << "\nReplacing.5 ";
9447               N->dump(&DAG);
9448               dbgs() << "\nWith: ";
9449               Result.getNode()->dump(&DAG);
9450               dbgs() << '\n');
9451         WorklistRemover DeadNodes(*this);
9452         if (isLoad) {
9453           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9454           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9455         } else {
9456           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9457         }
9458
9459         // Finally, since the node is now dead, remove it from the graph.
9460         deleteAndRecombine(N);
9461
9462         // Replace the uses of Use with uses of the updated base value.
9463         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9464                                       Result.getValue(isLoad ? 1 : 0));
9465         deleteAndRecombine(Op);
9466         return true;
9467       }
9468     }
9469   }
9470
9471   return false;
9472 }
9473
9474 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9475 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9476   ISD::MemIndexedMode AM = LD->getAddressingMode();
9477   assert(AM != ISD::UNINDEXED);
9478   SDValue BP = LD->getOperand(1);
9479   SDValue Inc = LD->getOperand(2);
9480
9481   // Some backends use TargetConstants for load offsets, but don't expect
9482   // TargetConstants in general ADD nodes. We can convert these constants into
9483   // regular Constants (if the constant is not opaque).
9484   assert((Inc.getOpcode() != ISD::TargetConstant ||
9485           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9486          "Cannot split out indexing using opaque target constants");
9487   if (Inc.getOpcode() == ISD::TargetConstant) {
9488     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9489     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9490                           ConstInc->getValueType(0));
9491   }
9492
9493   unsigned Opc =
9494       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9495   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9496 }
9497
9498 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9499   LoadSDNode *LD  = cast<LoadSDNode>(N);
9500   SDValue Chain = LD->getChain();
9501   SDValue Ptr   = LD->getBasePtr();
9502
9503   // If load is not volatile and there are no uses of the loaded value (and
9504   // the updated indexed value in case of indexed loads), change uses of the
9505   // chain value into uses of the chain input (i.e. delete the dead load).
9506   if (!LD->isVolatile()) {
9507     if (N->getValueType(1) == MVT::Other) {
9508       // Unindexed loads.
9509       if (!N->hasAnyUseOfValue(0)) {
9510         // It's not safe to use the two value CombineTo variant here. e.g.
9511         // v1, chain2 = load chain1, loc
9512         // v2, chain3 = load chain2, loc
9513         // v3         = add v2, c
9514         // Now we replace use of chain2 with chain1.  This makes the second load
9515         // isomorphic to the one we are deleting, and thus makes this load live.
9516         DEBUG(dbgs() << "\nReplacing.6 ";
9517               N->dump(&DAG);
9518               dbgs() << "\nWith chain: ";
9519               Chain.getNode()->dump(&DAG);
9520               dbgs() << "\n");
9521         WorklistRemover DeadNodes(*this);
9522         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9523
9524         if (N->use_empty())
9525           deleteAndRecombine(N);
9526
9527         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9528       }
9529     } else {
9530       // Indexed loads.
9531       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9532
9533       // If this load has an opaque TargetConstant offset, then we cannot split
9534       // the indexing into an add/sub directly (that TargetConstant may not be
9535       // valid for a different type of node, and we cannot convert an opaque
9536       // target constant into a regular constant).
9537       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9538                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9539
9540       if (!N->hasAnyUseOfValue(0) &&
9541           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9542         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9543         SDValue Index;
9544         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9545           Index = SplitIndexingFromLoad(LD);
9546           // Try to fold the base pointer arithmetic into subsequent loads and
9547           // stores.
9548           AddUsersToWorklist(N);
9549         } else
9550           Index = DAG.getUNDEF(N->getValueType(1));
9551         DEBUG(dbgs() << "\nReplacing.7 ";
9552               N->dump(&DAG);
9553               dbgs() << "\nWith: ";
9554               Undef.getNode()->dump(&DAG);
9555               dbgs() << " and 2 other values\n");
9556         WorklistRemover DeadNodes(*this);
9557         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9558         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9559         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9560         deleteAndRecombine(N);
9561         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9562       }
9563     }
9564   }
9565
9566   // If this load is directly stored, replace the load value with the stored
9567   // value.
9568   // TODO: Handle store large -> read small portion.
9569   // TODO: Handle TRUNCSTORE/LOADEXT
9570   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9571     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9572       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9573       if (PrevST->getBasePtr() == Ptr &&
9574           PrevST->getValue().getValueType() == N->getValueType(0))
9575       return CombineTo(N, Chain.getOperand(1), Chain);
9576     }
9577   }
9578
9579   // Try to infer better alignment information than the load already has.
9580   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9581     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9582       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9583         SDValue NewLoad =
9584                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9585                               LD->getValueType(0),
9586                               Chain, Ptr, LD->getPointerInfo(),
9587                               LD->getMemoryVT(),
9588                               LD->isVolatile(), LD->isNonTemporal(),
9589                               LD->isInvariant(), Align, LD->getAAInfo());
9590         if (NewLoad.getNode() != N)
9591           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9592       }
9593     }
9594   }
9595
9596   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9597                                                   : DAG.getSubtarget().useAA();
9598 #ifndef NDEBUG
9599   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9600       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9601     UseAA = false;
9602 #endif
9603   if (UseAA && LD->isUnindexed()) {
9604     // Walk up chain skipping non-aliasing memory nodes.
9605     SDValue BetterChain = FindBetterChain(N, Chain);
9606
9607     // If there is a better chain.
9608     if (Chain != BetterChain) {
9609       SDValue ReplLoad;
9610
9611       // Replace the chain to void dependency.
9612       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9613         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9614                                BetterChain, Ptr, LD->getMemOperand());
9615       } else {
9616         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9617                                   LD->getValueType(0),
9618                                   BetterChain, Ptr, LD->getMemoryVT(),
9619                                   LD->getMemOperand());
9620       }
9621
9622       // Create token factor to keep old chain connected.
9623       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9624                                   MVT::Other, Chain, ReplLoad.getValue(1));
9625
9626       // Make sure the new and old chains are cleaned up.
9627       AddToWorklist(Token.getNode());
9628
9629       // Replace uses with load result and token factor. Don't add users
9630       // to work list.
9631       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9632     }
9633   }
9634
9635   // Try transforming N to an indexed load.
9636   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9637     return SDValue(N, 0);
9638
9639   // Try to slice up N to more direct loads if the slices are mapped to
9640   // different register banks or pairing can take place.
9641   if (SliceUpLoad(N))
9642     return SDValue(N, 0);
9643
9644   return SDValue();
9645 }
9646
9647 namespace {
9648 /// \brief Helper structure used to slice a load in smaller loads.
9649 /// Basically a slice is obtained from the following sequence:
9650 /// Origin = load Ty1, Base
9651 /// Shift = srl Ty1 Origin, CstTy Amount
9652 /// Inst = trunc Shift to Ty2
9653 ///
9654 /// Then, it will be rewriten into:
9655 /// Slice = load SliceTy, Base + SliceOffset
9656 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9657 ///
9658 /// SliceTy is deduced from the number of bits that are actually used to
9659 /// build Inst.
9660 struct LoadedSlice {
9661   /// \brief Helper structure used to compute the cost of a slice.
9662   struct Cost {
9663     /// Are we optimizing for code size.
9664     bool ForCodeSize;
9665     /// Various cost.
9666     unsigned Loads;
9667     unsigned Truncates;
9668     unsigned CrossRegisterBanksCopies;
9669     unsigned ZExts;
9670     unsigned Shift;
9671
9672     Cost(bool ForCodeSize = false)
9673         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9674           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9675
9676     /// \brief Get the cost of one isolated slice.
9677     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9678         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9679           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9680       EVT TruncType = LS.Inst->getValueType(0);
9681       EVT LoadedType = LS.getLoadedType();
9682       if (TruncType != LoadedType &&
9683           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9684         ZExts = 1;
9685     }
9686
9687     /// \brief Account for slicing gain in the current cost.
9688     /// Slicing provide a few gains like removing a shift or a
9689     /// truncate. This method allows to grow the cost of the original
9690     /// load with the gain from this slice.
9691     void addSliceGain(const LoadedSlice &LS) {
9692       // Each slice saves a truncate.
9693       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9694       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9695                               LS.Inst->getOperand(0).getValueType()))
9696         ++Truncates;
9697       // If there is a shift amount, this slice gets rid of it.
9698       if (LS.Shift)
9699         ++Shift;
9700       // If this slice can merge a cross register bank copy, account for it.
9701       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9702         ++CrossRegisterBanksCopies;
9703     }
9704
9705     Cost &operator+=(const Cost &RHS) {
9706       Loads += RHS.Loads;
9707       Truncates += RHS.Truncates;
9708       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9709       ZExts += RHS.ZExts;
9710       Shift += RHS.Shift;
9711       return *this;
9712     }
9713
9714     bool operator==(const Cost &RHS) const {
9715       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9716              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9717              ZExts == RHS.ZExts && Shift == RHS.Shift;
9718     }
9719
9720     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9721
9722     bool operator<(const Cost &RHS) const {
9723       // Assume cross register banks copies are as expensive as loads.
9724       // FIXME: Do we want some more target hooks?
9725       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9726       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9727       // Unless we are optimizing for code size, consider the
9728       // expensive operation first.
9729       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9730         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9731       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9732              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9733     }
9734
9735     bool operator>(const Cost &RHS) const { return RHS < *this; }
9736
9737     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9738
9739     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9740   };
9741   // The last instruction that represent the slice. This should be a
9742   // truncate instruction.
9743   SDNode *Inst;
9744   // The original load instruction.
9745   LoadSDNode *Origin;
9746   // The right shift amount in bits from the original load.
9747   unsigned Shift;
9748   // The DAG from which Origin came from.
9749   // This is used to get some contextual information about legal types, etc.
9750   SelectionDAG *DAG;
9751
9752   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9753               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9754       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9755
9756   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9757   /// \return Result is \p BitWidth and has used bits set to 1 and
9758   ///         not used bits set to 0.
9759   APInt getUsedBits() const {
9760     // Reproduce the trunc(lshr) sequence:
9761     // - Start from the truncated value.
9762     // - Zero extend to the desired bit width.
9763     // - Shift left.
9764     assert(Origin && "No original load to compare against.");
9765     unsigned BitWidth = Origin->getValueSizeInBits(0);
9766     assert(Inst && "This slice is not bound to an instruction");
9767     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9768            "Extracted slice is bigger than the whole type!");
9769     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9770     UsedBits.setAllBits();
9771     UsedBits = UsedBits.zext(BitWidth);
9772     UsedBits <<= Shift;
9773     return UsedBits;
9774   }
9775
9776   /// \brief Get the size of the slice to be loaded in bytes.
9777   unsigned getLoadedSize() const {
9778     unsigned SliceSize = getUsedBits().countPopulation();
9779     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9780     return SliceSize / 8;
9781   }
9782
9783   /// \brief Get the type that will be loaded for this slice.
9784   /// Note: This may not be the final type for the slice.
9785   EVT getLoadedType() const {
9786     assert(DAG && "Missing context");
9787     LLVMContext &Ctxt = *DAG->getContext();
9788     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9789   }
9790
9791   /// \brief Get the alignment of the load used for this slice.
9792   unsigned getAlignment() const {
9793     unsigned Alignment = Origin->getAlignment();
9794     unsigned Offset = getOffsetFromBase();
9795     if (Offset != 0)
9796       Alignment = MinAlign(Alignment, Alignment + Offset);
9797     return Alignment;
9798   }
9799
9800   /// \brief Check if this slice can be rewritten with legal operations.
9801   bool isLegal() const {
9802     // An invalid slice is not legal.
9803     if (!Origin || !Inst || !DAG)
9804       return false;
9805
9806     // Offsets are for indexed load only, we do not handle that.
9807     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9808       return false;
9809
9810     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9811
9812     // Check that the type is legal.
9813     EVT SliceType = getLoadedType();
9814     if (!TLI.isTypeLegal(SliceType))
9815       return false;
9816
9817     // Check that the load is legal for this type.
9818     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9819       return false;
9820
9821     // Check that the offset can be computed.
9822     // 1. Check its type.
9823     EVT PtrType = Origin->getBasePtr().getValueType();
9824     if (PtrType == MVT::Untyped || PtrType.isExtended())
9825       return false;
9826
9827     // 2. Check that it fits in the immediate.
9828     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9829       return false;
9830
9831     // 3. Check that the computation is legal.
9832     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9833       return false;
9834
9835     // Check that the zext is legal if it needs one.
9836     EVT TruncateType = Inst->getValueType(0);
9837     if (TruncateType != SliceType &&
9838         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9839       return false;
9840
9841     return true;
9842   }
9843
9844   /// \brief Get the offset in bytes of this slice in the original chunk of
9845   /// bits.
9846   /// \pre DAG != nullptr.
9847   uint64_t getOffsetFromBase() const {
9848     assert(DAG && "Missing context.");
9849     bool IsBigEndian =
9850         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9851     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9852     uint64_t Offset = Shift / 8;
9853     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9854     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9855            "The size of the original loaded type is not a multiple of a"
9856            " byte.");
9857     // If Offset is bigger than TySizeInBytes, it means we are loading all
9858     // zeros. This should have been optimized before in the process.
9859     assert(TySizeInBytes > Offset &&
9860            "Invalid shift amount for given loaded size");
9861     if (IsBigEndian)
9862       Offset = TySizeInBytes - Offset - getLoadedSize();
9863     return Offset;
9864   }
9865
9866   /// \brief Generate the sequence of instructions to load the slice
9867   /// represented by this object and redirect the uses of this slice to
9868   /// this new sequence of instructions.
9869   /// \pre this->Inst && this->Origin are valid Instructions and this
9870   /// object passed the legal check: LoadedSlice::isLegal returned true.
9871   /// \return The last instruction of the sequence used to load the slice.
9872   SDValue loadSlice() const {
9873     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9874     const SDValue &OldBaseAddr = Origin->getBasePtr();
9875     SDValue BaseAddr = OldBaseAddr;
9876     // Get the offset in that chunk of bytes w.r.t. the endianess.
9877     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9878     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9879     if (Offset) {
9880       // BaseAddr = BaseAddr + Offset.
9881       EVT ArithType = BaseAddr.getValueType();
9882       SDLoc DL(Origin);
9883       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9884                               DAG->getConstant(Offset, DL, ArithType));
9885     }
9886
9887     // Create the type of the loaded slice according to its size.
9888     EVT SliceType = getLoadedType();
9889
9890     // Create the load for the slice.
9891     SDValue LastInst = DAG->getLoad(
9892         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9893         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9894         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9895     // If the final type is not the same as the loaded type, this means that
9896     // we have to pad with zero. Create a zero extend for that.
9897     EVT FinalType = Inst->getValueType(0);
9898     if (SliceType != FinalType)
9899       LastInst =
9900           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9901     return LastInst;
9902   }
9903
9904   /// \brief Check if this slice can be merged with an expensive cross register
9905   /// bank copy. E.g.,
9906   /// i = load i32
9907   /// f = bitcast i32 i to float
9908   bool canMergeExpensiveCrossRegisterBankCopy() const {
9909     if (!Inst || !Inst->hasOneUse())
9910       return false;
9911     SDNode *Use = *Inst->use_begin();
9912     if (Use->getOpcode() != ISD::BITCAST)
9913       return false;
9914     assert(DAG && "Missing context");
9915     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9916     EVT ResVT = Use->getValueType(0);
9917     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9918     const TargetRegisterClass *ArgRC =
9919         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9920     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9921       return false;
9922
9923     // At this point, we know that we perform a cross-register-bank copy.
9924     // Check if it is expensive.
9925     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9926     // Assume bitcasts are cheap, unless both register classes do not
9927     // explicitly share a common sub class.
9928     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9929       return false;
9930
9931     // Check if it will be merged with the load.
9932     // 1. Check the alignment constraint.
9933     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9934         ResVT.getTypeForEVT(*DAG->getContext()));
9935
9936     if (RequiredAlignment > getAlignment())
9937       return false;
9938
9939     // 2. Check that the load is a legal operation for that type.
9940     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9941       return false;
9942
9943     // 3. Check that we do not have a zext in the way.
9944     if (Inst->getValueType(0) != getLoadedType())
9945       return false;
9946
9947     return true;
9948   }
9949 };
9950 }
9951
9952 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9953 /// \p UsedBits looks like 0..0 1..1 0..0.
9954 static bool areUsedBitsDense(const APInt &UsedBits) {
9955   // If all the bits are one, this is dense!
9956   if (UsedBits.isAllOnesValue())
9957     return true;
9958
9959   // Get rid of the unused bits on the right.
9960   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9961   // Get rid of the unused bits on the left.
9962   if (NarrowedUsedBits.countLeadingZeros())
9963     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9964   // Check that the chunk of bits is completely used.
9965   return NarrowedUsedBits.isAllOnesValue();
9966 }
9967
9968 /// \brief Check whether or not \p First and \p Second are next to each other
9969 /// in memory. This means that there is no hole between the bits loaded
9970 /// by \p First and the bits loaded by \p Second.
9971 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9972                                      const LoadedSlice &Second) {
9973   assert(First.Origin == Second.Origin && First.Origin &&
9974          "Unable to match different memory origins.");
9975   APInt UsedBits = First.getUsedBits();
9976   assert((UsedBits & Second.getUsedBits()) == 0 &&
9977          "Slices are not supposed to overlap.");
9978   UsedBits |= Second.getUsedBits();
9979   return areUsedBitsDense(UsedBits);
9980 }
9981
9982 /// \brief Adjust the \p GlobalLSCost according to the target
9983 /// paring capabilities and the layout of the slices.
9984 /// \pre \p GlobalLSCost should account for at least as many loads as
9985 /// there is in the slices in \p LoadedSlices.
9986 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9987                                  LoadedSlice::Cost &GlobalLSCost) {
9988   unsigned NumberOfSlices = LoadedSlices.size();
9989   // If there is less than 2 elements, no pairing is possible.
9990   if (NumberOfSlices < 2)
9991     return;
9992
9993   // Sort the slices so that elements that are likely to be next to each
9994   // other in memory are next to each other in the list.
9995   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9996             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9997     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9998     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9999   });
10000   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10001   // First (resp. Second) is the first (resp. Second) potentially candidate
10002   // to be placed in a paired load.
10003   const LoadedSlice *First = nullptr;
10004   const LoadedSlice *Second = nullptr;
10005   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10006                 // Set the beginning of the pair.
10007                                                            First = Second) {
10008
10009     Second = &LoadedSlices[CurrSlice];
10010
10011     // If First is NULL, it means we start a new pair.
10012     // Get to the next slice.
10013     if (!First)
10014       continue;
10015
10016     EVT LoadedType = First->getLoadedType();
10017
10018     // If the types of the slices are different, we cannot pair them.
10019     if (LoadedType != Second->getLoadedType())
10020       continue;
10021
10022     // Check if the target supplies paired loads for this type.
10023     unsigned RequiredAlignment = 0;
10024     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10025       // move to the next pair, this type is hopeless.
10026       Second = nullptr;
10027       continue;
10028     }
10029     // Check if we meet the alignment requirement.
10030     if (RequiredAlignment > First->getAlignment())
10031       continue;
10032
10033     // Check that both loads are next to each other in memory.
10034     if (!areSlicesNextToEachOther(*First, *Second))
10035       continue;
10036
10037     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10038     --GlobalLSCost.Loads;
10039     // Move to the next pair.
10040     Second = nullptr;
10041   }
10042 }
10043
10044 /// \brief Check the profitability of all involved LoadedSlice.
10045 /// Currently, it is considered profitable if there is exactly two
10046 /// involved slices (1) which are (2) next to each other in memory, and
10047 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10048 ///
10049 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10050 /// the elements themselves.
10051 ///
10052 /// FIXME: When the cost model will be mature enough, we can relax
10053 /// constraints (1) and (2).
10054 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10055                                 const APInt &UsedBits, bool ForCodeSize) {
10056   unsigned NumberOfSlices = LoadedSlices.size();
10057   if (StressLoadSlicing)
10058     return NumberOfSlices > 1;
10059
10060   // Check (1).
10061   if (NumberOfSlices != 2)
10062     return false;
10063
10064   // Check (2).
10065   if (!areUsedBitsDense(UsedBits))
10066     return false;
10067
10068   // Check (3).
10069   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10070   // The original code has one big load.
10071   OrigCost.Loads = 1;
10072   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10073     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10074     // Accumulate the cost of all the slices.
10075     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10076     GlobalSlicingCost += SliceCost;
10077
10078     // Account as cost in the original configuration the gain obtained
10079     // with the current slices.
10080     OrigCost.addSliceGain(LS);
10081   }
10082
10083   // If the target supports paired load, adjust the cost accordingly.
10084   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10085   return OrigCost > GlobalSlicingCost;
10086 }
10087
10088 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10089 /// operations, split it in the various pieces being extracted.
10090 ///
10091 /// This sort of thing is introduced by SROA.
10092 /// This slicing takes care not to insert overlapping loads.
10093 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10094 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10095   if (Level < AfterLegalizeDAG)
10096     return false;
10097
10098   LoadSDNode *LD = cast<LoadSDNode>(N);
10099   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10100       !LD->getValueType(0).isInteger())
10101     return false;
10102
10103   // Keep track of already used bits to detect overlapping values.
10104   // In that case, we will just abort the transformation.
10105   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10106
10107   SmallVector<LoadedSlice, 4> LoadedSlices;
10108
10109   // Check if this load is used as several smaller chunks of bits.
10110   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10111   // of computation for each trunc.
10112   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10113        UI != UIEnd; ++UI) {
10114     // Skip the uses of the chain.
10115     if (UI.getUse().getResNo() != 0)
10116       continue;
10117
10118     SDNode *User = *UI;
10119     unsigned Shift = 0;
10120
10121     // Check if this is a trunc(lshr).
10122     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10123         isa<ConstantSDNode>(User->getOperand(1))) {
10124       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10125       User = *User->use_begin();
10126     }
10127
10128     // At this point, User is a Truncate, iff we encountered, trunc or
10129     // trunc(lshr).
10130     if (User->getOpcode() != ISD::TRUNCATE)
10131       return false;
10132
10133     // The width of the type must be a power of 2 and greater than 8-bits.
10134     // Otherwise the load cannot be represented in LLVM IR.
10135     // Moreover, if we shifted with a non-8-bits multiple, the slice
10136     // will be across several bytes. We do not support that.
10137     unsigned Width = User->getValueSizeInBits(0);
10138     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10139       return 0;
10140
10141     // Build the slice for this chain of computations.
10142     LoadedSlice LS(User, LD, Shift, &DAG);
10143     APInt CurrentUsedBits = LS.getUsedBits();
10144
10145     // Check if this slice overlaps with another.
10146     if ((CurrentUsedBits & UsedBits) != 0)
10147       return false;
10148     // Update the bits used globally.
10149     UsedBits |= CurrentUsedBits;
10150
10151     // Check if the new slice would be legal.
10152     if (!LS.isLegal())
10153       return false;
10154
10155     // Record the slice.
10156     LoadedSlices.push_back(LS);
10157   }
10158
10159   // Abort slicing if it does not seem to be profitable.
10160   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10161     return false;
10162
10163   ++SlicedLoads;
10164
10165   // Rewrite each chain to use an independent load.
10166   // By construction, each chain can be represented by a unique load.
10167
10168   // Prepare the argument for the new token factor for all the slices.
10169   SmallVector<SDValue, 8> ArgChains;
10170   for (SmallVectorImpl<LoadedSlice>::const_iterator
10171            LSIt = LoadedSlices.begin(),
10172            LSItEnd = LoadedSlices.end();
10173        LSIt != LSItEnd; ++LSIt) {
10174     SDValue SliceInst = LSIt->loadSlice();
10175     CombineTo(LSIt->Inst, SliceInst, true);
10176     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10177       SliceInst = SliceInst.getOperand(0);
10178     assert(SliceInst->getOpcode() == ISD::LOAD &&
10179            "It takes more than a zext to get to the loaded slice!!");
10180     ArgChains.push_back(SliceInst.getValue(1));
10181   }
10182
10183   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10184                               ArgChains);
10185   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10186   return true;
10187 }
10188
10189 /// Check to see if V is (and load (ptr), imm), where the load is having
10190 /// specific bytes cleared out.  If so, return the byte size being masked out
10191 /// and the shift amount.
10192 static std::pair<unsigned, unsigned>
10193 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10194   std::pair<unsigned, unsigned> Result(0, 0);
10195
10196   // Check for the structure we're looking for.
10197   if (V->getOpcode() != ISD::AND ||
10198       !isa<ConstantSDNode>(V->getOperand(1)) ||
10199       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10200     return Result;
10201
10202   // Check the chain and pointer.
10203   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10204   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10205
10206   // The store should be chained directly to the load or be an operand of a
10207   // tokenfactor.
10208   if (LD == Chain.getNode())
10209     ; // ok.
10210   else if (Chain->getOpcode() != ISD::TokenFactor)
10211     return Result; // Fail.
10212   else {
10213     bool isOk = false;
10214     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10215       if (Chain->getOperand(i).getNode() == LD) {
10216         isOk = true;
10217         break;
10218       }
10219     if (!isOk) return Result;
10220   }
10221
10222   // This only handles simple types.
10223   if (V.getValueType() != MVT::i16 &&
10224       V.getValueType() != MVT::i32 &&
10225       V.getValueType() != MVT::i64)
10226     return Result;
10227
10228   // Check the constant mask.  Invert it so that the bits being masked out are
10229   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10230   // follow the sign bit for uniformity.
10231   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10232   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10233   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10234   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10235   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10236   if (NotMaskLZ == 64) return Result;  // All zero mask.
10237
10238   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10239   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10240     return Result;
10241
10242   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10243   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10244     NotMaskLZ -= 64-V.getValueSizeInBits();
10245
10246   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10247   switch (MaskedBytes) {
10248   case 1:
10249   case 2:
10250   case 4: break;
10251   default: return Result; // All one mask, or 5-byte mask.
10252   }
10253
10254   // Verify that the first bit starts at a multiple of mask so that the access
10255   // is aligned the same as the access width.
10256   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10257
10258   Result.first = MaskedBytes;
10259   Result.second = NotMaskTZ/8;
10260   return Result;
10261 }
10262
10263
10264 /// Check to see if IVal is something that provides a value as specified by
10265 /// MaskInfo. If so, replace the specified store with a narrower store of
10266 /// truncated IVal.
10267 static SDNode *
10268 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10269                                 SDValue IVal, StoreSDNode *St,
10270                                 DAGCombiner *DC) {
10271   unsigned NumBytes = MaskInfo.first;
10272   unsigned ByteShift = MaskInfo.second;
10273   SelectionDAG &DAG = DC->getDAG();
10274
10275   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10276   // that uses this.  If not, this is not a replacement.
10277   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10278                                   ByteShift*8, (ByteShift+NumBytes)*8);
10279   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10280
10281   // Check that it is legal on the target to do this.  It is legal if the new
10282   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10283   // legalization.
10284   MVT VT = MVT::getIntegerVT(NumBytes*8);
10285   if (!DC->isTypeLegal(VT))
10286     return nullptr;
10287
10288   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10289   // shifted by ByteShift and truncated down to NumBytes.
10290   if (ByteShift) {
10291     SDLoc DL(IVal);
10292     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10293                        DAG.getConstant(ByteShift*8, DL,
10294                                     DC->getShiftAmountTy(IVal.getValueType())));
10295   }
10296
10297   // Figure out the offset for the store and the alignment of the access.
10298   unsigned StOffset;
10299   unsigned NewAlign = St->getAlignment();
10300
10301   if (DAG.getTargetLoweringInfo().isLittleEndian())
10302     StOffset = ByteShift;
10303   else
10304     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10305
10306   SDValue Ptr = St->getBasePtr();
10307   if (StOffset) {
10308     SDLoc DL(IVal);
10309     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10310                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10311     NewAlign = MinAlign(NewAlign, StOffset);
10312   }
10313
10314   // Truncate down to the new size.
10315   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10316
10317   ++OpsNarrowed;
10318   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10319                       St->getPointerInfo().getWithOffset(StOffset),
10320                       false, false, NewAlign).getNode();
10321 }
10322
10323
10324 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10325 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10326 /// narrowing the load and store if it would end up being a win for performance
10327 /// or code size.
10328 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10329   StoreSDNode *ST  = cast<StoreSDNode>(N);
10330   if (ST->isVolatile())
10331     return SDValue();
10332
10333   SDValue Chain = ST->getChain();
10334   SDValue Value = ST->getValue();
10335   SDValue Ptr   = ST->getBasePtr();
10336   EVT VT = Value.getValueType();
10337
10338   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10339     return SDValue();
10340
10341   unsigned Opc = Value.getOpcode();
10342
10343   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10344   // is a byte mask indicating a consecutive number of bytes, check to see if
10345   // Y is known to provide just those bytes.  If so, we try to replace the
10346   // load + replace + store sequence with a single (narrower) store, which makes
10347   // the load dead.
10348   if (Opc == ISD::OR) {
10349     std::pair<unsigned, unsigned> MaskedLoad;
10350     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10351     if (MaskedLoad.first)
10352       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10353                                                   Value.getOperand(1), ST,this))
10354         return SDValue(NewST, 0);
10355
10356     // Or is commutative, so try swapping X and Y.
10357     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10358     if (MaskedLoad.first)
10359       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10360                                                   Value.getOperand(0), ST,this))
10361         return SDValue(NewST, 0);
10362   }
10363
10364   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10365       Value.getOperand(1).getOpcode() != ISD::Constant)
10366     return SDValue();
10367
10368   SDValue N0 = Value.getOperand(0);
10369   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10370       Chain == SDValue(N0.getNode(), 1)) {
10371     LoadSDNode *LD = cast<LoadSDNode>(N0);
10372     if (LD->getBasePtr() != Ptr ||
10373         LD->getPointerInfo().getAddrSpace() !=
10374         ST->getPointerInfo().getAddrSpace())
10375       return SDValue();
10376
10377     // Find the type to narrow it the load / op / store to.
10378     SDValue N1 = Value.getOperand(1);
10379     unsigned BitWidth = N1.getValueSizeInBits();
10380     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10381     if (Opc == ISD::AND)
10382       Imm ^= APInt::getAllOnesValue(BitWidth);
10383     if (Imm == 0 || Imm.isAllOnesValue())
10384       return SDValue();
10385     unsigned ShAmt = Imm.countTrailingZeros();
10386     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10387     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10388     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10389     // The narrowing should be profitable, the load/store operation should be
10390     // legal (or custom) and the store size should be equal to the NewVT width.
10391     while (NewBW < BitWidth &&
10392            (NewVT.getStoreSizeInBits() != NewBW ||
10393             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10394             !TLI.isNarrowingProfitable(VT, NewVT))) {
10395       NewBW = NextPowerOf2(NewBW);
10396       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10397     }
10398     if (NewBW >= BitWidth)
10399       return SDValue();
10400
10401     // If the lsb changed does not start at the type bitwidth boundary,
10402     // start at the previous one.
10403     if (ShAmt % NewBW)
10404       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10405     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10406                                    std::min(BitWidth, ShAmt + NewBW));
10407     if ((Imm & Mask) == Imm) {
10408       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10409       if (Opc == ISD::AND)
10410         NewImm ^= APInt::getAllOnesValue(NewBW);
10411       uint64_t PtrOff = ShAmt / 8;
10412       // For big endian targets, we need to adjust the offset to the pointer to
10413       // load the correct bytes.
10414       if (TLI.isBigEndian())
10415         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10416
10417       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10418       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10419       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10420         return SDValue();
10421
10422       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10423                                    Ptr.getValueType(), Ptr,
10424                                    DAG.getConstant(PtrOff, SDLoc(LD),
10425                                                    Ptr.getValueType()));
10426       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10427                                   LD->getChain(), NewPtr,
10428                                   LD->getPointerInfo().getWithOffset(PtrOff),
10429                                   LD->isVolatile(), LD->isNonTemporal(),
10430                                   LD->isInvariant(), NewAlign,
10431                                   LD->getAAInfo());
10432       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10433                                    DAG.getConstant(NewImm, SDLoc(Value),
10434                                                    NewVT));
10435       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10436                                    NewVal, NewPtr,
10437                                    ST->getPointerInfo().getWithOffset(PtrOff),
10438                                    false, false, NewAlign);
10439
10440       AddToWorklist(NewPtr.getNode());
10441       AddToWorklist(NewLD.getNode());
10442       AddToWorklist(NewVal.getNode());
10443       WorklistRemover DeadNodes(*this);
10444       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10445       ++OpsNarrowed;
10446       return NewST;
10447     }
10448   }
10449
10450   return SDValue();
10451 }
10452
10453 /// For a given floating point load / store pair, if the load value isn't used
10454 /// by any other operations, then consider transforming the pair to integer
10455 /// load / store operations if the target deems the transformation profitable.
10456 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10457   StoreSDNode *ST  = cast<StoreSDNode>(N);
10458   SDValue Chain = ST->getChain();
10459   SDValue Value = ST->getValue();
10460   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10461       Value.hasOneUse() &&
10462       Chain == SDValue(Value.getNode(), 1)) {
10463     LoadSDNode *LD = cast<LoadSDNode>(Value);
10464     EVT VT = LD->getMemoryVT();
10465     if (!VT.isFloatingPoint() ||
10466         VT != ST->getMemoryVT() ||
10467         LD->isNonTemporal() ||
10468         ST->isNonTemporal() ||
10469         LD->getPointerInfo().getAddrSpace() != 0 ||
10470         ST->getPointerInfo().getAddrSpace() != 0)
10471       return SDValue();
10472
10473     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10474     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10475         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10476         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10477         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10478       return SDValue();
10479
10480     unsigned LDAlign = LD->getAlignment();
10481     unsigned STAlign = ST->getAlignment();
10482     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10483     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10484     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10485       return SDValue();
10486
10487     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10488                                 LD->getChain(), LD->getBasePtr(),
10489                                 LD->getPointerInfo(),
10490                                 false, false, false, LDAlign);
10491
10492     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10493                                  NewLD, ST->getBasePtr(),
10494                                  ST->getPointerInfo(),
10495                                  false, false, STAlign);
10496
10497     AddToWorklist(NewLD.getNode());
10498     AddToWorklist(NewST.getNode());
10499     WorklistRemover DeadNodes(*this);
10500     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10501     ++LdStFP2Int;
10502     return NewST;
10503   }
10504
10505   return SDValue();
10506 }
10507
10508 namespace {
10509 /// Helper struct to parse and store a memory address as base + index + offset.
10510 /// We ignore sign extensions when it is safe to do so.
10511 /// The following two expressions are not equivalent. To differentiate we need
10512 /// to store whether there was a sign extension involved in the index
10513 /// computation.
10514 ///  (load (i64 add (i64 copyfromreg %c)
10515 ///                 (i64 signextend (add (i8 load %index)
10516 ///                                      (i8 1))))
10517 /// vs
10518 ///
10519 /// (load (i64 add (i64 copyfromreg %c)
10520 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10521 ///                                         (i32 1)))))
10522 struct BaseIndexOffset {
10523   SDValue Base;
10524   SDValue Index;
10525   int64_t Offset;
10526   bool IsIndexSignExt;
10527
10528   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10529
10530   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10531                   bool IsIndexSignExt) :
10532     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10533
10534   bool equalBaseIndex(const BaseIndexOffset &Other) {
10535     return Other.Base == Base && Other.Index == Index &&
10536       Other.IsIndexSignExt == IsIndexSignExt;
10537   }
10538
10539   /// Parses tree in Ptr for base, index, offset addresses.
10540   static BaseIndexOffset match(SDValue Ptr) {
10541     bool IsIndexSignExt = false;
10542
10543     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10544     // instruction, then it could be just the BASE or everything else we don't
10545     // know how to handle. Just use Ptr as BASE and give up.
10546     if (Ptr->getOpcode() != ISD::ADD)
10547       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10548
10549     // We know that we have at least an ADD instruction. Try to pattern match
10550     // the simple case of BASE + OFFSET.
10551     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10552       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10553       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10554                               IsIndexSignExt);
10555     }
10556
10557     // Inside a loop the current BASE pointer is calculated using an ADD and a
10558     // MUL instruction. In this case Ptr is the actual BASE pointer.
10559     // (i64 add (i64 %array_ptr)
10560     //          (i64 mul (i64 %induction_var)
10561     //                   (i64 %element_size)))
10562     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10563       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10564
10565     // Look at Base + Index + Offset cases.
10566     SDValue Base = Ptr->getOperand(0);
10567     SDValue IndexOffset = Ptr->getOperand(1);
10568
10569     // Skip signextends.
10570     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10571       IndexOffset = IndexOffset->getOperand(0);
10572       IsIndexSignExt = true;
10573     }
10574
10575     // Either the case of Base + Index (no offset) or something else.
10576     if (IndexOffset->getOpcode() != ISD::ADD)
10577       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10578
10579     // Now we have the case of Base + Index + offset.
10580     SDValue Index = IndexOffset->getOperand(0);
10581     SDValue Offset = IndexOffset->getOperand(1);
10582
10583     if (!isa<ConstantSDNode>(Offset))
10584       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10585
10586     // Ignore signextends.
10587     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10588       Index = Index->getOperand(0);
10589       IsIndexSignExt = true;
10590     } else IsIndexSignExt = false;
10591
10592     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10593     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10594   }
10595 };
10596 } // namespace
10597
10598 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10599                                                   SDLoc SL,
10600                                                   ArrayRef<MemOpLink> Stores,
10601                                                   EVT Ty) const {
10602   SmallVector<SDValue, 8> BuildVector;
10603
10604   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10605     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10606
10607   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10608 }
10609
10610 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10611                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10612                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10613   // Make sure we have something to merge.
10614   if (NumElem < 2)
10615     return false;
10616
10617   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10618   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10619   unsigned LatestNodeUsed = 0;
10620
10621   for (unsigned i=0; i < NumElem; ++i) {
10622     // Find a chain for the new wide-store operand. Notice that some
10623     // of the store nodes that we found may not be selected for inclusion
10624     // in the wide store. The chain we use needs to be the chain of the
10625     // latest store node which is *used* and replaced by the wide store.
10626     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10627       LatestNodeUsed = i;
10628   }
10629
10630   // The latest Node in the DAG.
10631   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10632   SDLoc DL(StoreNodes[0].MemNode);
10633
10634   SDValue StoredVal;
10635   if (UseVector) {
10636     // Find a legal type for the vector store.
10637     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10638     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10639     if (IsConstantSrc) {
10640       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10641     } else {
10642       SmallVector<SDValue, 8> Ops;
10643       for (unsigned i = 0; i < NumElem ; ++i) {
10644         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10645         SDValue Val = St->getValue();
10646         // All of the operands of a BUILD_VECTOR must have the same type.
10647         if (Val.getValueType() != MemVT)
10648           return false;
10649         Ops.push_back(Val);
10650       }
10651
10652       // Build the extracted vector elements back into a vector.
10653       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10654     }
10655   } else {
10656     // We should always use a vector store when merging extracted vector
10657     // elements, so this path implies a store of constants.
10658     assert(IsConstantSrc && "Merged vector elements should use vector store");
10659
10660     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10661     APInt StoreInt(StoreBW, 0);
10662
10663     // Construct a single integer constant which is made of the smaller
10664     // constant inputs.
10665     bool IsLE = TLI.isLittleEndian();
10666     for (unsigned i = 0; i < NumElem ; ++i) {
10667       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10668       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10669       SDValue Val = St->getValue();
10670       StoreInt <<= ElementSizeBytes*8;
10671       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10672         StoreInt |= C->getAPIntValue().zext(StoreBW);
10673       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10674         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10675       } else {
10676         llvm_unreachable("Invalid constant element type");
10677       }
10678     }
10679
10680     // Create the new Load and Store operations.
10681     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10682     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10683   }
10684
10685   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10686                                   FirstInChain->getBasePtr(),
10687                                   FirstInChain->getPointerInfo(),
10688                                   false, false,
10689                                   FirstInChain->getAlignment());
10690
10691   // Replace the last store with the new store
10692   CombineTo(LatestOp, NewStore);
10693   // Erase all other stores.
10694   for (unsigned i = 0; i < NumElem ; ++i) {
10695     if (StoreNodes[i].MemNode == LatestOp)
10696       continue;
10697     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10698     // ReplaceAllUsesWith will replace all uses that existed when it was
10699     // called, but graph optimizations may cause new ones to appear. For
10700     // example, the case in pr14333 looks like
10701     //
10702     //  St's chain -> St -> another store -> X
10703     //
10704     // And the only difference from St to the other store is the chain.
10705     // When we change it's chain to be St's chain they become identical,
10706     // get CSEed and the net result is that X is now a use of St.
10707     // Since we know that St is redundant, just iterate.
10708     while (!St->use_empty())
10709       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10710     deleteAndRecombine(St);
10711   }
10712
10713   return true;
10714 }
10715
10716 static bool allowableAlignment(const SelectionDAG &DAG,
10717                                const TargetLowering &TLI, EVT EVTTy,
10718                                unsigned AS, unsigned Align) {
10719   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10720     return true;
10721
10722   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10723   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10724   return (Align >= ABIAlignment);
10725 }
10726
10727 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10728   if (OptLevel == CodeGenOpt::None)
10729     return false;
10730
10731   EVT MemVT = St->getMemoryVT();
10732   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10733   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10734       Attribute::NoImplicitFloat);
10735
10736   // This function cannot currently deal with non-byte-sized memory sizes.
10737   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10738     return false;
10739
10740   // Don't merge vectors into wider inputs.
10741   if (MemVT.isVector() || !MemVT.isSimple())
10742     return false;
10743
10744   // Perform an early exit check. Do not bother looking at stored values that
10745   // are not constants, loads, or extracted vector elements.
10746   SDValue StoredVal = St->getValue();
10747   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10748   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10749                        isa<ConstantFPSDNode>(StoredVal);
10750   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10751
10752   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10753     return false;
10754
10755   // Only look at ends of store sequences.
10756   SDValue Chain = SDValue(St, 0);
10757   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10758     return false;
10759
10760   // This holds the base pointer, index, and the offset in bytes from the base
10761   // pointer.
10762   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10763
10764   // We must have a base and an offset.
10765   if (!BasePtr.Base.getNode())
10766     return false;
10767
10768   // Do not handle stores to undef base pointers.
10769   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10770     return false;
10771
10772   // Save the LoadSDNodes that we find in the chain.
10773   // We need to make sure that these nodes do not interfere with
10774   // any of the store nodes.
10775   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10776
10777   // Save the StoreSDNodes that we find in the chain.
10778   SmallVector<MemOpLink, 8> StoreNodes;
10779
10780   // Walk up the chain and look for nodes with offsets from the same
10781   // base pointer. Stop when reaching an instruction with a different kind
10782   // or instruction which has a different base pointer.
10783   unsigned Seq = 0;
10784   StoreSDNode *Index = St;
10785   while (Index) {
10786     // If the chain has more than one use, then we can't reorder the mem ops.
10787     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10788       break;
10789
10790     // Find the base pointer and offset for this memory node.
10791     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10792
10793     // Check that the base pointer is the same as the original one.
10794     if (!Ptr.equalBaseIndex(BasePtr))
10795       break;
10796
10797     // The memory operands must not be volatile.
10798     if (Index->isVolatile() || Index->isIndexed())
10799       break;
10800
10801     // No truncation.
10802     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10803       if (St->isTruncatingStore())
10804         break;
10805
10806     // The stored memory type must be the same.
10807     if (Index->getMemoryVT() != MemVT)
10808       break;
10809
10810     // We found a potential memory operand to merge.
10811     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10812
10813     // Find the next memory operand in the chain. If the next operand in the
10814     // chain is a store then move up and continue the scan with the next
10815     // memory operand. If the next operand is a load save it and use alias
10816     // information to check if it interferes with anything.
10817     SDNode *NextInChain = Index->getChain().getNode();
10818     while (1) {
10819       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10820         // We found a store node. Use it for the next iteration.
10821         Index = STn;
10822         break;
10823       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10824         if (Ldn->isVolatile()) {
10825           Index = nullptr;
10826           break;
10827         }
10828
10829         // Save the load node for later. Continue the scan.
10830         AliasLoadNodes.push_back(Ldn);
10831         NextInChain = Ldn->getChain().getNode();
10832         continue;
10833       } else {
10834         Index = nullptr;
10835         break;
10836       }
10837     }
10838   }
10839
10840   // Check if there is anything to merge.
10841   if (StoreNodes.size() < 2)
10842     return false;
10843
10844   // Sort the memory operands according to their distance from the base pointer.
10845   std::sort(StoreNodes.begin(), StoreNodes.end(),
10846             [](MemOpLink LHS, MemOpLink RHS) {
10847     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10848            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10849             LHS.SequenceNum > RHS.SequenceNum);
10850   });
10851
10852   // Scan the memory operations on the chain and find the first non-consecutive
10853   // store memory address.
10854   unsigned LastConsecutiveStore = 0;
10855   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10856   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10857
10858     // Check that the addresses are consecutive starting from the second
10859     // element in the list of stores.
10860     if (i > 0) {
10861       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10862       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10863         break;
10864     }
10865
10866     bool Alias = false;
10867     // Check if this store interferes with any of the loads that we found.
10868     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10869       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10870         Alias = true;
10871         break;
10872       }
10873     // We found a load that alias with this store. Stop the sequence.
10874     if (Alias)
10875       break;
10876
10877     // Mark this node as useful.
10878     LastConsecutiveStore = i;
10879   }
10880
10881   // The node with the lowest store address.
10882   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10883   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10884   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10885
10886   // Store the constants into memory as one consecutive store.
10887   if (IsConstantSrc) {
10888     unsigned LastLegalType = 0;
10889     unsigned LastLegalVectorType = 0;
10890     bool NonZero = false;
10891     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10892       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10893       SDValue StoredVal = St->getValue();
10894
10895       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10896         NonZero |= !C->isNullValue();
10897       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10898         NonZero |= !C->getConstantFPValue()->isNullValue();
10899       } else {
10900         // Non-constant.
10901         break;
10902       }
10903
10904       // Find a legal type for the constant store.
10905       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10906       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10907       if (TLI.isTypeLegal(StoreTy) &&
10908           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10909                              FirstStoreAlign)) {
10910         LastLegalType = i+1;
10911       // Or check whether a truncstore is legal.
10912       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10913                  TargetLowering::TypePromoteInteger) {
10914         EVT LegalizedStoredValueTy =
10915           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10916         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10917             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10918                                FirstStoreAlign)) {
10919           LastLegalType = i + 1;
10920         }
10921       }
10922
10923       // Find a legal type for the vector store.
10924       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10925       if (TLI.isTypeLegal(Ty) &&
10926           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10927         LastLegalVectorType = i + 1;
10928       }
10929     }
10930
10931
10932     // We only use vectors if the constant is known to be zero or the target
10933     // allows it and the function is not marked with the noimplicitfloat
10934     // attribute.
10935     if (NoVectors) {
10936       LastLegalVectorType = 0;
10937     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10938                                                             LastLegalVectorType,
10939                                                             FirstStoreAS)) {
10940       LastLegalVectorType = 0;
10941     }
10942
10943     // Check if we found a legal integer type to store.
10944     if (LastLegalType == 0 && LastLegalVectorType == 0)
10945       return false;
10946
10947     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10948     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10949
10950     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10951                                            true, UseVector);
10952   }
10953
10954   // When extracting multiple vector elements, try to store them
10955   // in one vector store rather than a sequence of scalar stores.
10956   if (IsExtractVecEltSrc) {
10957     unsigned NumElem = 0;
10958     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10959       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10960       SDValue StoredVal = St->getValue();
10961       // This restriction could be loosened.
10962       // Bail out if any stored values are not elements extracted from a vector.
10963       // It should be possible to handle mixed sources, but load sources need
10964       // more careful handling (see the block of code below that handles
10965       // consecutive loads).
10966       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10967         return false;
10968
10969       // Find a legal type for the vector store.
10970       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10971       if (TLI.isTypeLegal(Ty) &&
10972           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10973         NumElem = i + 1;
10974     }
10975
10976     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10977                                            false, true);
10978   }
10979
10980   // Below we handle the case of multiple consecutive stores that
10981   // come from multiple consecutive loads. We merge them into a single
10982   // wide load and a single wide store.
10983
10984   // Look for load nodes which are used by the stored values.
10985   SmallVector<MemOpLink, 8> LoadNodes;
10986
10987   // Find acceptable loads. Loads need to have the same chain (token factor),
10988   // must not be zext, volatile, indexed, and they must be consecutive.
10989   BaseIndexOffset LdBasePtr;
10990   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10991     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10992     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10993     if (!Ld) break;
10994
10995     // Loads must only have one use.
10996     if (!Ld->hasNUsesOfValue(1, 0))
10997       break;
10998
10999     // The memory operands must not be volatile.
11000     if (Ld->isVolatile() || Ld->isIndexed())
11001       break;
11002
11003     // We do not accept ext loads.
11004     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11005       break;
11006
11007     // The stored memory type must be the same.
11008     if (Ld->getMemoryVT() != MemVT)
11009       break;
11010
11011     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11012     // If this is not the first ptr that we check.
11013     if (LdBasePtr.Base.getNode()) {
11014       // The base ptr must be the same.
11015       if (!LdPtr.equalBaseIndex(LdBasePtr))
11016         break;
11017     } else {
11018       // Check that all other base pointers are the same as this one.
11019       LdBasePtr = LdPtr;
11020     }
11021
11022     // We found a potential memory operand to merge.
11023     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11024   }
11025
11026   if (LoadNodes.size() < 2)
11027     return false;
11028
11029   // If we have load/store pair instructions and we only have two values,
11030   // don't bother.
11031   unsigned RequiredAlignment;
11032   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11033       St->getAlignment() >= RequiredAlignment)
11034     return false;
11035
11036   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11037   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11038   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11039
11040   // Scan the memory operations on the chain and find the first non-consecutive
11041   // load memory address. These variables hold the index in the store node
11042   // array.
11043   unsigned LastConsecutiveLoad = 0;
11044   // This variable refers to the size and not index in the array.
11045   unsigned LastLegalVectorType = 0;
11046   unsigned LastLegalIntegerType = 0;
11047   StartAddress = LoadNodes[0].OffsetFromBase;
11048   SDValue FirstChain = FirstLoad->getChain();
11049   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11050     // All loads much share the same chain.
11051     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11052       break;
11053
11054     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11055     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11056       break;
11057     LastConsecutiveLoad = i;
11058
11059     // Find a legal type for the vector store.
11060     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11061     if (TLI.isTypeLegal(StoreTy) &&
11062         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11063         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11064       LastLegalVectorType = i + 1;
11065     }
11066
11067     // Find a legal type for the integer store.
11068     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11069     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11070     if (TLI.isTypeLegal(StoreTy) &&
11071         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11072         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11073       LastLegalIntegerType = i + 1;
11074     // Or check whether a truncstore and extload is legal.
11075     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11076              TargetLowering::TypePromoteInteger) {
11077       EVT LegalizedStoredValueTy =
11078         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11079       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11080           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11081           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11082           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11083           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11084                              FirstStoreAlign) &&
11085           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11086                              FirstLoadAlign))
11087         LastLegalIntegerType = i+1;
11088     }
11089   }
11090
11091   // Only use vector types if the vector type is larger than the integer type.
11092   // If they are the same, use integers.
11093   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11094   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11095
11096   // We add +1 here because the LastXXX variables refer to location while
11097   // the NumElem refers to array/index size.
11098   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11099   NumElem = std::min(LastLegalType, NumElem);
11100
11101   if (NumElem < 2)
11102     return false;
11103
11104   // The latest Node in the DAG.
11105   unsigned LatestNodeUsed = 0;
11106   for (unsigned i=1; i<NumElem; ++i) {
11107     // Find a chain for the new wide-store operand. Notice that some
11108     // of the store nodes that we found may not be selected for inclusion
11109     // in the wide store. The chain we use needs to be the chain of the
11110     // latest store node which is *used* and replaced by the wide store.
11111     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11112       LatestNodeUsed = i;
11113   }
11114
11115   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11116
11117   // Find if it is better to use vectors or integers to load and store
11118   // to memory.
11119   EVT JointMemOpVT;
11120   if (UseVectorTy) {
11121     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11122   } else {
11123     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11124     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11125   }
11126
11127   SDLoc LoadDL(LoadNodes[0].MemNode);
11128   SDLoc StoreDL(StoreNodes[0].MemNode);
11129
11130   SDValue NewLoad = DAG.getLoad(
11131       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11132       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11133
11134   SDValue NewStore = DAG.getStore(
11135       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11136       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11137
11138   // Replace one of the loads with the new load.
11139   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11140   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11141                                 SDValue(NewLoad.getNode(), 1));
11142
11143   // Remove the rest of the load chains.
11144   for (unsigned i = 1; i < NumElem ; ++i) {
11145     // Replace all chain users of the old load nodes with the chain of the new
11146     // load node.
11147     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11148     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11149   }
11150
11151   // Replace the last store with the new store.
11152   CombineTo(LatestOp, NewStore);
11153   // Erase all other stores.
11154   for (unsigned i = 0; i < NumElem ; ++i) {
11155     // Remove all Store nodes.
11156     if (StoreNodes[i].MemNode == LatestOp)
11157       continue;
11158     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11159     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11160     deleteAndRecombine(St);
11161   }
11162
11163   return true;
11164 }
11165
11166 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11167   StoreSDNode *ST  = cast<StoreSDNode>(N);
11168   SDValue Chain = ST->getChain();
11169   SDValue Value = ST->getValue();
11170   SDValue Ptr   = ST->getBasePtr();
11171
11172   // If this is a store of a bit convert, store the input value if the
11173   // resultant store does not need a higher alignment than the original.
11174   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11175       ST->isUnindexed()) {
11176     unsigned OrigAlign = ST->getAlignment();
11177     EVT SVT = Value.getOperand(0).getValueType();
11178     unsigned Align = TLI.getDataLayout()->
11179       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11180     if (Align <= OrigAlign &&
11181         ((!LegalOperations && !ST->isVolatile()) ||
11182          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11183       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11184                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11185                           ST->isNonTemporal(), OrigAlign,
11186                           ST->getAAInfo());
11187   }
11188
11189   // Turn 'store undef, Ptr' -> nothing.
11190   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11191     return Chain;
11192
11193   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11194   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11195     // NOTE: If the original store is volatile, this transform must not increase
11196     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11197     // processor operation but an i64 (which is not legal) requires two.  So the
11198     // transform should not be done in this case.
11199     if (Value.getOpcode() != ISD::TargetConstantFP) {
11200       SDValue Tmp;
11201       switch (CFP->getSimpleValueType(0).SimpleTy) {
11202       default: llvm_unreachable("Unknown FP type");
11203       case MVT::f16:    // We don't do this for these yet.
11204       case MVT::f80:
11205       case MVT::f128:
11206       case MVT::ppcf128:
11207         break;
11208       case MVT::f32:
11209         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11210             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11211           ;
11212           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11213                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11214                               MVT::i32);
11215           return DAG.getStore(Chain, SDLoc(N), Tmp,
11216                               Ptr, ST->getMemOperand());
11217         }
11218         break;
11219       case MVT::f64:
11220         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11221              !ST->isVolatile()) ||
11222             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11223           ;
11224           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11225                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11226           return DAG.getStore(Chain, SDLoc(N), Tmp,
11227                               Ptr, ST->getMemOperand());
11228         }
11229
11230         if (!ST->isVolatile() &&
11231             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11232           // Many FP stores are not made apparent until after legalize, e.g. for
11233           // argument passing.  Since this is so common, custom legalize the
11234           // 64-bit integer store into two 32-bit stores.
11235           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11236           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11237           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11238           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11239
11240           unsigned Alignment = ST->getAlignment();
11241           bool isVolatile = ST->isVolatile();
11242           bool isNonTemporal = ST->isNonTemporal();
11243           AAMDNodes AAInfo = ST->getAAInfo();
11244
11245           SDLoc DL(N);
11246
11247           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11248                                      Ptr, ST->getPointerInfo(),
11249                                      isVolatile, isNonTemporal,
11250                                      ST->getAlignment(), AAInfo);
11251           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11252                             DAG.getConstant(4, DL, Ptr.getValueType()));
11253           Alignment = MinAlign(Alignment, 4U);
11254           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11255                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11256                                      isVolatile, isNonTemporal,
11257                                      Alignment, AAInfo);
11258           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11259                              St0, St1);
11260         }
11261
11262         break;
11263       }
11264     }
11265   }
11266
11267   // Try to infer better alignment information than the store already has.
11268   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11269     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11270       if (Align > ST->getAlignment()) {
11271         SDValue NewStore =
11272                DAG.getTruncStore(Chain, SDLoc(N), Value,
11273                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11274                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11275                                  ST->getAAInfo());
11276         if (NewStore.getNode() != N)
11277           return CombineTo(ST, NewStore, true);
11278       }
11279     }
11280   }
11281
11282   // Try transforming a pair floating point load / store ops to integer
11283   // load / store ops.
11284   SDValue NewST = TransformFPLoadStorePair(N);
11285   if (NewST.getNode())
11286     return NewST;
11287
11288   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11289                                                   : DAG.getSubtarget().useAA();
11290 #ifndef NDEBUG
11291   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11292       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11293     UseAA = false;
11294 #endif
11295   if (UseAA && ST->isUnindexed()) {
11296     // Walk up chain skipping non-aliasing memory nodes.
11297     SDValue BetterChain = FindBetterChain(N, Chain);
11298
11299     // If there is a better chain.
11300     if (Chain != BetterChain) {
11301       SDValue ReplStore;
11302
11303       // Replace the chain to avoid dependency.
11304       if (ST->isTruncatingStore()) {
11305         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11306                                       ST->getMemoryVT(), ST->getMemOperand());
11307       } else {
11308         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11309                                  ST->getMemOperand());
11310       }
11311
11312       // Create token to keep both nodes around.
11313       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11314                                   MVT::Other, Chain, ReplStore);
11315
11316       // Make sure the new and old chains are cleaned up.
11317       AddToWorklist(Token.getNode());
11318
11319       // Don't add users to work list.
11320       return CombineTo(N, Token, false);
11321     }
11322   }
11323
11324   // Try transforming N to an indexed store.
11325   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11326     return SDValue(N, 0);
11327
11328   // FIXME: is there such a thing as a truncating indexed store?
11329   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11330       Value.getValueType().isInteger()) {
11331     // See if we can simplify the input to this truncstore with knowledge that
11332     // only the low bits are being used.  For example:
11333     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11334     SDValue Shorter =
11335       GetDemandedBits(Value,
11336                       APInt::getLowBitsSet(
11337                         Value.getValueType().getScalarType().getSizeInBits(),
11338                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11339     AddToWorklist(Value.getNode());
11340     if (Shorter.getNode())
11341       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11342                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11343
11344     // Otherwise, see if we can simplify the operation with
11345     // SimplifyDemandedBits, which only works if the value has a single use.
11346     if (SimplifyDemandedBits(Value,
11347                         APInt::getLowBitsSet(
11348                           Value.getValueType().getScalarType().getSizeInBits(),
11349                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11350       return SDValue(N, 0);
11351   }
11352
11353   // If this is a load followed by a store to the same location, then the store
11354   // is dead/noop.
11355   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11356     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11357         ST->isUnindexed() && !ST->isVolatile() &&
11358         // There can't be any side effects between the load and store, such as
11359         // a call or store.
11360         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11361       // The store is dead, remove it.
11362       return Chain;
11363     }
11364   }
11365
11366   // If this is a store followed by a store with the same value to the same
11367   // location, then the store is dead/noop.
11368   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11369     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11370         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11371         ST1->isUnindexed() && !ST1->isVolatile()) {
11372       // The store is dead, remove it.
11373       return Chain;
11374     }
11375   }
11376
11377   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11378   // truncating store.  We can do this even if this is already a truncstore.
11379   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11380       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11381       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11382                             ST->getMemoryVT())) {
11383     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11384                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11385   }
11386
11387   // Only perform this optimization before the types are legal, because we
11388   // don't want to perform this optimization on every DAGCombine invocation.
11389   if (!LegalTypes) {
11390     bool EverChanged = false;
11391
11392     do {
11393       // There can be multiple store sequences on the same chain.
11394       // Keep trying to merge store sequences until we are unable to do so
11395       // or until we merge the last store on the chain.
11396       bool Changed = MergeConsecutiveStores(ST);
11397       EverChanged |= Changed;
11398       if (!Changed) break;
11399     } while (ST->getOpcode() != ISD::DELETED_NODE);
11400
11401     if (EverChanged)
11402       return SDValue(N, 0);
11403   }
11404
11405   return ReduceLoadOpStoreWidth(N);
11406 }
11407
11408 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11409   SDValue InVec = N->getOperand(0);
11410   SDValue InVal = N->getOperand(1);
11411   SDValue EltNo = N->getOperand(2);
11412   SDLoc dl(N);
11413
11414   // If the inserted element is an UNDEF, just use the input vector.
11415   if (InVal.getOpcode() == ISD::UNDEF)
11416     return InVec;
11417
11418   EVT VT = InVec.getValueType();
11419
11420   // If we can't generate a legal BUILD_VECTOR, exit
11421   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11422     return SDValue();
11423
11424   // Check that we know which element is being inserted
11425   if (!isa<ConstantSDNode>(EltNo))
11426     return SDValue();
11427   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11428
11429   // Canonicalize insert_vector_elt dag nodes.
11430   // Example:
11431   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11432   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11433   //
11434   // Do this only if the child insert_vector node has one use; also
11435   // do this only if indices are both constants and Idx1 < Idx0.
11436   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11437       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11438     unsigned OtherElt =
11439       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11440     if (Elt < OtherElt) {
11441       // Swap nodes.
11442       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11443                                   InVec.getOperand(0), InVal, EltNo);
11444       AddToWorklist(NewOp.getNode());
11445       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11446                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11447     }
11448   }
11449
11450   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11451   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11452   // vector elements.
11453   SmallVector<SDValue, 8> Ops;
11454   // Do not combine these two vectors if the output vector will not replace
11455   // the input vector.
11456   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11457     Ops.append(InVec.getNode()->op_begin(),
11458                InVec.getNode()->op_end());
11459   } else if (InVec.getOpcode() == ISD::UNDEF) {
11460     unsigned NElts = VT.getVectorNumElements();
11461     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11462   } else {
11463     return SDValue();
11464   }
11465
11466   // Insert the element
11467   if (Elt < Ops.size()) {
11468     // All the operands of BUILD_VECTOR must have the same type;
11469     // we enforce that here.
11470     EVT OpVT = Ops[0].getValueType();
11471     if (InVal.getValueType() != OpVT)
11472       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11473                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11474                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11475     Ops[Elt] = InVal;
11476   }
11477
11478   // Return the new vector
11479   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11480 }
11481
11482 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11483     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11484   EVT ResultVT = EVE->getValueType(0);
11485   EVT VecEltVT = InVecVT.getVectorElementType();
11486   unsigned Align = OriginalLoad->getAlignment();
11487   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11488       VecEltVT.getTypeForEVT(*DAG.getContext()));
11489
11490   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11491     return SDValue();
11492
11493   Align = NewAlign;
11494
11495   SDValue NewPtr = OriginalLoad->getBasePtr();
11496   SDValue Offset;
11497   EVT PtrType = NewPtr.getValueType();
11498   MachinePointerInfo MPI;
11499   SDLoc DL(EVE);
11500   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11501     int Elt = ConstEltNo->getZExtValue();
11502     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11503     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11504     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11505   } else {
11506     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11507     Offset = DAG.getNode(
11508         ISD::MUL, DL, PtrType, Offset,
11509         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11510     MPI = OriginalLoad->getPointerInfo();
11511   }
11512   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11513
11514   // The replacement we need to do here is a little tricky: we need to
11515   // replace an extractelement of a load with a load.
11516   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11517   // Note that this replacement assumes that the extractvalue is the only
11518   // use of the load; that's okay because we don't want to perform this
11519   // transformation in other cases anyway.
11520   SDValue Load;
11521   SDValue Chain;
11522   if (ResultVT.bitsGT(VecEltVT)) {
11523     // If the result type of vextract is wider than the load, then issue an
11524     // extending load instead.
11525     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11526                                                   VecEltVT)
11527                                    ? ISD::ZEXTLOAD
11528                                    : ISD::EXTLOAD;
11529     Load = DAG.getExtLoad(
11530         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11531         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11532         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11533     Chain = Load.getValue(1);
11534   } else {
11535     Load = DAG.getLoad(
11536         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11537         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11538         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11539     Chain = Load.getValue(1);
11540     if (ResultVT.bitsLT(VecEltVT))
11541       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11542     else
11543       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11544   }
11545   WorklistRemover DeadNodes(*this);
11546   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11547   SDValue To[] = { Load, Chain };
11548   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11549   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11550   // worklist explicitly as well.
11551   AddToWorklist(Load.getNode());
11552   AddUsersToWorklist(Load.getNode()); // Add users too
11553   // Make sure to revisit this node to clean it up; it will usually be dead.
11554   AddToWorklist(EVE);
11555   ++OpsNarrowed;
11556   return SDValue(EVE, 0);
11557 }
11558
11559 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11560   // (vextract (scalar_to_vector val, 0) -> val
11561   SDValue InVec = N->getOperand(0);
11562   EVT VT = InVec.getValueType();
11563   EVT NVT = N->getValueType(0);
11564
11565   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11566     // Check if the result type doesn't match the inserted element type. A
11567     // SCALAR_TO_VECTOR may truncate the inserted element and the
11568     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11569     SDValue InOp = InVec.getOperand(0);
11570     if (InOp.getValueType() != NVT) {
11571       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11572       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11573     }
11574     return InOp;
11575   }
11576
11577   SDValue EltNo = N->getOperand(1);
11578   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11579
11580   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11581   // We only perform this optimization before the op legalization phase because
11582   // we may introduce new vector instructions which are not backed by TD
11583   // patterns. For example on AVX, extracting elements from a wide vector
11584   // without using extract_subvector. However, if we can find an underlying
11585   // scalar value, then we can always use that.
11586   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11587       && ConstEltNo) {
11588     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11589     int NumElem = VT.getVectorNumElements();
11590     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11591     // Find the new index to extract from.
11592     int OrigElt = SVOp->getMaskElt(Elt);
11593
11594     // Extracting an undef index is undef.
11595     if (OrigElt == -1)
11596       return DAG.getUNDEF(NVT);
11597
11598     // Select the right vector half to extract from.
11599     SDValue SVInVec;
11600     if (OrigElt < NumElem) {
11601       SVInVec = InVec->getOperand(0);
11602     } else {
11603       SVInVec = InVec->getOperand(1);
11604       OrigElt -= NumElem;
11605     }
11606
11607     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11608       SDValue InOp = SVInVec.getOperand(OrigElt);
11609       if (InOp.getValueType() != NVT) {
11610         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11611         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11612       }
11613
11614       return InOp;
11615     }
11616
11617     // FIXME: We should handle recursing on other vector shuffles and
11618     // scalar_to_vector here as well.
11619
11620     if (!LegalOperations) {
11621       EVT IndexTy = TLI.getVectorIdxTy();
11622       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11623                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11624     }
11625   }
11626
11627   bool BCNumEltsChanged = false;
11628   EVT ExtVT = VT.getVectorElementType();
11629   EVT LVT = ExtVT;
11630
11631   // If the result of load has to be truncated, then it's not necessarily
11632   // profitable.
11633   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11634     return SDValue();
11635
11636   if (InVec.getOpcode() == ISD::BITCAST) {
11637     // Don't duplicate a load with other uses.
11638     if (!InVec.hasOneUse())
11639       return SDValue();
11640
11641     EVT BCVT = InVec.getOperand(0).getValueType();
11642     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11643       return SDValue();
11644     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11645       BCNumEltsChanged = true;
11646     InVec = InVec.getOperand(0);
11647     ExtVT = BCVT.getVectorElementType();
11648   }
11649
11650   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11651   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11652       ISD::isNormalLoad(InVec.getNode()) &&
11653       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11654     SDValue Index = N->getOperand(1);
11655     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11656       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11657                                                            OrigLoad);
11658   }
11659
11660   // Perform only after legalization to ensure build_vector / vector_shuffle
11661   // optimizations have already been done.
11662   if (!LegalOperations) return SDValue();
11663
11664   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11665   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11666   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11667
11668   if (ConstEltNo) {
11669     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11670
11671     LoadSDNode *LN0 = nullptr;
11672     const ShuffleVectorSDNode *SVN = nullptr;
11673     if (ISD::isNormalLoad(InVec.getNode())) {
11674       LN0 = cast<LoadSDNode>(InVec);
11675     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11676                InVec.getOperand(0).getValueType() == ExtVT &&
11677                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11678       // Don't duplicate a load with other uses.
11679       if (!InVec.hasOneUse())
11680         return SDValue();
11681
11682       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11683     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11684       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11685       // =>
11686       // (load $addr+1*size)
11687
11688       // Don't duplicate a load with other uses.
11689       if (!InVec.hasOneUse())
11690         return SDValue();
11691
11692       // If the bit convert changed the number of elements, it is unsafe
11693       // to examine the mask.
11694       if (BCNumEltsChanged)
11695         return SDValue();
11696
11697       // Select the input vector, guarding against out of range extract vector.
11698       unsigned NumElems = VT.getVectorNumElements();
11699       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11700       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11701
11702       if (InVec.getOpcode() == ISD::BITCAST) {
11703         // Don't duplicate a load with other uses.
11704         if (!InVec.hasOneUse())
11705           return SDValue();
11706
11707         InVec = InVec.getOperand(0);
11708       }
11709       if (ISD::isNormalLoad(InVec.getNode())) {
11710         LN0 = cast<LoadSDNode>(InVec);
11711         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11712         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11713       }
11714     }
11715
11716     // Make sure we found a non-volatile load and the extractelement is
11717     // the only use.
11718     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11719       return SDValue();
11720
11721     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11722     if (Elt == -1)
11723       return DAG.getUNDEF(LVT);
11724
11725     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11726   }
11727
11728   return SDValue();
11729 }
11730
11731 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11732 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11733   // We perform this optimization post type-legalization because
11734   // the type-legalizer often scalarizes integer-promoted vectors.
11735   // Performing this optimization before may create bit-casts which
11736   // will be type-legalized to complex code sequences.
11737   // We perform this optimization only before the operation legalizer because we
11738   // may introduce illegal operations.
11739   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11740     return SDValue();
11741
11742   unsigned NumInScalars = N->getNumOperands();
11743   SDLoc dl(N);
11744   EVT VT = N->getValueType(0);
11745
11746   // Check to see if this is a BUILD_VECTOR of a bunch of values
11747   // which come from any_extend or zero_extend nodes. If so, we can create
11748   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11749   // optimizations. We do not handle sign-extend because we can't fill the sign
11750   // using shuffles.
11751   EVT SourceType = MVT::Other;
11752   bool AllAnyExt = true;
11753
11754   for (unsigned i = 0; i != NumInScalars; ++i) {
11755     SDValue In = N->getOperand(i);
11756     // Ignore undef inputs.
11757     if (In.getOpcode() == ISD::UNDEF) continue;
11758
11759     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11760     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11761
11762     // Abort if the element is not an extension.
11763     if (!ZeroExt && !AnyExt) {
11764       SourceType = MVT::Other;
11765       break;
11766     }
11767
11768     // The input is a ZeroExt or AnyExt. Check the original type.
11769     EVT InTy = In.getOperand(0).getValueType();
11770
11771     // Check that all of the widened source types are the same.
11772     if (SourceType == MVT::Other)
11773       // First time.
11774       SourceType = InTy;
11775     else if (InTy != SourceType) {
11776       // Multiple income types. Abort.
11777       SourceType = MVT::Other;
11778       break;
11779     }
11780
11781     // Check if all of the extends are ANY_EXTENDs.
11782     AllAnyExt &= AnyExt;
11783   }
11784
11785   // In order to have valid types, all of the inputs must be extended from the
11786   // same source type and all of the inputs must be any or zero extend.
11787   // Scalar sizes must be a power of two.
11788   EVT OutScalarTy = VT.getScalarType();
11789   bool ValidTypes = SourceType != MVT::Other &&
11790                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11791                  isPowerOf2_32(SourceType.getSizeInBits());
11792
11793   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11794   // turn into a single shuffle instruction.
11795   if (!ValidTypes)
11796     return SDValue();
11797
11798   bool isLE = TLI.isLittleEndian();
11799   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11800   assert(ElemRatio > 1 && "Invalid element size ratio");
11801   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11802                                DAG.getConstant(0, SDLoc(N), SourceType);
11803
11804   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11805   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11806
11807   // Populate the new build_vector
11808   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11809     SDValue Cast = N->getOperand(i);
11810     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11811             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11812             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11813     SDValue In;
11814     if (Cast.getOpcode() == ISD::UNDEF)
11815       In = DAG.getUNDEF(SourceType);
11816     else
11817       In = Cast->getOperand(0);
11818     unsigned Index = isLE ? (i * ElemRatio) :
11819                             (i * ElemRatio + (ElemRatio - 1));
11820
11821     assert(Index < Ops.size() && "Invalid index");
11822     Ops[Index] = In;
11823   }
11824
11825   // The type of the new BUILD_VECTOR node.
11826   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11827   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11828          "Invalid vector size");
11829   // Check if the new vector type is legal.
11830   if (!isTypeLegal(VecVT)) return SDValue();
11831
11832   // Make the new BUILD_VECTOR.
11833   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11834
11835   // The new BUILD_VECTOR node has the potential to be further optimized.
11836   AddToWorklist(BV.getNode());
11837   // Bitcast to the desired type.
11838   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11839 }
11840
11841 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11842   EVT VT = N->getValueType(0);
11843
11844   unsigned NumInScalars = N->getNumOperands();
11845   SDLoc dl(N);
11846
11847   EVT SrcVT = MVT::Other;
11848   unsigned Opcode = ISD::DELETED_NODE;
11849   unsigned NumDefs = 0;
11850
11851   for (unsigned i = 0; i != NumInScalars; ++i) {
11852     SDValue In = N->getOperand(i);
11853     unsigned Opc = In.getOpcode();
11854
11855     if (Opc == ISD::UNDEF)
11856       continue;
11857
11858     // If all scalar values are floats and converted from integers.
11859     if (Opcode == ISD::DELETED_NODE &&
11860         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11861       Opcode = Opc;
11862     }
11863
11864     if (Opc != Opcode)
11865       return SDValue();
11866
11867     EVT InVT = In.getOperand(0).getValueType();
11868
11869     // If all scalar values are typed differently, bail out. It's chosen to
11870     // simplify BUILD_VECTOR of integer types.
11871     if (SrcVT == MVT::Other)
11872       SrcVT = InVT;
11873     if (SrcVT != InVT)
11874       return SDValue();
11875     NumDefs++;
11876   }
11877
11878   // If the vector has just one element defined, it's not worth to fold it into
11879   // a vectorized one.
11880   if (NumDefs < 2)
11881     return SDValue();
11882
11883   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11884          && "Should only handle conversion from integer to float.");
11885   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11886
11887   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11888
11889   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11890     return SDValue();
11891
11892   // Just because the floating-point vector type is legal does not necessarily
11893   // mean that the corresponding integer vector type is.
11894   if (!isTypeLegal(NVT))
11895     return SDValue();
11896
11897   SmallVector<SDValue, 8> Opnds;
11898   for (unsigned i = 0; i != NumInScalars; ++i) {
11899     SDValue In = N->getOperand(i);
11900
11901     if (In.getOpcode() == ISD::UNDEF)
11902       Opnds.push_back(DAG.getUNDEF(SrcVT));
11903     else
11904       Opnds.push_back(In.getOperand(0));
11905   }
11906   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11907   AddToWorklist(BV.getNode());
11908
11909   return DAG.getNode(Opcode, dl, VT, BV);
11910 }
11911
11912 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11913   unsigned NumInScalars = N->getNumOperands();
11914   SDLoc dl(N);
11915   EVT VT = N->getValueType(0);
11916
11917   // A vector built entirely of undefs is undef.
11918   if (ISD::allOperandsUndef(N))
11919     return DAG.getUNDEF(VT);
11920
11921   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11922     return V;
11923
11924   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11925     return V;
11926
11927   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11928   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11929   // at most two distinct vectors, turn this into a shuffle node.
11930
11931   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11932   if (!isTypeLegal(VT))
11933     return SDValue();
11934
11935   // May only combine to shuffle after legalize if shuffle is legal.
11936   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11937     return SDValue();
11938
11939   SDValue VecIn1, VecIn2;
11940   bool UsesZeroVector = false;
11941   for (unsigned i = 0; i != NumInScalars; ++i) {
11942     SDValue Op = N->getOperand(i);
11943     // Ignore undef inputs.
11944     if (Op.getOpcode() == ISD::UNDEF) continue;
11945
11946     // See if we can combine this build_vector into a blend with a zero vector.
11947     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11948       UsesZeroVector = true;
11949       continue;
11950     }
11951
11952     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11953     // constant index, bail out.
11954     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11955         !isa<ConstantSDNode>(Op.getOperand(1))) {
11956       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11957       break;
11958     }
11959
11960     // We allow up to two distinct input vectors.
11961     SDValue ExtractedFromVec = Op.getOperand(0);
11962     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11963       continue;
11964
11965     if (!VecIn1.getNode()) {
11966       VecIn1 = ExtractedFromVec;
11967     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11968       VecIn2 = ExtractedFromVec;
11969     } else {
11970       // Too many inputs.
11971       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11972       break;
11973     }
11974   }
11975
11976   // If everything is good, we can make a shuffle operation.
11977   if (VecIn1.getNode()) {
11978     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11979     SmallVector<int, 8> Mask;
11980     for (unsigned i = 0; i != NumInScalars; ++i) {
11981       unsigned Opcode = N->getOperand(i).getOpcode();
11982       if (Opcode == ISD::UNDEF) {
11983         Mask.push_back(-1);
11984         continue;
11985       }
11986
11987       // Operands can also be zero.
11988       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11989         assert(UsesZeroVector &&
11990                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11991                "Unexpected node found!");
11992         Mask.push_back(NumInScalars+i);
11993         continue;
11994       }
11995
11996       // If extracting from the first vector, just use the index directly.
11997       SDValue Extract = N->getOperand(i);
11998       SDValue ExtVal = Extract.getOperand(1);
11999       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12000       if (Extract.getOperand(0) == VecIn1) {
12001         Mask.push_back(ExtIndex);
12002         continue;
12003       }
12004
12005       // Otherwise, use InIdx + InputVecSize
12006       Mask.push_back(InNumElements + ExtIndex);
12007     }
12008
12009     // Avoid introducing illegal shuffles with zero.
12010     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12011       return SDValue();
12012
12013     // We can't generate a shuffle node with mismatched input and output types.
12014     // Attempt to transform a single input vector to the correct type.
12015     if ((VT != VecIn1.getValueType())) {
12016       // If the input vector type has a different base type to the output
12017       // vector type, bail out.
12018       EVT VTElemType = VT.getVectorElementType();
12019       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12020           (VecIn2.getNode() &&
12021            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12022         return SDValue();
12023
12024       // If the input vector is too small, widen it.
12025       // We only support widening of vectors which are half the size of the
12026       // output registers. For example XMM->YMM widening on X86 with AVX.
12027       EVT VecInT = VecIn1.getValueType();
12028       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12029         // If we only have one small input, widen it by adding undef values.
12030         if (!VecIn2.getNode())
12031           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12032                                DAG.getUNDEF(VecIn1.getValueType()));
12033         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12034           // If we have two small inputs of the same type, try to concat them.
12035           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12036           VecIn2 = SDValue(nullptr, 0);
12037         } else
12038           return SDValue();
12039       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12040         // If the input vector is too large, try to split it.
12041         // We don't support having two input vectors that are too large.
12042         // If the zero vector was used, we can not split the vector,
12043         // since we'd need 3 inputs.
12044         if (UsesZeroVector || VecIn2.getNode())
12045           return SDValue();
12046
12047         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12048           return SDValue();
12049
12050         // Try to replace VecIn1 with two extract_subvectors
12051         // No need to update the masks, they should still be correct.
12052         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12053           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12054         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12055           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12056       } else
12057         return SDValue();
12058     }
12059
12060     if (UsesZeroVector)
12061       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12062                                 DAG.getConstantFP(0.0, dl, VT);
12063     else
12064       // If VecIn2 is unused then change it to undef.
12065       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12066
12067     // Check that we were able to transform all incoming values to the same
12068     // type.
12069     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12070         VecIn1.getValueType() != VT)
12071           return SDValue();
12072
12073     // Return the new VECTOR_SHUFFLE node.
12074     SDValue Ops[2];
12075     Ops[0] = VecIn1;
12076     Ops[1] = VecIn2;
12077     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12078   }
12079
12080   return SDValue();
12081 }
12082
12083 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12085   EVT OpVT = N->getOperand(0).getValueType();
12086
12087   // If the operands are legal vectors, leave them alone.
12088   if (TLI.isTypeLegal(OpVT))
12089     return SDValue();
12090
12091   SDLoc DL(N);
12092   EVT VT = N->getValueType(0);
12093   SmallVector<SDValue, 8> Ops;
12094
12095   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12096   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12097
12098   // Keep track of what we encounter.
12099   bool AnyInteger = false;
12100   bool AnyFP = false;
12101   for (const SDValue &Op : N->ops()) {
12102     if (ISD::BITCAST == Op.getOpcode() &&
12103         !Op.getOperand(0).getValueType().isVector())
12104       Ops.push_back(Op.getOperand(0));
12105     else if (ISD::UNDEF == Op.getOpcode())
12106       Ops.push_back(ScalarUndef);
12107     else
12108       return SDValue();
12109
12110     // Note whether we encounter an integer or floating point scalar.
12111     // If it's neither, bail out, it could be something weird like x86mmx.
12112     EVT LastOpVT = Ops.back().getValueType();
12113     if (LastOpVT.isFloatingPoint())
12114       AnyFP = true;
12115     else if (LastOpVT.isInteger())
12116       AnyInteger = true;
12117     else
12118       return SDValue();
12119   }
12120
12121   // If any of the operands is a floating point scalar bitcast to a vector,
12122   // use floating point types throughout, and bitcast everything.
12123   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12124   if (AnyFP) {
12125     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12126     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12127     if (AnyInteger) {
12128       for (SDValue &Op : Ops) {
12129         if (Op.getValueType() == SVT)
12130           continue;
12131         if (Op.getOpcode() == ISD::UNDEF)
12132           Op = ScalarUndef;
12133         else
12134           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12135       }
12136     }
12137   }
12138
12139   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12140                                VT.getSizeInBits() / SVT.getSizeInBits());
12141   return DAG.getNode(ISD::BITCAST, DL, VT,
12142                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12143 }
12144
12145 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12146   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12147   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12148   // inputs come from at most two distinct vectors, turn this into a shuffle
12149   // node.
12150
12151   // If we only have one input vector, we don't need to do any concatenation.
12152   if (N->getNumOperands() == 1)
12153     return N->getOperand(0);
12154
12155   // Check if all of the operands are undefs.
12156   EVT VT = N->getValueType(0);
12157   if (ISD::allOperandsUndef(N))
12158     return DAG.getUNDEF(VT);
12159
12160   // Optimize concat_vectors where all but the first of the vectors are undef.
12161   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12162         return Op.getOpcode() == ISD::UNDEF;
12163       })) {
12164     SDValue In = N->getOperand(0);
12165     assert(In.getValueType().isVector() && "Must concat vectors");
12166
12167     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12168     if (In->getOpcode() == ISD::BITCAST &&
12169         !In->getOperand(0)->getValueType(0).isVector()) {
12170       SDValue Scalar = In->getOperand(0);
12171
12172       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12173       // look through the trunc so we can still do the transform:
12174       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12175       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12176           !TLI.isTypeLegal(Scalar.getValueType()) &&
12177           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12178         Scalar = Scalar->getOperand(0);
12179
12180       EVT SclTy = Scalar->getValueType(0);
12181
12182       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12183         return SDValue();
12184
12185       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12186                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12187       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12188         return SDValue();
12189
12190       SDLoc dl = SDLoc(N);
12191       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12192       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12193     }
12194   }
12195
12196   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12197   // We have already tested above for an UNDEF only concatenation.
12198   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12199   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12200   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12201     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12202   };
12203   bool AllBuildVectorsOrUndefs =
12204       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12205   if (AllBuildVectorsOrUndefs) {
12206     SmallVector<SDValue, 8> Opnds;
12207     EVT SVT = VT.getScalarType();
12208
12209     EVT MinVT = SVT;
12210     if (!SVT.isFloatingPoint()) {
12211       // If BUILD_VECTOR are from built from integer, they may have different
12212       // operand types. Get the smallest type and truncate all operands to it.
12213       bool FoundMinVT = false;
12214       for (const SDValue &Op : N->ops())
12215         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12216           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12217           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12218           FoundMinVT = true;
12219         }
12220       assert(FoundMinVT && "Concat vector type mismatch");
12221     }
12222
12223     for (const SDValue &Op : N->ops()) {
12224       EVT OpVT = Op.getValueType();
12225       unsigned NumElts = OpVT.getVectorNumElements();
12226
12227       if (ISD::UNDEF == Op.getOpcode())
12228         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12229
12230       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12231         if (SVT.isFloatingPoint()) {
12232           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12233           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12234         } else {
12235           for (unsigned i = 0; i != NumElts; ++i)
12236             Opnds.push_back(
12237                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12238         }
12239       }
12240     }
12241
12242     assert(VT.getVectorNumElements() == Opnds.size() &&
12243            "Concat vector type mismatch");
12244     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12245   }
12246
12247   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12248   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12249     return V;
12250
12251   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12252   // nodes often generate nop CONCAT_VECTOR nodes.
12253   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12254   // place the incoming vectors at the exact same location.
12255   SDValue SingleSource = SDValue();
12256   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12257
12258   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12259     SDValue Op = N->getOperand(i);
12260
12261     if (Op.getOpcode() == ISD::UNDEF)
12262       continue;
12263
12264     // Check if this is the identity extract:
12265     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12266       return SDValue();
12267
12268     // Find the single incoming vector for the extract_subvector.
12269     if (SingleSource.getNode()) {
12270       if (Op.getOperand(0) != SingleSource)
12271         return SDValue();
12272     } else {
12273       SingleSource = Op.getOperand(0);
12274
12275       // Check the source type is the same as the type of the result.
12276       // If not, this concat may extend the vector, so we can not
12277       // optimize it away.
12278       if (SingleSource.getValueType() != N->getValueType(0))
12279         return SDValue();
12280     }
12281
12282     unsigned IdentityIndex = i * PartNumElem;
12283     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12284     // The extract index must be constant.
12285     if (!CS)
12286       return SDValue();
12287
12288     // Check that we are reading from the identity index.
12289     if (CS->getZExtValue() != IdentityIndex)
12290       return SDValue();
12291   }
12292
12293   if (SingleSource.getNode())
12294     return SingleSource;
12295
12296   return SDValue();
12297 }
12298
12299 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12300   EVT NVT = N->getValueType(0);
12301   SDValue V = N->getOperand(0);
12302
12303   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12304     // Combine:
12305     //    (extract_subvec (concat V1, V2, ...), i)
12306     // Into:
12307     //    Vi if possible
12308     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12309     // type.
12310     if (V->getOperand(0).getValueType() != NVT)
12311       return SDValue();
12312     unsigned Idx = N->getConstantOperandVal(1);
12313     unsigned NumElems = NVT.getVectorNumElements();
12314     assert((Idx % NumElems) == 0 &&
12315            "IDX in concat is not a multiple of the result vector length.");
12316     return V->getOperand(Idx / NumElems);
12317   }
12318
12319   // Skip bitcasting
12320   if (V->getOpcode() == ISD::BITCAST)
12321     V = V.getOperand(0);
12322
12323   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12324     SDLoc dl(N);
12325     // Handle only simple case where vector being inserted and vector
12326     // being extracted are of same type, and are half size of larger vectors.
12327     EVT BigVT = V->getOperand(0).getValueType();
12328     EVT SmallVT = V->getOperand(1).getValueType();
12329     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12330       return SDValue();
12331
12332     // Only handle cases where both indexes are constants with the same type.
12333     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12334     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12335
12336     if (InsIdx && ExtIdx &&
12337         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12338         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12339       // Combine:
12340       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12341       // Into:
12342       //    indices are equal or bit offsets are equal => V1
12343       //    otherwise => (extract_subvec V1, ExtIdx)
12344       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12345           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12346         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12347       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12348                          DAG.getNode(ISD::BITCAST, dl,
12349                                      N->getOperand(0).getValueType(),
12350                                      V->getOperand(0)), N->getOperand(1));
12351     }
12352   }
12353
12354   return SDValue();
12355 }
12356
12357 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12358                                                  SDValue V, SelectionDAG &DAG) {
12359   SDLoc DL(V);
12360   EVT VT = V.getValueType();
12361
12362   switch (V.getOpcode()) {
12363   default:
12364     return V;
12365
12366   case ISD::CONCAT_VECTORS: {
12367     EVT OpVT = V->getOperand(0).getValueType();
12368     int OpSize = OpVT.getVectorNumElements();
12369     SmallBitVector OpUsedElements(OpSize, false);
12370     bool FoundSimplification = false;
12371     SmallVector<SDValue, 4> NewOps;
12372     NewOps.reserve(V->getNumOperands());
12373     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12374       SDValue Op = V->getOperand(i);
12375       bool OpUsed = false;
12376       for (int j = 0; j < OpSize; ++j)
12377         if (UsedElements[i * OpSize + j]) {
12378           OpUsedElements[j] = true;
12379           OpUsed = true;
12380         }
12381       NewOps.push_back(
12382           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12383                  : DAG.getUNDEF(OpVT));
12384       FoundSimplification |= Op == NewOps.back();
12385       OpUsedElements.reset();
12386     }
12387     if (FoundSimplification)
12388       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12389     return V;
12390   }
12391
12392   case ISD::INSERT_SUBVECTOR: {
12393     SDValue BaseV = V->getOperand(0);
12394     SDValue SubV = V->getOperand(1);
12395     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12396     if (!IdxN)
12397       return V;
12398
12399     int SubSize = SubV.getValueType().getVectorNumElements();
12400     int Idx = IdxN->getZExtValue();
12401     bool SubVectorUsed = false;
12402     SmallBitVector SubUsedElements(SubSize, false);
12403     for (int i = 0; i < SubSize; ++i)
12404       if (UsedElements[i + Idx]) {
12405         SubVectorUsed = true;
12406         SubUsedElements[i] = true;
12407         UsedElements[i + Idx] = false;
12408       }
12409
12410     // Now recurse on both the base and sub vectors.
12411     SDValue SimplifiedSubV =
12412         SubVectorUsed
12413             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12414             : DAG.getUNDEF(SubV.getValueType());
12415     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12416     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12417       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12418                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12419     return V;
12420   }
12421   }
12422 }
12423
12424 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12425                                        SDValue N1, SelectionDAG &DAG) {
12426   EVT VT = SVN->getValueType(0);
12427   int NumElts = VT.getVectorNumElements();
12428   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12429   for (int M : SVN->getMask())
12430     if (M >= 0 && M < NumElts)
12431       N0UsedElements[M] = true;
12432     else if (M >= NumElts)
12433       N1UsedElements[M - NumElts] = true;
12434
12435   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12436   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12437   if (S0 == N0 && S1 == N1)
12438     return SDValue();
12439
12440   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12441 }
12442
12443 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12444 // or turn a shuffle of a single concat into simpler shuffle then concat.
12445 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12446   EVT VT = N->getValueType(0);
12447   unsigned NumElts = VT.getVectorNumElements();
12448
12449   SDValue N0 = N->getOperand(0);
12450   SDValue N1 = N->getOperand(1);
12451   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12452
12453   SmallVector<SDValue, 4> Ops;
12454   EVT ConcatVT = N0.getOperand(0).getValueType();
12455   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12456   unsigned NumConcats = NumElts / NumElemsPerConcat;
12457
12458   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12459   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12460   // half vector elements.
12461   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12462       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12463                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12464     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12465                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12466     N1 = DAG.getUNDEF(ConcatVT);
12467     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12468   }
12469
12470   // Look at every vector that's inserted. We're looking for exact
12471   // subvector-sized copies from a concatenated vector
12472   for (unsigned I = 0; I != NumConcats; ++I) {
12473     // Make sure we're dealing with a copy.
12474     unsigned Begin = I * NumElemsPerConcat;
12475     bool AllUndef = true, NoUndef = true;
12476     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12477       if (SVN->getMaskElt(J) >= 0)
12478         AllUndef = false;
12479       else
12480         NoUndef = false;
12481     }
12482
12483     if (NoUndef) {
12484       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12485         return SDValue();
12486
12487       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12488         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12489           return SDValue();
12490
12491       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12492       if (FirstElt < N0.getNumOperands())
12493         Ops.push_back(N0.getOperand(FirstElt));
12494       else
12495         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12496
12497     } else if (AllUndef) {
12498       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12499     } else { // Mixed with general masks and undefs, can't do optimization.
12500       return SDValue();
12501     }
12502   }
12503
12504   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12505 }
12506
12507 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12508   EVT VT = N->getValueType(0);
12509   unsigned NumElts = VT.getVectorNumElements();
12510
12511   SDValue N0 = N->getOperand(0);
12512   SDValue N1 = N->getOperand(1);
12513
12514   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12515
12516   // Canonicalize shuffle undef, undef -> undef
12517   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12518     return DAG.getUNDEF(VT);
12519
12520   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12521
12522   // Canonicalize shuffle v, v -> v, undef
12523   if (N0 == N1) {
12524     SmallVector<int, 8> NewMask;
12525     for (unsigned i = 0; i != NumElts; ++i) {
12526       int Idx = SVN->getMaskElt(i);
12527       if (Idx >= (int)NumElts) Idx -= NumElts;
12528       NewMask.push_back(Idx);
12529     }
12530     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12531                                 &NewMask[0]);
12532   }
12533
12534   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12535   if (N0.getOpcode() == ISD::UNDEF) {
12536     SmallVector<int, 8> NewMask;
12537     for (unsigned i = 0; i != NumElts; ++i) {
12538       int Idx = SVN->getMaskElt(i);
12539       if (Idx >= 0) {
12540         if (Idx >= (int)NumElts)
12541           Idx -= NumElts;
12542         else
12543           Idx = -1; // remove reference to lhs
12544       }
12545       NewMask.push_back(Idx);
12546     }
12547     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12548                                 &NewMask[0]);
12549   }
12550
12551   // Remove references to rhs if it is undef
12552   if (N1.getOpcode() == ISD::UNDEF) {
12553     bool Changed = false;
12554     SmallVector<int, 8> NewMask;
12555     for (unsigned i = 0; i != NumElts; ++i) {
12556       int Idx = SVN->getMaskElt(i);
12557       if (Idx >= (int)NumElts) {
12558         Idx = -1;
12559         Changed = true;
12560       }
12561       NewMask.push_back(Idx);
12562     }
12563     if (Changed)
12564       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12565   }
12566
12567   // If it is a splat, check if the argument vector is another splat or a
12568   // build_vector.
12569   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12570     SDNode *V = N0.getNode();
12571
12572     // If this is a bit convert that changes the element type of the vector but
12573     // not the number of vector elements, look through it.  Be careful not to
12574     // look though conversions that change things like v4f32 to v2f64.
12575     if (V->getOpcode() == ISD::BITCAST) {
12576       SDValue ConvInput = V->getOperand(0);
12577       if (ConvInput.getValueType().isVector() &&
12578           ConvInput.getValueType().getVectorNumElements() == NumElts)
12579         V = ConvInput.getNode();
12580     }
12581
12582     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12583       assert(V->getNumOperands() == NumElts &&
12584              "BUILD_VECTOR has wrong number of operands");
12585       SDValue Base;
12586       bool AllSame = true;
12587       for (unsigned i = 0; i != NumElts; ++i) {
12588         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12589           Base = V->getOperand(i);
12590           break;
12591         }
12592       }
12593       // Splat of <u, u, u, u>, return <u, u, u, u>
12594       if (!Base.getNode())
12595         return N0;
12596       for (unsigned i = 0; i != NumElts; ++i) {
12597         if (V->getOperand(i) != Base) {
12598           AllSame = false;
12599           break;
12600         }
12601       }
12602       // Splat of <x, x, x, x>, return <x, x, x, x>
12603       if (AllSame)
12604         return N0;
12605
12606       // Canonicalize any other splat as a build_vector.
12607       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12608       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12609       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12610                                   V->getValueType(0), Ops);
12611
12612       // We may have jumped through bitcasts, so the type of the
12613       // BUILD_VECTOR may not match the type of the shuffle.
12614       if (V->getValueType(0) != VT)
12615         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12616       return NewBV;
12617     }
12618   }
12619
12620   // There are various patterns used to build up a vector from smaller vectors,
12621   // subvectors, or elements. Scan chains of these and replace unused insertions
12622   // or components with undef.
12623   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12624     return S;
12625
12626   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12627       Level < AfterLegalizeVectorOps &&
12628       (N1.getOpcode() == ISD::UNDEF ||
12629       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12630        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12631     SDValue V = partitionShuffleOfConcats(N, DAG);
12632
12633     if (V.getNode())
12634       return V;
12635   }
12636
12637   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12638   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12639   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12640     SmallVector<SDValue, 8> Ops;
12641     for (int M : SVN->getMask()) {
12642       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12643       if (M >= 0) {
12644         int Idx = M % NumElts;
12645         SDValue &S = (M < (int)NumElts ? N0 : N1);
12646         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12647           Op = S.getOperand(Idx);
12648         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12649           if (Idx == 0)
12650             Op = S.getOperand(0);
12651         } else {
12652           // Operand can't be combined - bail out.
12653           break;
12654         }
12655       }
12656       Ops.push_back(Op);
12657     }
12658     if (Ops.size() == VT.getVectorNumElements()) {
12659       // BUILD_VECTOR requires all inputs to be of the same type, find the
12660       // maximum type and extend them all.
12661       EVT SVT = VT.getScalarType();
12662       if (SVT.isInteger())
12663         for (SDValue &Op : Ops)
12664           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12665       if (SVT != VT.getScalarType())
12666         for (SDValue &Op : Ops)
12667           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12668                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12669                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12670       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12671     }
12672   }
12673
12674   // If this shuffle only has a single input that is a bitcasted shuffle,
12675   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12676   // back to their original types.
12677   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12678       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12679       TLI.isTypeLegal(VT)) {
12680
12681     // Peek through the bitcast only if there is one user.
12682     SDValue BC0 = N0;
12683     while (BC0.getOpcode() == ISD::BITCAST) {
12684       if (!BC0.hasOneUse())
12685         break;
12686       BC0 = BC0.getOperand(0);
12687     }
12688
12689     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12690       if (Scale == 1)
12691         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12692
12693       SmallVector<int, 8> NewMask;
12694       for (int M : Mask)
12695         for (int s = 0; s != Scale; ++s)
12696           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12697       return NewMask;
12698     };
12699
12700     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12701       EVT SVT = VT.getScalarType();
12702       EVT InnerVT = BC0->getValueType(0);
12703       EVT InnerSVT = InnerVT.getScalarType();
12704
12705       // Determine which shuffle works with the smaller scalar type.
12706       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12707       EVT ScaleSVT = ScaleVT.getScalarType();
12708
12709       if (TLI.isTypeLegal(ScaleVT) &&
12710           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12711           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12712
12713         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12714         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12715
12716         // Scale the shuffle masks to the smaller scalar type.
12717         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12718         SmallVector<int, 8> InnerMask =
12719             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12720         SmallVector<int, 8> OuterMask =
12721             ScaleShuffleMask(SVN->getMask(), OuterScale);
12722
12723         // Merge the shuffle masks.
12724         SmallVector<int, 8> NewMask;
12725         for (int M : OuterMask)
12726           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12727
12728         // Test for shuffle mask legality over both commutations.
12729         SDValue SV0 = BC0->getOperand(0);
12730         SDValue SV1 = BC0->getOperand(1);
12731         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12732         if (!LegalMask) {
12733           std::swap(SV0, SV1);
12734           ShuffleVectorSDNode::commuteMask(NewMask);
12735           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12736         }
12737
12738         if (LegalMask) {
12739           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12740           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12741           return DAG.getNode(
12742               ISD::BITCAST, SDLoc(N), VT,
12743               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12744         }
12745       }
12746     }
12747   }
12748
12749   // Canonicalize shuffles according to rules:
12750   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12751   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12752   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12753   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12754       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12755       TLI.isTypeLegal(VT)) {
12756     // The incoming shuffle must be of the same type as the result of the
12757     // current shuffle.
12758     assert(N1->getOperand(0).getValueType() == VT &&
12759            "Shuffle types don't match");
12760
12761     SDValue SV0 = N1->getOperand(0);
12762     SDValue SV1 = N1->getOperand(1);
12763     bool HasSameOp0 = N0 == SV0;
12764     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12765     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12766       // Commute the operands of this shuffle so that next rule
12767       // will trigger.
12768       return DAG.getCommutedVectorShuffle(*SVN);
12769   }
12770
12771   // Try to fold according to rules:
12772   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12773   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12774   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12775   // Don't try to fold shuffles with illegal type.
12776   // Only fold if this shuffle is the only user of the other shuffle.
12777   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12778       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12779     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12780
12781     // The incoming shuffle must be of the same type as the result of the
12782     // current shuffle.
12783     assert(OtherSV->getOperand(0).getValueType() == VT &&
12784            "Shuffle types don't match");
12785
12786     SDValue SV0, SV1;
12787     SmallVector<int, 4> Mask;
12788     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12789     // operand, and SV1 as the second operand.
12790     for (unsigned i = 0; i != NumElts; ++i) {
12791       int Idx = SVN->getMaskElt(i);
12792       if (Idx < 0) {
12793         // Propagate Undef.
12794         Mask.push_back(Idx);
12795         continue;
12796       }
12797
12798       SDValue CurrentVec;
12799       if (Idx < (int)NumElts) {
12800         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12801         // shuffle mask to identify which vector is actually referenced.
12802         Idx = OtherSV->getMaskElt(Idx);
12803         if (Idx < 0) {
12804           // Propagate Undef.
12805           Mask.push_back(Idx);
12806           continue;
12807         }
12808
12809         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12810                                            : OtherSV->getOperand(1);
12811       } else {
12812         // This shuffle index references an element within N1.
12813         CurrentVec = N1;
12814       }
12815
12816       // Simple case where 'CurrentVec' is UNDEF.
12817       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12818         Mask.push_back(-1);
12819         continue;
12820       }
12821
12822       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12823       // will be the first or second operand of the combined shuffle.
12824       Idx = Idx % NumElts;
12825       if (!SV0.getNode() || SV0 == CurrentVec) {
12826         // Ok. CurrentVec is the left hand side.
12827         // Update the mask accordingly.
12828         SV0 = CurrentVec;
12829         Mask.push_back(Idx);
12830         continue;
12831       }
12832
12833       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12834       if (SV1.getNode() && SV1 != CurrentVec)
12835         return SDValue();
12836
12837       // Ok. CurrentVec is the right hand side.
12838       // Update the mask accordingly.
12839       SV1 = CurrentVec;
12840       Mask.push_back(Idx + NumElts);
12841     }
12842
12843     // Check if all indices in Mask are Undef. In case, propagate Undef.
12844     bool isUndefMask = true;
12845     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12846       isUndefMask &= Mask[i] < 0;
12847
12848     if (isUndefMask)
12849       return DAG.getUNDEF(VT);
12850
12851     if (!SV0.getNode())
12852       SV0 = DAG.getUNDEF(VT);
12853     if (!SV1.getNode())
12854       SV1 = DAG.getUNDEF(VT);
12855
12856     // Avoid introducing shuffles with illegal mask.
12857     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12858       ShuffleVectorSDNode::commuteMask(Mask);
12859
12860       if (!TLI.isShuffleMaskLegal(Mask, VT))
12861         return SDValue();
12862
12863       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12864       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12865       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12866       std::swap(SV0, SV1);
12867     }
12868
12869     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12870     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12871     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12872     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12873   }
12874
12875   return SDValue();
12876 }
12877
12878 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12879   SDValue InVal = N->getOperand(0);
12880   EVT VT = N->getValueType(0);
12881
12882   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12883   // with a VECTOR_SHUFFLE.
12884   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12885     SDValue InVec = InVal->getOperand(0);
12886     SDValue EltNo = InVal->getOperand(1);
12887
12888     // FIXME: We could support implicit truncation if the shuffle can be
12889     // scaled to a smaller vector scalar type.
12890     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12891     if (C0 && VT == InVec.getValueType() &&
12892         VT.getScalarType() == InVal.getValueType()) {
12893       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12894       int Elt = C0->getZExtValue();
12895       NewMask[0] = Elt;
12896
12897       if (TLI.isShuffleMaskLegal(NewMask, VT))
12898         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12899                                     NewMask);
12900     }
12901   }
12902
12903   return SDValue();
12904 }
12905
12906 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12907   SDValue N0 = N->getOperand(0);
12908   SDValue N2 = N->getOperand(2);
12909
12910   // If the input vector is a concatenation, and the insert replaces
12911   // one of the halves, we can optimize into a single concat_vectors.
12912   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12913       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12914     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12915     EVT VT = N->getValueType(0);
12916
12917     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12918     // (concat_vectors Z, Y)
12919     if (InsIdx == 0)
12920       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12921                          N->getOperand(1), N0.getOperand(1));
12922
12923     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12924     // (concat_vectors X, Z)
12925     if (InsIdx == VT.getVectorNumElements()/2)
12926       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12927                          N0.getOperand(0), N->getOperand(1));
12928   }
12929
12930   return SDValue();
12931 }
12932
12933 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12934   SDValue N0 = N->getOperand(0);
12935
12936   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12937   if (N0->getOpcode() == ISD::FP16_TO_FP)
12938     return N0->getOperand(0);
12939
12940   return SDValue();
12941 }
12942
12943 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12944 /// with the destination vector and a zero vector.
12945 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12946 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12947 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12948   EVT VT = N->getValueType(0);
12949   SDValue LHS = N->getOperand(0);
12950   SDValue RHS = N->getOperand(1);
12951   SDLoc dl(N);
12952
12953   // Make sure we're not running after operation legalization where it
12954   // may have custom lowered the vector shuffles.
12955   if (LegalOperations)
12956     return SDValue();
12957
12958   if (N->getOpcode() != ISD::AND)
12959     return SDValue();
12960
12961   if (RHS.getOpcode() == ISD::BITCAST)
12962     RHS = RHS.getOperand(0);
12963
12964   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12965     SmallVector<int, 8> Indices;
12966     unsigned NumElts = RHS.getNumOperands();
12967
12968     for (unsigned i = 0; i != NumElts; ++i) {
12969       SDValue Elt = RHS.getOperand(i);
12970       if (isAllOnesConstant(Elt))
12971         Indices.push_back(i);
12972       else if (isNullConstant(Elt))
12973         Indices.push_back(NumElts+i);
12974       else
12975         return SDValue();
12976     }
12977
12978     // Let's see if the target supports this vector_shuffle.
12979     EVT RVT = RHS.getValueType();
12980     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12981       return SDValue();
12982
12983     // Return the new VECTOR_SHUFFLE node.
12984     EVT EltVT = RVT.getVectorElementType();
12985     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12986                                    DAG.getConstant(0, dl, EltVT));
12987     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12988     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12989     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12990     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12991   }
12992
12993   return SDValue();
12994 }
12995
12996 /// Visit a binary vector operation, like ADD.
12997 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12998   assert(N->getValueType(0).isVector() &&
12999          "SimplifyVBinOp only works on vectors!");
13000
13001   SDValue LHS = N->getOperand(0);
13002   SDValue RHS = N->getOperand(1);
13003
13004   if (SDValue Shuffle = XformToShuffleWithZero(N))
13005     return Shuffle;
13006
13007   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13008   // this operation.
13009   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13010       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13011     // Check if both vectors are constants. If not bail out.
13012     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13013           cast<BuildVectorSDNode>(RHS)->isConstant()))
13014       return SDValue();
13015
13016     SmallVector<SDValue, 8> Ops;
13017     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13018       SDValue LHSOp = LHS.getOperand(i);
13019       SDValue RHSOp = RHS.getOperand(i);
13020
13021       // Can't fold divide by zero.
13022       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13023           N->getOpcode() == ISD::FDIV) {
13024         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13025              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13026           break;
13027       }
13028
13029       EVT VT = LHSOp.getValueType();
13030       EVT RVT = RHSOp.getValueType();
13031       if (RVT != VT) {
13032         // Integer BUILD_VECTOR operands may have types larger than the element
13033         // size (e.g., when the element type is not legal).  Prior to type
13034         // legalization, the types may not match between the two BUILD_VECTORS.
13035         // Truncate one of the operands to make them match.
13036         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13037           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13038         } else {
13039           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13040           VT = RVT;
13041         }
13042       }
13043       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13044                                    LHSOp, RHSOp);
13045       if (FoldOp.getOpcode() != ISD::UNDEF &&
13046           FoldOp.getOpcode() != ISD::Constant &&
13047           FoldOp.getOpcode() != ISD::ConstantFP)
13048         break;
13049       Ops.push_back(FoldOp);
13050       AddToWorklist(FoldOp.getNode());
13051     }
13052
13053     if (Ops.size() == LHS.getNumOperands())
13054       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13055   }
13056
13057   // Type legalization might introduce new shuffles in the DAG.
13058   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13059   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13060   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13061       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13062       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13063       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13064     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13065     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13066
13067     if (SVN0->getMask().equals(SVN1->getMask())) {
13068       EVT VT = N->getValueType(0);
13069       SDValue UndefVector = LHS.getOperand(1);
13070       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13071                                      LHS.getOperand(0), RHS.getOperand(0));
13072       AddUsersToWorklist(N);
13073       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13074                                   &SVN0->getMask()[0]);
13075     }
13076   }
13077
13078   return SDValue();
13079 }
13080
13081 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13082                                     SDValue N1, SDValue N2){
13083   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13084
13085   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13086                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13087
13088   // If we got a simplified select_cc node back from SimplifySelectCC, then
13089   // break it down into a new SETCC node, and a new SELECT node, and then return
13090   // the SELECT node, since we were called with a SELECT node.
13091   if (SCC.getNode()) {
13092     // Check to see if we got a select_cc back (to turn into setcc/select).
13093     // Otherwise, just return whatever node we got back, like fabs.
13094     if (SCC.getOpcode() == ISD::SELECT_CC) {
13095       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13096                                   N0.getValueType(),
13097                                   SCC.getOperand(0), SCC.getOperand(1),
13098                                   SCC.getOperand(4));
13099       AddToWorklist(SETCC.getNode());
13100       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13101                            SCC.getOperand(2), SCC.getOperand(3));
13102     }
13103
13104     return SCC;
13105   }
13106   return SDValue();
13107 }
13108
13109 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13110 /// being selected between, see if we can simplify the select.  Callers of this
13111 /// should assume that TheSelect is deleted if this returns true.  As such, they
13112 /// should return the appropriate thing (e.g. the node) back to the top-level of
13113 /// the DAG combiner loop to avoid it being looked at.
13114 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13115                                     SDValue RHS) {
13116
13117   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13118   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13119   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13120     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13121       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13122       SDValue Sqrt = RHS;
13123       ISD::CondCode CC;
13124       SDValue CmpLHS;
13125       const ConstantFPSDNode *NegZero = nullptr;
13126
13127       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13128         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13129         CmpLHS = TheSelect->getOperand(0);
13130         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13131       } else {
13132         // SELECT or VSELECT
13133         SDValue Cmp = TheSelect->getOperand(0);
13134         if (Cmp.getOpcode() == ISD::SETCC) {
13135           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13136           CmpLHS = Cmp.getOperand(0);
13137           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13138         }
13139       }
13140       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13141           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13142           CC == ISD::SETULT || CC == ISD::SETLT)) {
13143         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13144         CombineTo(TheSelect, Sqrt);
13145         return true;
13146       }
13147     }
13148   }
13149   // Cannot simplify select with vector condition
13150   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13151
13152   // If this is a select from two identical things, try to pull the operation
13153   // through the select.
13154   if (LHS.getOpcode() != RHS.getOpcode() ||
13155       !LHS.hasOneUse() || !RHS.hasOneUse())
13156     return false;
13157
13158   // If this is a load and the token chain is identical, replace the select
13159   // of two loads with a load through a select of the address to load from.
13160   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13161   // constants have been dropped into the constant pool.
13162   if (LHS.getOpcode() == ISD::LOAD) {
13163     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13164     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13165
13166     // Token chains must be identical.
13167     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13168         // Do not let this transformation reduce the number of volatile loads.
13169         LLD->isVolatile() || RLD->isVolatile() ||
13170         // FIXME: If either is a pre/post inc/dec load,
13171         // we'd need to split out the address adjustment.
13172         LLD->isIndexed() || RLD->isIndexed() ||
13173         // If this is an EXTLOAD, the VT's must match.
13174         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13175         // If this is an EXTLOAD, the kind of extension must match.
13176         (LLD->getExtensionType() != RLD->getExtensionType() &&
13177          // The only exception is if one of the extensions is anyext.
13178          LLD->getExtensionType() != ISD::EXTLOAD &&
13179          RLD->getExtensionType() != ISD::EXTLOAD) ||
13180         // FIXME: this discards src value information.  This is
13181         // over-conservative. It would be beneficial to be able to remember
13182         // both potential memory locations.  Since we are discarding
13183         // src value info, don't do the transformation if the memory
13184         // locations are not in the default address space.
13185         LLD->getPointerInfo().getAddrSpace() != 0 ||
13186         RLD->getPointerInfo().getAddrSpace() != 0 ||
13187         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13188                                       LLD->getBasePtr().getValueType()))
13189       return false;
13190
13191     // Check that the select condition doesn't reach either load.  If so,
13192     // folding this will induce a cycle into the DAG.  If not, this is safe to
13193     // xform, so create a select of the addresses.
13194     SDValue Addr;
13195     if (TheSelect->getOpcode() == ISD::SELECT) {
13196       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13197       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13198           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13199         return false;
13200       // The loads must not depend on one another.
13201       if (LLD->isPredecessorOf(RLD) ||
13202           RLD->isPredecessorOf(LLD))
13203         return false;
13204       Addr = DAG.getSelect(SDLoc(TheSelect),
13205                            LLD->getBasePtr().getValueType(),
13206                            TheSelect->getOperand(0), LLD->getBasePtr(),
13207                            RLD->getBasePtr());
13208     } else {  // Otherwise SELECT_CC
13209       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13210       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13211
13212       if ((LLD->hasAnyUseOfValue(1) &&
13213            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13214           (RLD->hasAnyUseOfValue(1) &&
13215            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13216         return false;
13217
13218       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13219                          LLD->getBasePtr().getValueType(),
13220                          TheSelect->getOperand(0),
13221                          TheSelect->getOperand(1),
13222                          LLD->getBasePtr(), RLD->getBasePtr(),
13223                          TheSelect->getOperand(4));
13224     }
13225
13226     SDValue Load;
13227     // It is safe to replace the two loads if they have different alignments,
13228     // but the new load must be the minimum (most restrictive) alignment of the
13229     // inputs.
13230     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13231     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13232     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13233       Load = DAG.getLoad(TheSelect->getValueType(0),
13234                          SDLoc(TheSelect),
13235                          // FIXME: Discards pointer and AA info.
13236                          LLD->getChain(), Addr, MachinePointerInfo(),
13237                          LLD->isVolatile(), LLD->isNonTemporal(),
13238                          isInvariant, Alignment);
13239     } else {
13240       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13241                             RLD->getExtensionType() : LLD->getExtensionType(),
13242                             SDLoc(TheSelect),
13243                             TheSelect->getValueType(0),
13244                             // FIXME: Discards pointer and AA info.
13245                             LLD->getChain(), Addr, MachinePointerInfo(),
13246                             LLD->getMemoryVT(), LLD->isVolatile(),
13247                             LLD->isNonTemporal(), isInvariant, Alignment);
13248     }
13249
13250     // Users of the select now use the result of the load.
13251     CombineTo(TheSelect, Load);
13252
13253     // Users of the old loads now use the new load's chain.  We know the
13254     // old-load value is dead now.
13255     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13256     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13257     return true;
13258   }
13259
13260   return false;
13261 }
13262
13263 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13264 /// where 'cond' is the comparison specified by CC.
13265 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13266                                       SDValue N2, SDValue N3,
13267                                       ISD::CondCode CC, bool NotExtCompare) {
13268   // (x ? y : y) -> y.
13269   if (N2 == N3) return N2;
13270
13271   EVT VT = N2.getValueType();
13272   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13273   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13274
13275   // Determine if the condition we're dealing with is constant
13276   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13277                               N0, N1, CC, DL, false);
13278   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13279
13280   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13281     // fold select_cc true, x, y -> x
13282     // fold select_cc false, x, y -> y
13283     return !SCCC->isNullValue() ? N2 : N3;
13284   }
13285
13286   // Check to see if we can simplify the select into an fabs node
13287   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13288     // Allow either -0.0 or 0.0
13289     if (CFP->isZero()) {
13290       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13291       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13292           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13293           N2 == N3.getOperand(0))
13294         return DAG.getNode(ISD::FABS, DL, VT, N0);
13295
13296       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13297       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13298           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13299           N2.getOperand(0) == N3)
13300         return DAG.getNode(ISD::FABS, DL, VT, N3);
13301     }
13302   }
13303
13304   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13305   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13306   // in it.  This is a win when the constant is not otherwise available because
13307   // it replaces two constant pool loads with one.  We only do this if the FP
13308   // type is known to be legal, because if it isn't, then we are before legalize
13309   // types an we want the other legalization to happen first (e.g. to avoid
13310   // messing with soft float) and if the ConstantFP is not legal, because if
13311   // it is legal, we may not need to store the FP constant in a constant pool.
13312   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13313     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13314       if (TLI.isTypeLegal(N2.getValueType()) &&
13315           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13316                TargetLowering::Legal &&
13317            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13318            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13319           // If both constants have multiple uses, then we won't need to do an
13320           // extra load, they are likely around in registers for other users.
13321           (TV->hasOneUse() || FV->hasOneUse())) {
13322         Constant *Elts[] = {
13323           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13324           const_cast<ConstantFP*>(TV->getConstantFPValue())
13325         };
13326         Type *FPTy = Elts[0]->getType();
13327         const DataLayout &TD = *TLI.getDataLayout();
13328
13329         // Create a ConstantArray of the two constants.
13330         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13331         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13332                                             TD.getPrefTypeAlignment(FPTy));
13333         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13334
13335         // Get the offsets to the 0 and 1 element of the array so that we can
13336         // select between them.
13337         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13338         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13339         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13340
13341         SDValue Cond = DAG.getSetCC(DL,
13342                                     getSetCCResultType(N0.getValueType()),
13343                                     N0, N1, CC);
13344         AddToWorklist(Cond.getNode());
13345         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13346                                           Cond, One, Zero);
13347         AddToWorklist(CstOffset.getNode());
13348         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13349                             CstOffset);
13350         AddToWorklist(CPIdx.getNode());
13351         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13352                            MachinePointerInfo::getConstantPool(), false,
13353                            false, false, Alignment);
13354       }
13355     }
13356
13357   // Check to see if we can perform the "gzip trick", transforming
13358   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13359   if (isNullConstant(N3) && CC == ISD::SETLT &&
13360       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13361        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13362     EVT XType = N0.getValueType();
13363     EVT AType = N2.getValueType();
13364     if (XType.bitsGE(AType)) {
13365       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13366       // single-bit constant.
13367       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13368         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13369         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13370         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13371                                        getShiftAmountTy(N0.getValueType()));
13372         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13373                                     XType, N0, ShCt);
13374         AddToWorklist(Shift.getNode());
13375
13376         if (XType.bitsGT(AType)) {
13377           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13378           AddToWorklist(Shift.getNode());
13379         }
13380
13381         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13382       }
13383
13384       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13385                                   XType, N0,
13386                                   DAG.getConstant(XType.getSizeInBits() - 1,
13387                                                   SDLoc(N0),
13388                                          getShiftAmountTy(N0.getValueType())));
13389       AddToWorklist(Shift.getNode());
13390
13391       if (XType.bitsGT(AType)) {
13392         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13393         AddToWorklist(Shift.getNode());
13394       }
13395
13396       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13397     }
13398   }
13399
13400   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13401   // where y is has a single bit set.
13402   // A plaintext description would be, we can turn the SELECT_CC into an AND
13403   // when the condition can be materialized as an all-ones register.  Any
13404   // single bit-test can be materialized as an all-ones register with
13405   // shift-left and shift-right-arith.
13406   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13407       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13408     SDValue AndLHS = N0->getOperand(0);
13409     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13410     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13411       // Shift the tested bit over the sign bit.
13412       APInt AndMask = ConstAndRHS->getAPIntValue();
13413       SDValue ShlAmt =
13414         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13415                         getShiftAmountTy(AndLHS.getValueType()));
13416       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13417
13418       // Now arithmetic right shift it all the way over, so the result is either
13419       // all-ones, or zero.
13420       SDValue ShrAmt =
13421         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13422                         getShiftAmountTy(Shl.getValueType()));
13423       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13424
13425       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13426     }
13427   }
13428
13429   // fold select C, 16, 0 -> shl C, 4
13430   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13431       TLI.getBooleanContents(N0.getValueType()) ==
13432           TargetLowering::ZeroOrOneBooleanContent) {
13433
13434     // If the caller doesn't want us to simplify this into a zext of a compare,
13435     // don't do it.
13436     if (NotExtCompare && N2C->isOne())
13437       return SDValue();
13438
13439     // Get a SetCC of the condition
13440     // NOTE: Don't create a SETCC if it's not legal on this target.
13441     if (!LegalOperations ||
13442         TLI.isOperationLegal(ISD::SETCC,
13443           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13444       SDValue Temp, SCC;
13445       // cast from setcc result type to select result type
13446       if (LegalTypes) {
13447         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13448                             N0, N1, CC);
13449         if (N2.getValueType().bitsLT(SCC.getValueType()))
13450           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13451                                         N2.getValueType());
13452         else
13453           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13454                              N2.getValueType(), SCC);
13455       } else {
13456         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13457         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13458                            N2.getValueType(), SCC);
13459       }
13460
13461       AddToWorklist(SCC.getNode());
13462       AddToWorklist(Temp.getNode());
13463
13464       if (N2C->isOne())
13465         return Temp;
13466
13467       // shl setcc result by log2 n2c
13468       return DAG.getNode(
13469           ISD::SHL, DL, N2.getValueType(), Temp,
13470           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13471                           getShiftAmountTy(Temp.getValueType())));
13472     }
13473   }
13474
13475   // Check to see if this is the equivalent of setcc
13476   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13477   // otherwise, go ahead with the folds.
13478   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13479     EVT XType = N0.getValueType();
13480     if (!LegalOperations ||
13481         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13482       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13483       if (Res.getValueType() != VT)
13484         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13485       return Res;
13486     }
13487
13488     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13489     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13490         (!LegalOperations ||
13491          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13492       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13493       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13494                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13495                                          SDLoc(Ctlz),
13496                                        getShiftAmountTy(Ctlz.getValueType())));
13497     }
13498     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13499     if (isNullConstant(N1) && CC == ISD::SETGT) {
13500       SDLoc DL(N0);
13501       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13502                                   XType, DAG.getConstant(0, DL, XType), N0);
13503       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13504       return DAG.getNode(ISD::SRL, DL, XType,
13505                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13506                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13507                                          getShiftAmountTy(XType)));
13508     }
13509     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13510     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13511       SDLoc DL(N0);
13512       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13513                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13514                                          getShiftAmountTy(N0.getValueType())));
13515       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13516                                                                     XType));
13517     }
13518   }
13519
13520   // Check to see if this is an integer abs.
13521   // select_cc setg[te] X,  0,  X, -X ->
13522   // select_cc setgt    X, -1,  X, -X ->
13523   // select_cc setl[te] X,  0, -X,  X ->
13524   // select_cc setlt    X,  1, -X,  X ->
13525   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13526   if (N1C) {
13527     ConstantSDNode *SubC = nullptr;
13528     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13529          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13530         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13531       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13532     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13533               (N1C->isOne() && CC == ISD::SETLT)) &&
13534              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13535       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13536
13537     EVT XType = N0.getValueType();
13538     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13539       SDLoc DL(N0);
13540       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13541                                   N0,
13542                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13543                                          getShiftAmountTy(N0.getValueType())));
13544       SDValue Add = DAG.getNode(ISD::ADD, DL,
13545                                 XType, N0, Shift);
13546       AddToWorklist(Shift.getNode());
13547       AddToWorklist(Add.getNode());
13548       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13549     }
13550   }
13551
13552   return SDValue();
13553 }
13554
13555 /// This is a stub for TargetLowering::SimplifySetCC.
13556 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13557                                    SDValue N1, ISD::CondCode Cond,
13558                                    SDLoc DL, bool foldBooleans) {
13559   TargetLowering::DAGCombinerInfo
13560     DagCombineInfo(DAG, Level, false, this);
13561   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13562 }
13563
13564 /// Given an ISD::SDIV node expressing a divide by constant, return
13565 /// a DAG expression to select that will generate the same value by multiplying
13566 /// by a magic number.
13567 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13568 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13569   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13570   if (!C)
13571     return SDValue();
13572
13573   // Avoid division by zero.
13574   if (C->isNullValue())
13575     return SDValue();
13576
13577   std::vector<SDNode*> Built;
13578   SDValue S =
13579       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13580
13581   for (SDNode *N : Built)
13582     AddToWorklist(N);
13583   return S;
13584 }
13585
13586 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13587 /// DAG expression that will generate the same value by right shifting.
13588 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13589   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13590   if (!C)
13591     return SDValue();
13592
13593   // Avoid division by zero.
13594   if (C->isNullValue())
13595     return SDValue();
13596
13597   std::vector<SDNode *> Built;
13598   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13599
13600   for (SDNode *N : Built)
13601     AddToWorklist(N);
13602   return S;
13603 }
13604
13605 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13606 /// expression that will generate the same value by multiplying by a magic
13607 /// number.
13608 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13609 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13610   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13611   if (!C)
13612     return SDValue();
13613
13614   // Avoid division by zero.
13615   if (C->isNullValue())
13616     return SDValue();
13617
13618   std::vector<SDNode*> Built;
13619   SDValue S =
13620       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13621
13622   for (SDNode *N : Built)
13623     AddToWorklist(N);
13624   return S;
13625 }
13626
13627 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13628   if (Level >= AfterLegalizeDAG)
13629     return SDValue();
13630
13631   // Expose the DAG combiner to the target combiner implementations.
13632   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13633
13634   unsigned Iterations = 0;
13635   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13636     if (Iterations) {
13637       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13638       // For the reciprocal, we need to find the zero of the function:
13639       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13640       //     =>
13641       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13642       //     does not require additional intermediate precision]
13643       EVT VT = Op.getValueType();
13644       SDLoc DL(Op);
13645       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13646
13647       AddToWorklist(Est.getNode());
13648
13649       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13650       for (unsigned i = 0; i < Iterations; ++i) {
13651         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13652         AddToWorklist(NewEst.getNode());
13653
13654         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13655         AddToWorklist(NewEst.getNode());
13656
13657         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13658         AddToWorklist(NewEst.getNode());
13659
13660         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13661         AddToWorklist(Est.getNode());
13662       }
13663     }
13664     return Est;
13665   }
13666
13667   return SDValue();
13668 }
13669
13670 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13671 /// For the reciprocal sqrt, we need to find the zero of the function:
13672 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13673 ///     =>
13674 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13675 /// As a result, we precompute A/2 prior to the iteration loop.
13676 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13677                                           unsigned Iterations) {
13678   EVT VT = Arg.getValueType();
13679   SDLoc DL(Arg);
13680   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13681
13682   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13683   // this entire sequence requires only one FP constant.
13684   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13685   AddToWorklist(HalfArg.getNode());
13686
13687   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13688   AddToWorklist(HalfArg.getNode());
13689
13690   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13691   for (unsigned i = 0; i < Iterations; ++i) {
13692     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13693     AddToWorklist(NewEst.getNode());
13694
13695     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13696     AddToWorklist(NewEst.getNode());
13697
13698     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13699     AddToWorklist(NewEst.getNode());
13700
13701     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13702     AddToWorklist(Est.getNode());
13703   }
13704   return Est;
13705 }
13706
13707 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13708 /// For the reciprocal sqrt, we need to find the zero of the function:
13709 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13710 ///     =>
13711 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13712 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13713                                           unsigned Iterations) {
13714   EVT VT = Arg.getValueType();
13715   SDLoc DL(Arg);
13716   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13717   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13718
13719   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13720   for (unsigned i = 0; i < Iterations; ++i) {
13721     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13722     AddToWorklist(HalfEst.getNode());
13723
13724     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13725     AddToWorklist(Est.getNode());
13726
13727     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13728     AddToWorklist(Est.getNode());
13729
13730     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13731     AddToWorklist(Est.getNode());
13732
13733     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13734     AddToWorklist(Est.getNode());
13735   }
13736   return Est;
13737 }
13738
13739 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13740   if (Level >= AfterLegalizeDAG)
13741     return SDValue();
13742
13743   // Expose the DAG combiner to the target combiner implementations.
13744   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13745   unsigned Iterations = 0;
13746   bool UseOneConstNR = false;
13747   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13748     AddToWorklist(Est.getNode());
13749     if (Iterations) {
13750       Est = UseOneConstNR ?
13751         BuildRsqrtNROneConst(Op, Est, Iterations) :
13752         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13753     }
13754     return Est;
13755   }
13756
13757   return SDValue();
13758 }
13759
13760 /// Return true if base is a frame index, which is known not to alias with
13761 /// anything but itself.  Provides base object and offset as results.
13762 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13763                            const GlobalValue *&GV, const void *&CV) {
13764   // Assume it is a primitive operation.
13765   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13766
13767   // If it's an adding a simple constant then integrate the offset.
13768   if (Base.getOpcode() == ISD::ADD) {
13769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13770       Base = Base.getOperand(0);
13771       Offset += C->getZExtValue();
13772     }
13773   }
13774
13775   // Return the underlying GlobalValue, and update the Offset.  Return false
13776   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13777   // by multiple nodes with different offsets.
13778   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13779     GV = G->getGlobal();
13780     Offset += G->getOffset();
13781     return false;
13782   }
13783
13784   // Return the underlying Constant value, and update the Offset.  Return false
13785   // for ConstantSDNodes since the same constant pool entry may be represented
13786   // by multiple nodes with different offsets.
13787   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13788     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13789                                          : (const void *)C->getConstVal();
13790     Offset += C->getOffset();
13791     return false;
13792   }
13793   // If it's any of the following then it can't alias with anything but itself.
13794   return isa<FrameIndexSDNode>(Base);
13795 }
13796
13797 /// Return true if there is any possibility that the two addresses overlap.
13798 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13799   // If they are the same then they must be aliases.
13800   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13801
13802   // If they are both volatile then they cannot be reordered.
13803   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13804
13805   // Gather base node and offset information.
13806   SDValue Base1, Base2;
13807   int64_t Offset1, Offset2;
13808   const GlobalValue *GV1, *GV2;
13809   const void *CV1, *CV2;
13810   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13811                                       Base1, Offset1, GV1, CV1);
13812   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13813                                       Base2, Offset2, GV2, CV2);
13814
13815   // If they have a same base address then check to see if they overlap.
13816   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13817     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13818              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13819
13820   // It is possible for different frame indices to alias each other, mostly
13821   // when tail call optimization reuses return address slots for arguments.
13822   // To catch this case, look up the actual index of frame indices to compute
13823   // the real alias relationship.
13824   if (isFrameIndex1 && isFrameIndex2) {
13825     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13826     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13827     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13828     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13829              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13830   }
13831
13832   // Otherwise, if we know what the bases are, and they aren't identical, then
13833   // we know they cannot alias.
13834   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13835     return false;
13836
13837   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13838   // compared to the size and offset of the access, we may be able to prove they
13839   // do not alias.  This check is conservative for now to catch cases created by
13840   // splitting vector types.
13841   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13842       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13843       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13844        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13845       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13846     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13847     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13848
13849     // There is no overlap between these relatively aligned accesses of similar
13850     // size, return no alias.
13851     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13852         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13853       return false;
13854   }
13855
13856   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13857                    ? CombinerGlobalAA
13858                    : DAG.getSubtarget().useAA();
13859 #ifndef NDEBUG
13860   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13861       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13862     UseAA = false;
13863 #endif
13864   if (UseAA &&
13865       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13866     // Use alias analysis information.
13867     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13868                                  Op1->getSrcValueOffset());
13869     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13870         Op0->getSrcValueOffset() - MinOffset;
13871     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13872         Op1->getSrcValueOffset() - MinOffset;
13873     AliasAnalysis::AliasResult AAResult =
13874         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13875                                          Overlap1,
13876                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13877                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13878                                          Overlap2,
13879                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13880     if (AAResult == AliasAnalysis::NoAlias)
13881       return false;
13882   }
13883
13884   // Otherwise we have to assume they alias.
13885   return true;
13886 }
13887
13888 /// Walk up chain skipping non-aliasing memory nodes,
13889 /// looking for aliasing nodes and adding them to the Aliases vector.
13890 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13891                                    SmallVectorImpl<SDValue> &Aliases) {
13892   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13893   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13894
13895   // Get alias information for node.
13896   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13897
13898   // Starting off.
13899   Chains.push_back(OriginalChain);
13900   unsigned Depth = 0;
13901
13902   // Look at each chain and determine if it is an alias.  If so, add it to the
13903   // aliases list.  If not, then continue up the chain looking for the next
13904   // candidate.
13905   while (!Chains.empty()) {
13906     SDValue Chain = Chains.back();
13907     Chains.pop_back();
13908
13909     // For TokenFactor nodes, look at each operand and only continue up the
13910     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13911     // find more and revert to original chain since the xform is unlikely to be
13912     // profitable.
13913     //
13914     // FIXME: The depth check could be made to return the last non-aliasing
13915     // chain we found before we hit a tokenfactor rather than the original
13916     // chain.
13917     if (Depth > 6 || Aliases.size() == 2) {
13918       Aliases.clear();
13919       Aliases.push_back(OriginalChain);
13920       return;
13921     }
13922
13923     // Don't bother if we've been before.
13924     if (!Visited.insert(Chain.getNode()).second)
13925       continue;
13926
13927     switch (Chain.getOpcode()) {
13928     case ISD::EntryToken:
13929       // Entry token is ideal chain operand, but handled in FindBetterChain.
13930       break;
13931
13932     case ISD::LOAD:
13933     case ISD::STORE: {
13934       // Get alias information for Chain.
13935       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13936           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13937
13938       // If chain is alias then stop here.
13939       if (!(IsLoad && IsOpLoad) &&
13940           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13941         Aliases.push_back(Chain);
13942       } else {
13943         // Look further up the chain.
13944         Chains.push_back(Chain.getOperand(0));
13945         ++Depth;
13946       }
13947       break;
13948     }
13949
13950     case ISD::TokenFactor:
13951       // We have to check each of the operands of the token factor for "small"
13952       // token factors, so we queue them up.  Adding the operands to the queue
13953       // (stack) in reverse order maintains the original order and increases the
13954       // likelihood that getNode will find a matching token factor (CSE.)
13955       if (Chain.getNumOperands() > 16) {
13956         Aliases.push_back(Chain);
13957         break;
13958       }
13959       for (unsigned n = Chain.getNumOperands(); n;)
13960         Chains.push_back(Chain.getOperand(--n));
13961       ++Depth;
13962       break;
13963
13964     default:
13965       // For all other instructions we will just have to take what we can get.
13966       Aliases.push_back(Chain);
13967       break;
13968     }
13969   }
13970
13971   // We need to be careful here to also search for aliases through the
13972   // value operand of a store, etc. Consider the following situation:
13973   //   Token1 = ...
13974   //   L1 = load Token1, %52
13975   //   S1 = store Token1, L1, %51
13976   //   L2 = load Token1, %52+8
13977   //   S2 = store Token1, L2, %51+8
13978   //   Token2 = Token(S1, S2)
13979   //   L3 = load Token2, %53
13980   //   S3 = store Token2, L3, %52
13981   //   L4 = load Token2, %53+8
13982   //   S4 = store Token2, L4, %52+8
13983   // If we search for aliases of S3 (which loads address %52), and we look
13984   // only through the chain, then we'll miss the trivial dependence on L1
13985   // (which also loads from %52). We then might change all loads and
13986   // stores to use Token1 as their chain operand, which could result in
13987   // copying %53 into %52 before copying %52 into %51 (which should
13988   // happen first).
13989   //
13990   // The problem is, however, that searching for such data dependencies
13991   // can become expensive, and the cost is not directly related to the
13992   // chain depth. Instead, we'll rule out such configurations here by
13993   // insisting that we've visited all chain users (except for users
13994   // of the original chain, which is not necessary). When doing this,
13995   // we need to look through nodes we don't care about (otherwise, things
13996   // like register copies will interfere with trivial cases).
13997
13998   SmallVector<const SDNode *, 16> Worklist;
13999   for (const SDNode *N : Visited)
14000     if (N != OriginalChain.getNode())
14001       Worklist.push_back(N);
14002
14003   while (!Worklist.empty()) {
14004     const SDNode *M = Worklist.pop_back_val();
14005
14006     // We have already visited M, and want to make sure we've visited any uses
14007     // of M that we care about. For uses that we've not visisted, and don't
14008     // care about, queue them to the worklist.
14009
14010     for (SDNode::use_iterator UI = M->use_begin(),
14011          UIE = M->use_end(); UI != UIE; ++UI)
14012       if (UI.getUse().getValueType() == MVT::Other &&
14013           Visited.insert(*UI).second) {
14014         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
14015           // We've not visited this use, and we care about it (it could have an
14016           // ordering dependency with the original node).
14017           Aliases.clear();
14018           Aliases.push_back(OriginalChain);
14019           return;
14020         }
14021
14022         // We've not visited this use, but we don't care about it. Mark it as
14023         // visited and enqueue it to the worklist.
14024         Worklist.push_back(*UI);
14025       }
14026   }
14027 }
14028
14029 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14030 /// (aliasing node.)
14031 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14032   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14033
14034   // Accumulate all the aliases to this node.
14035   GatherAllAliases(N, OldChain, Aliases);
14036
14037   // If no operands then chain to entry token.
14038   if (Aliases.size() == 0)
14039     return DAG.getEntryNode();
14040
14041   // If a single operand then chain to it.  We don't need to revisit it.
14042   if (Aliases.size() == 1)
14043     return Aliases[0];
14044
14045   // Construct a custom tailored token factor.
14046   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14047 }
14048
14049 /// This is the entry point for the file.
14050 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14051                            CodeGenOpt::Level OptLevel) {
14052   /// This is the main entry point to this class.
14053   DAGCombiner(*this, AA, OptLevel).Run(Level);
14054 }