Fix comment typos.
[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 visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
272     SDValue visitTRUNCATE(SDNode *N);
273     SDValue visitBITCAST(SDNode *N);
274     SDValue visitBUILD_PAIR(SDNode *N);
275     SDValue visitFADD(SDNode *N);
276     SDValue visitFSUB(SDNode *N);
277     SDValue visitFMUL(SDNode *N);
278     SDValue visitFMA(SDNode *N);
279     SDValue visitFDIV(SDNode *N);
280     SDValue visitFREM(SDNode *N);
281     SDValue visitFSQRT(SDNode *N);
282     SDValue visitFCOPYSIGN(SDNode *N);
283     SDValue visitSINT_TO_FP(SDNode *N);
284     SDValue visitUINT_TO_FP(SDNode *N);
285     SDValue visitFP_TO_SINT(SDNode *N);
286     SDValue visitFP_TO_UINT(SDNode *N);
287     SDValue visitFP_ROUND(SDNode *N);
288     SDValue visitFP_ROUND_INREG(SDNode *N);
289     SDValue visitFP_EXTEND(SDNode *N);
290     SDValue visitFNEG(SDNode *N);
291     SDValue visitFABS(SDNode *N);
292     SDValue visitFCEIL(SDNode *N);
293     SDValue visitFTRUNC(SDNode *N);
294     SDValue visitFFLOOR(SDNode *N);
295     SDValue visitFMINNUM(SDNode *N);
296     SDValue visitFMAXNUM(SDNode *N);
297     SDValue visitBRCOND(SDNode *N);
298     SDValue visitBR_CC(SDNode *N);
299     SDValue visitLOAD(SDNode *N);
300     SDValue visitSTORE(SDNode *N);
301     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303     SDValue visitBUILD_VECTOR(SDNode *N);
304     SDValue visitCONCAT_VECTORS(SDNode *N);
305     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306     SDValue visitVECTOR_SHUFFLE(SDNode *N);
307     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
308     SDValue visitINSERT_SUBVECTOR(SDNode *N);
309     SDValue visitMLOAD(SDNode *N);
310     SDValue visitMSTORE(SDNode *N);
311     SDValue visitMGATHER(SDNode *N);
312     SDValue visitMSCATTER(SDNode *N);
313     SDValue visitFP_TO_FP16(SDNode *N);
314
315     SDValue visitFADDForFMACombine(SDNode *N);
316     SDValue visitFSUBForFMACombine(SDNode *N);
317
318     SDValue XformToShuffleWithZero(SDNode *N);
319     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
320
321     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
322
323     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
324     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
325     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
326     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
327                              SDValue N3, ISD::CondCode CC,
328                              bool NotExtCompare = false);
329     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
330                           SDLoc DL, bool foldBooleans = true);
331
332     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
333                            SDValue &CC) const;
334     bool isOneUseSetCC(SDValue N) const;
335
336     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
337                                          unsigned HiOp);
338     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
339     SDValue CombineExtLoad(SDNode *N);
340     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
341     SDValue BuildSDIV(SDNode *N);
342     SDValue BuildSDIVPow2(SDNode *N);
343     SDValue BuildUDIV(SDNode *N);
344     SDValue BuildReciprocalEstimate(SDValue Op);
345     SDValue BuildRsqrtEstimate(SDValue Op);
346     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
348     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
349                                bool DemandHighBits = true);
350     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
351     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
352                               SDValue InnerPos, SDValue InnerNeg,
353                               unsigned PosOpcode, unsigned NegOpcode,
354                               SDLoc DL);
355     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
356     SDValue ReduceLoadWidth(SDNode *N);
357     SDValue ReduceLoadOpStoreWidth(SDNode *N);
358     SDValue TransformFPLoadStorePair(SDNode *N);
359     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
360     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
361
362     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
363
364     /// Walk up chain skipping non-aliasing memory nodes,
365     /// looking for aliasing nodes and adding them to the Aliases vector.
366     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
367                           SmallVectorImpl<SDValue> &Aliases);
368
369     /// Return true if there is any possibility that the two addresses overlap.
370     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
371
372     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
373     /// chain (aliasing node.)
374     SDValue FindBetterChain(SDNode *N, SDValue Chain);
375
376     /// Holds a pointer to an LSBaseSDNode as well as information on where it
377     /// is located in a sequence of memory operations connected by a chain.
378     struct MemOpLink {
379       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
380       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
381       // Ptr to the mem node.
382       LSBaseSDNode *MemNode;
383       // Offset from the base ptr.
384       int64_t OffsetFromBase;
385       // What is the sequence number of this mem node.
386       // Lowest mem operand in the DAG starts at zero.
387       unsigned SequenceNum;
388     };
389
390     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
391     /// constant build_vector of the stored constant values in Stores.
392     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
393                                          SDLoc SL,
394                                          ArrayRef<MemOpLink> Stores,
395                                          EVT Ty) const;
396
397     /// This is a helper function for MergeConsecutiveStores. When the source
398     /// elements of the consecutive stores are all constants or all extracted
399     /// vector elements, try to merge them into one larger store.
400     /// \return True if a merged store was created.
401     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
402                                          EVT MemVT, unsigned NumElem,
403                                          bool IsConstantSrc, bool UseVector);
404
405     /// Merge consecutive store operations into a wide store.
406     /// This optimization uses wide integers or vectors when possible.
407     /// \return True if some memory operations were changed.
408     bool MergeConsecutiveStores(StoreSDNode *N);
409
410     /// \brief Try to transform a truncation where C is a constant:
411     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
412     ///
413     /// \p N needs to be a truncation and its first operand an AND. Other
414     /// requirements are checked by the function (e.g. that trunc is
415     /// single-use) and if missed an empty SDValue is returned.
416     SDValue distributeTruncateThroughAnd(SDNode *N);
417
418   public:
419     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
420         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
421           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
422       auto *F = DAG.getMachineFunction().getFunction();
423       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
424                     F->hasFnAttribute(Attribute::MinSize);
425     }
426
427     /// Runs the dag combiner on all nodes in the work list
428     void Run(CombineLevel AtLevel);
429
430     SelectionDAG &getDAG() const { return DAG; }
431
432     /// Returns a type large enough to hold any valid shift amount - before type
433     /// legalization these can be huge.
434     EVT getShiftAmountTy(EVT LHSTy) {
435       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
436       if (LHSTy.isVector())
437         return LHSTy;
438       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
439                         : TLI.getPointerTy();
440     }
441
442     /// This method returns true if we are running before type legalization or
443     /// if the specified VT is legal.
444     bool isTypeLegal(const EVT &VT) {
445       if (!LegalTypes) return true;
446       return TLI.isTypeLegal(VT);
447     }
448
449     /// Convenience wrapper around TargetLowering::getSetCCResultType
450     EVT getSetCCResultType(EVT VT) const {
451       return TLI.getSetCCResultType(*DAG.getContext(), VT);
452     }
453   };
454 }
455
456
457 namespace {
458 /// This class is a DAGUpdateListener that removes any deleted
459 /// nodes from the worklist.
460 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
461   DAGCombiner &DC;
462 public:
463   explicit WorklistRemover(DAGCombiner &dc)
464     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
465
466   void NodeDeleted(SDNode *N, SDNode *E) override {
467     DC.removeFromWorklist(N);
468   }
469 };
470 }
471
472 //===----------------------------------------------------------------------===//
473 //  TargetLowering::DAGCombinerInfo implementation
474 //===----------------------------------------------------------------------===//
475
476 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
477   ((DAGCombiner*)DC)->AddToWorklist(N);
478 }
479
480 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
481   ((DAGCombiner*)DC)->removeFromWorklist(N);
482 }
483
484 SDValue TargetLowering::DAGCombinerInfo::
485 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
486   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
487 }
488
489 SDValue TargetLowering::DAGCombinerInfo::
490 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
491   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
492 }
493
494
495 SDValue TargetLowering::DAGCombinerInfo::
496 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
497   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
498 }
499
500 void TargetLowering::DAGCombinerInfo::
501 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
502   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
503 }
504
505 //===----------------------------------------------------------------------===//
506 // Helper Functions
507 //===----------------------------------------------------------------------===//
508
509 void DAGCombiner::deleteAndRecombine(SDNode *N) {
510   removeFromWorklist(N);
511
512   // If the operands of this node are only used by the node, they will now be
513   // dead. Make sure to re-visit them and recursively delete dead nodes.
514   for (const SDValue &Op : N->ops())
515     // For an operand generating multiple values, one of the values may
516     // become dead allowing further simplification (e.g. split index
517     // arithmetic from an indexed load).
518     if (Op->hasOneUse() || Op->getNumValues() > 1)
519       AddToWorklist(Op.getNode());
520
521   DAG.DeleteNode(N);
522 }
523
524 /// Return 1 if we can compute the negated form of the specified expression for
525 /// the same cost as the expression itself, or 2 if we can compute the negated
526 /// form more cheaply than the expression itself.
527 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
528                                const TargetLowering &TLI,
529                                const TargetOptions *Options,
530                                unsigned Depth = 0) {
531   // fneg is removable even if it has multiple uses.
532   if (Op.getOpcode() == ISD::FNEG) return 2;
533
534   // Don't allow anything with multiple uses.
535   if (!Op.hasOneUse()) return 0;
536
537   // Don't recurse exponentially.
538   if (Depth > 6) return 0;
539
540   switch (Op.getOpcode()) {
541   default: return false;
542   case ISD::ConstantFP:
543     // Don't invert constant FP values after legalize.  The negated constant
544     // isn't necessarily legal.
545     return LegalOperations ? 0 : 1;
546   case ISD::FADD:
547     // FIXME: determine better conditions for this xform.
548     if (!Options->UnsafeFPMath) return 0;
549
550     // After operation legalization, it might not be legal to create new FSUBs.
551     if (LegalOperations &&
552         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
553       return 0;
554
555     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
556     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
557                                     Options, Depth + 1))
558       return V;
559     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
560     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
561                               Depth + 1);
562   case ISD::FSUB:
563     // We can't turn -(A-B) into B-A when we honor signed zeros.
564     if (!Options->UnsafeFPMath) return 0;
565
566     // fold (fneg (fsub A, B)) -> (fsub B, A)
567     return 1;
568
569   case ISD::FMUL:
570   case ISD::FDIV:
571     if (Options->HonorSignDependentRoundingFPMath()) return 0;
572
573     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
574     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
575                                     Options, Depth + 1))
576       return V;
577
578     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
579                               Depth + 1);
580
581   case ISD::FP_EXTEND:
582   case ISD::FP_ROUND:
583   case ISD::FSIN:
584     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
585                               Depth + 1);
586   }
587 }
588
589 /// If isNegatibleForFree returns true, return the newly negated expression.
590 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
591                                     bool LegalOperations, unsigned Depth = 0) {
592   const TargetOptions &Options = DAG.getTarget().Options;
593   // fneg is removable even if it has multiple uses.
594   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
595
596   // Don't allow anything with multiple uses.
597   assert(Op.hasOneUse() && "Unknown reuse!");
598
599   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
600   switch (Op.getOpcode()) {
601   default: llvm_unreachable("Unknown code");
602   case ISD::ConstantFP: {
603     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
604     V.changeSign();
605     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
606   }
607   case ISD::FADD:
608     // FIXME: determine better conditions for this xform.
609     assert(Options.UnsafeFPMath);
610
611     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
612     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
613                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
614       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
615                          GetNegatedExpression(Op.getOperand(0), DAG,
616                                               LegalOperations, Depth+1),
617                          Op.getOperand(1));
618     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
619     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
620                        GetNegatedExpression(Op.getOperand(1), DAG,
621                                             LegalOperations, Depth+1),
622                        Op.getOperand(0));
623   case ISD::FSUB:
624     // We can't turn -(A-B) into B-A when we honor signed zeros.
625     assert(Options.UnsafeFPMath);
626
627     // fold (fneg (fsub 0, B)) -> B
628     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
629       if (N0CFP->isZero())
630         return Op.getOperand(1);
631
632     // fold (fneg (fsub A, B)) -> (fsub B, A)
633     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
634                        Op.getOperand(1), Op.getOperand(0));
635
636   case ISD::FMUL:
637   case ISD::FDIV:
638     assert(!Options.HonorSignDependentRoundingFPMath());
639
640     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
641     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
642                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
643       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
644                          GetNegatedExpression(Op.getOperand(0), DAG,
645                                               LegalOperations, Depth+1),
646                          Op.getOperand(1));
647
648     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
649     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
650                        Op.getOperand(0),
651                        GetNegatedExpression(Op.getOperand(1), DAG,
652                                             LegalOperations, Depth+1));
653
654   case ISD::FP_EXTEND:
655   case ISD::FSIN:
656     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
657                        GetNegatedExpression(Op.getOperand(0), DAG,
658                                             LegalOperations, Depth+1));
659   case ISD::FP_ROUND:
660       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
661                          GetNegatedExpression(Op.getOperand(0), DAG,
662                                               LegalOperations, Depth+1),
663                          Op.getOperand(1));
664   }
665 }
666
667 // Return true if this node is a setcc, or is a select_cc
668 // that selects between the target values used for true and false, making it
669 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
670 // the appropriate nodes based on the type of node we are checking. This
671 // simplifies life a bit for the callers.
672 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
673                                     SDValue &CC) const {
674   if (N.getOpcode() == ISD::SETCC) {
675     LHS = N.getOperand(0);
676     RHS = N.getOperand(1);
677     CC  = N.getOperand(2);
678     return true;
679   }
680
681   if (N.getOpcode() != ISD::SELECT_CC ||
682       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
683       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
684     return false;
685
686   if (TLI.getBooleanContents(N.getValueType()) ==
687       TargetLowering::UndefinedBooleanContent)
688     return false;
689
690   LHS = N.getOperand(0);
691   RHS = N.getOperand(1);
692   CC  = N.getOperand(4);
693   return true;
694 }
695
696 /// Return true if this is a SetCC-equivalent operation with only one use.
697 /// If this is true, it allows the users to invert the operation for free when
698 /// it is profitable to do so.
699 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
700   SDValue N0, N1, N2;
701   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
702     return true;
703   return false;
704 }
705
706 /// Returns true if N is a BUILD_VECTOR node whose
707 /// elements are all the same constant or undefined.
708 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
709   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
710   if (!C)
711     return false;
712
713   APInt SplatUndef;
714   unsigned SplatBitSize;
715   bool HasAnyUndefs;
716   EVT EltVT = N->getValueType(0).getVectorElementType();
717   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
718                              HasAnyUndefs) &&
719           EltVT.getSizeInBits() >= SplatBitSize);
720 }
721
722 // \brief Returns the SDNode if it is a constant integer BuildVector
723 // or constant integer.
724 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
725   if (isa<ConstantSDNode>(N))
726     return N.getNode();
727   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
728     return N.getNode();
729   return nullptr;
730 }
731
732 // \brief Returns the SDNode if it is a constant float BuildVector
733 // or constant float.
734 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
735   if (isa<ConstantFPSDNode>(N))
736     return N.getNode();
737   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
738     return N.getNode();
739   return nullptr;
740 }
741
742 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
743 // int.
744 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
745   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
746     return CN;
747
748   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
749     BitVector UndefElements;
750     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
751
752     // BuildVectors can truncate their operands. Ignore that case here.
753     // FIXME: We blindly ignore splats which include undef which is overly
754     // pessimistic.
755     if (CN && UndefElements.none() &&
756         CN->getValueType(0) == N.getValueType().getScalarType())
757       return CN;
758   }
759
760   return nullptr;
761 }
762
763 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
764 // float.
765 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
766   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
767     return CN;
768
769   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
770     BitVector UndefElements;
771     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
772
773     if (CN && UndefElements.none())
774       return CN;
775   }
776
777   return nullptr;
778 }
779
780 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
781                                     SDValue N0, SDValue N1) {
782   EVT VT = N0.getValueType();
783   if (N0.getOpcode() == Opc) {
784     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
785       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
786         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
787         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
788           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
789         return SDValue();
790       }
791       if (N0.hasOneUse()) {
792         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
793         // use
794         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
795         if (!OpNode.getNode())
796           return SDValue();
797         AddToWorklist(OpNode.getNode());
798         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
799       }
800     }
801   }
802
803   if (N1.getOpcode() == Opc) {
804     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
805       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
806         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
807         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
808           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
809         return SDValue();
810       }
811       if (N1.hasOneUse()) {
812         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
813         // use
814         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
815         if (!OpNode.getNode())
816           return SDValue();
817         AddToWorklist(OpNode.getNode());
818         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
819       }
820     }
821   }
822
823   return SDValue();
824 }
825
826 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
827                                bool AddTo) {
828   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
829   ++NodesCombined;
830   DEBUG(dbgs() << "\nReplacing.1 ";
831         N->dump(&DAG);
832         dbgs() << "\nWith: ";
833         To[0].getNode()->dump(&DAG);
834         dbgs() << " and " << NumTo-1 << " other values\n");
835   for (unsigned i = 0, e = NumTo; i != e; ++i)
836     assert((!To[i].getNode() ||
837             N->getValueType(i) == To[i].getValueType()) &&
838            "Cannot combine value to value of different type!");
839
840   WorklistRemover DeadNodes(*this);
841   DAG.ReplaceAllUsesWith(N, To);
842   if (AddTo) {
843     // Push the new nodes and any users onto the worklist
844     for (unsigned i = 0, e = NumTo; i != e; ++i) {
845       if (To[i].getNode()) {
846         AddToWorklist(To[i].getNode());
847         AddUsersToWorklist(To[i].getNode());
848       }
849     }
850   }
851
852   // Finally, if the node is now dead, remove it from the graph.  The node
853   // may not be dead if the replacement process recursively simplified to
854   // something else needing this node.
855   if (N->use_empty())
856     deleteAndRecombine(N);
857   return SDValue(N, 0);
858 }
859
860 void DAGCombiner::
861 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
862   // Replace all uses.  If any nodes become isomorphic to other nodes and
863   // are deleted, make sure to remove them from our worklist.
864   WorklistRemover DeadNodes(*this);
865   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
866
867   // Push the new node and any (possibly new) users onto the worklist.
868   AddToWorklist(TLO.New.getNode());
869   AddUsersToWorklist(TLO.New.getNode());
870
871   // Finally, if the node is now dead, remove it from the graph.  The node
872   // may not be dead if the replacement process recursively simplified to
873   // something else needing this node.
874   if (TLO.Old.getNode()->use_empty())
875     deleteAndRecombine(TLO.Old.getNode());
876 }
877
878 /// Check the specified integer node value to see if it can be simplified or if
879 /// things it uses can be simplified by bit propagation. If so, return true.
880 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
881   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
882   APInt KnownZero, KnownOne;
883   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
884     return false;
885
886   // Revisit the node.
887   AddToWorklist(Op.getNode());
888
889   // Replace the old value with the new one.
890   ++NodesCombined;
891   DEBUG(dbgs() << "\nReplacing.2 ";
892         TLO.Old.getNode()->dump(&DAG);
893         dbgs() << "\nWith: ";
894         TLO.New.getNode()->dump(&DAG);
895         dbgs() << '\n');
896
897   CommitTargetLoweringOpt(TLO);
898   return true;
899 }
900
901 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
902   SDLoc dl(Load);
903   EVT VT = Load->getValueType(0);
904   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
905
906   DEBUG(dbgs() << "\nReplacing.9 ";
907         Load->dump(&DAG);
908         dbgs() << "\nWith: ";
909         Trunc.getNode()->dump(&DAG);
910         dbgs() << '\n');
911   WorklistRemover DeadNodes(*this);
912   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
913   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
914   deleteAndRecombine(Load);
915   AddToWorklist(Trunc.getNode());
916 }
917
918 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
919   Replace = false;
920   SDLoc dl(Op);
921   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
922     EVT MemVT = LD->getMemoryVT();
923     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
924       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
925                                                        : ISD::EXTLOAD)
926       : LD->getExtensionType();
927     Replace = true;
928     return DAG.getExtLoad(ExtType, dl, PVT,
929                           LD->getChain(), LD->getBasePtr(),
930                           MemVT, LD->getMemOperand());
931   }
932
933   unsigned Opc = Op.getOpcode();
934   switch (Opc) {
935   default: break;
936   case ISD::AssertSext:
937     return DAG.getNode(ISD::AssertSext, dl, PVT,
938                        SExtPromoteOperand(Op.getOperand(0), PVT),
939                        Op.getOperand(1));
940   case ISD::AssertZext:
941     return DAG.getNode(ISD::AssertZext, dl, PVT,
942                        ZExtPromoteOperand(Op.getOperand(0), PVT),
943                        Op.getOperand(1));
944   case ISD::Constant: {
945     unsigned ExtOpc =
946       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
947     return DAG.getNode(ExtOpc, dl, PVT, Op);
948   }
949   }
950
951   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
952     return SDValue();
953   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
954 }
955
956 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
957   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
958     return SDValue();
959   EVT OldVT = Op.getValueType();
960   SDLoc dl(Op);
961   bool Replace = false;
962   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
963   if (!NewOp.getNode())
964     return SDValue();
965   AddToWorklist(NewOp.getNode());
966
967   if (Replace)
968     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
969   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
970                      DAG.getValueType(OldVT));
971 }
972
973 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
974   EVT OldVT = Op.getValueType();
975   SDLoc dl(Op);
976   bool Replace = false;
977   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
978   if (!NewOp.getNode())
979     return SDValue();
980   AddToWorklist(NewOp.getNode());
981
982   if (Replace)
983     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
984   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
985 }
986
987 /// Promote the specified integer binary operation if the target indicates it is
988 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
989 /// i32 since i16 instructions are longer.
990 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
991   if (!LegalOperations)
992     return SDValue();
993
994   EVT VT = Op.getValueType();
995   if (VT.isVector() || !VT.isInteger())
996     return SDValue();
997
998   // If operation type is 'undesirable', e.g. i16 on x86, consider
999   // promoting it.
1000   unsigned Opc = Op.getOpcode();
1001   if (TLI.isTypeDesirableForOp(Opc, VT))
1002     return SDValue();
1003
1004   EVT PVT = VT;
1005   // Consult target whether it is a good idea to promote this operation and
1006   // what's the right type to promote it to.
1007   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1008     assert(PVT != VT && "Don't know what type to promote to!");
1009
1010     bool Replace0 = false;
1011     SDValue N0 = Op.getOperand(0);
1012     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1013     if (!NN0.getNode())
1014       return SDValue();
1015
1016     bool Replace1 = false;
1017     SDValue N1 = Op.getOperand(1);
1018     SDValue NN1;
1019     if (N0 == N1)
1020       NN1 = NN0;
1021     else {
1022       NN1 = PromoteOperand(N1, PVT, Replace1);
1023       if (!NN1.getNode())
1024         return SDValue();
1025     }
1026
1027     AddToWorklist(NN0.getNode());
1028     if (NN1.getNode())
1029       AddToWorklist(NN1.getNode());
1030
1031     if (Replace0)
1032       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1033     if (Replace1)
1034       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1035
1036     DEBUG(dbgs() << "\nPromoting ";
1037           Op.getNode()->dump(&DAG));
1038     SDLoc dl(Op);
1039     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1040                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1041   }
1042   return SDValue();
1043 }
1044
1045 /// Promote the specified integer shift operation if the target indicates it is
1046 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1047 /// i32 since i16 instructions are longer.
1048 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1049   if (!LegalOperations)
1050     return SDValue();
1051
1052   EVT VT = Op.getValueType();
1053   if (VT.isVector() || !VT.isInteger())
1054     return SDValue();
1055
1056   // If operation type is 'undesirable', e.g. i16 on x86, consider
1057   // promoting it.
1058   unsigned Opc = Op.getOpcode();
1059   if (TLI.isTypeDesirableForOp(Opc, VT))
1060     return SDValue();
1061
1062   EVT PVT = VT;
1063   // Consult target whether it is a good idea to promote this operation and
1064   // what's the right type to promote it to.
1065   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1066     assert(PVT != VT && "Don't know what type to promote to!");
1067
1068     bool Replace = false;
1069     SDValue N0 = Op.getOperand(0);
1070     if (Opc == ISD::SRA)
1071       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1072     else if (Opc == ISD::SRL)
1073       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1074     else
1075       N0 = PromoteOperand(N0, PVT, Replace);
1076     if (!N0.getNode())
1077       return SDValue();
1078
1079     AddToWorklist(N0.getNode());
1080     if (Replace)
1081       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1082
1083     DEBUG(dbgs() << "\nPromoting ";
1084           Op.getNode()->dump(&DAG));
1085     SDLoc dl(Op);
1086     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1087                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1088   }
1089   return SDValue();
1090 }
1091
1092 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1093   if (!LegalOperations)
1094     return SDValue();
1095
1096   EVT VT = Op.getValueType();
1097   if (VT.isVector() || !VT.isInteger())
1098     return SDValue();
1099
1100   // If operation type is 'undesirable', e.g. i16 on x86, consider
1101   // promoting it.
1102   unsigned Opc = Op.getOpcode();
1103   if (TLI.isTypeDesirableForOp(Opc, VT))
1104     return SDValue();
1105
1106   EVT PVT = VT;
1107   // Consult target whether it is a good idea to promote this operation and
1108   // what's the right type to promote it to.
1109   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1110     assert(PVT != VT && "Don't know what type to promote to!");
1111     // fold (aext (aext x)) -> (aext x)
1112     // fold (aext (zext x)) -> (zext x)
1113     // fold (aext (sext x)) -> (sext x)
1114     DEBUG(dbgs() << "\nPromoting ";
1115           Op.getNode()->dump(&DAG));
1116     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1117   }
1118   return SDValue();
1119 }
1120
1121 bool DAGCombiner::PromoteLoad(SDValue Op) {
1122   if (!LegalOperations)
1123     return false;
1124
1125   EVT VT = Op.getValueType();
1126   if (VT.isVector() || !VT.isInteger())
1127     return false;
1128
1129   // If operation type is 'undesirable', e.g. i16 on x86, consider
1130   // promoting it.
1131   unsigned Opc = Op.getOpcode();
1132   if (TLI.isTypeDesirableForOp(Opc, VT))
1133     return false;
1134
1135   EVT PVT = VT;
1136   // Consult target whether it is a good idea to promote this operation and
1137   // what's the right type to promote it to.
1138   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1139     assert(PVT != VT && "Don't know what type to promote to!");
1140
1141     SDLoc dl(Op);
1142     SDNode *N = Op.getNode();
1143     LoadSDNode *LD = cast<LoadSDNode>(N);
1144     EVT MemVT = LD->getMemoryVT();
1145     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1146       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1147                                                        : ISD::EXTLOAD)
1148       : LD->getExtensionType();
1149     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1150                                    LD->getChain(), LD->getBasePtr(),
1151                                    MemVT, LD->getMemOperand());
1152     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1153
1154     DEBUG(dbgs() << "\nPromoting ";
1155           N->dump(&DAG);
1156           dbgs() << "\nTo: ";
1157           Result.getNode()->dump(&DAG);
1158           dbgs() << '\n');
1159     WorklistRemover DeadNodes(*this);
1160     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1161     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1162     deleteAndRecombine(N);
1163     AddToWorklist(Result.getNode());
1164     return true;
1165   }
1166   return false;
1167 }
1168
1169 /// \brief Recursively delete a node which has no uses and any operands for
1170 /// which it is the only use.
1171 ///
1172 /// Note that this both deletes the nodes and removes them from the worklist.
1173 /// It also adds any nodes who have had a user deleted to the worklist as they
1174 /// may now have only one use and subject to other combines.
1175 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1176   if (!N->use_empty())
1177     return false;
1178
1179   SmallSetVector<SDNode *, 16> Nodes;
1180   Nodes.insert(N);
1181   do {
1182     N = Nodes.pop_back_val();
1183     if (!N)
1184       continue;
1185
1186     if (N->use_empty()) {
1187       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1188         Nodes.insert(N->getOperand(i).getNode());
1189
1190       removeFromWorklist(N);
1191       DAG.DeleteNode(N);
1192     } else {
1193       AddToWorklist(N);
1194     }
1195   } while (!Nodes.empty());
1196   return true;
1197 }
1198
1199 //===----------------------------------------------------------------------===//
1200 //  Main DAG Combiner implementation
1201 //===----------------------------------------------------------------------===//
1202
1203 void DAGCombiner::Run(CombineLevel AtLevel) {
1204   // set the instance variables, so that the various visit routines may use it.
1205   Level = AtLevel;
1206   LegalOperations = Level >= AfterLegalizeVectorOps;
1207   LegalTypes = Level >= AfterLegalizeTypes;
1208
1209   // Add all the dag nodes to the worklist.
1210   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1211        E = DAG.allnodes_end(); I != E; ++I)
1212     AddToWorklist(I);
1213
1214   // Create a dummy node (which is not added to allnodes), that adds a reference
1215   // to the root node, preventing it from being deleted, and tracking any
1216   // changes of the root.
1217   HandleSDNode Dummy(DAG.getRoot());
1218
1219   // while the worklist isn't empty, find a node and
1220   // try and combine it.
1221   while (!WorklistMap.empty()) {
1222     SDNode *N;
1223     // The Worklist holds the SDNodes in order, but it may contain null entries.
1224     do {
1225       N = Worklist.pop_back_val();
1226     } while (!N);
1227
1228     bool GoodWorklistEntry = WorklistMap.erase(N);
1229     (void)GoodWorklistEntry;
1230     assert(GoodWorklistEntry &&
1231            "Found a worklist entry without a corresponding map entry!");
1232
1233     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1234     // N is deleted from the DAG, since they too may now be dead or may have a
1235     // reduced number of uses, allowing other xforms.
1236     if (recursivelyDeleteUnusedNodes(N))
1237       continue;
1238
1239     WorklistRemover DeadNodes(*this);
1240
1241     // If this combine is running after legalizing the DAG, re-legalize any
1242     // nodes pulled off the worklist.
1243     if (Level == AfterLegalizeDAG) {
1244       SmallSetVector<SDNode *, 16> UpdatedNodes;
1245       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1246
1247       for (SDNode *LN : UpdatedNodes) {
1248         AddToWorklist(LN);
1249         AddUsersToWorklist(LN);
1250       }
1251       if (!NIsValid)
1252         continue;
1253     }
1254
1255     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1256
1257     // Add any operands of the new node which have not yet been combined to the
1258     // worklist as well. Because the worklist uniques things already, this
1259     // won't repeatedly process the same operand.
1260     CombinedNodes.insert(N);
1261     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1262       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1263         AddToWorklist(N->getOperand(i).getNode());
1264
1265     SDValue RV = combine(N);
1266
1267     if (!RV.getNode())
1268       continue;
1269
1270     ++NodesCombined;
1271
1272     // If we get back the same node we passed in, rather than a new node or
1273     // zero, we know that the node must have defined multiple values and
1274     // CombineTo was used.  Since CombineTo takes care of the worklist
1275     // mechanics for us, we have no work to do in this case.
1276     if (RV.getNode() == N)
1277       continue;
1278
1279     assert(N->getOpcode() != ISD::DELETED_NODE &&
1280            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1281            "Node was deleted but visit returned new node!");
1282
1283     DEBUG(dbgs() << " ... into: ";
1284           RV.getNode()->dump(&DAG));
1285
1286     // Transfer debug value.
1287     DAG.TransferDbgValues(SDValue(N, 0), RV);
1288     if (N->getNumValues() == RV.getNode()->getNumValues())
1289       DAG.ReplaceAllUsesWith(N, RV.getNode());
1290     else {
1291       assert(N->getValueType(0) == RV.getValueType() &&
1292              N->getNumValues() == 1 && "Type mismatch");
1293       SDValue OpV = RV;
1294       DAG.ReplaceAllUsesWith(N, &OpV);
1295     }
1296
1297     // Push the new node and any users onto the worklist
1298     AddToWorklist(RV.getNode());
1299     AddUsersToWorklist(RV.getNode());
1300
1301     // Finally, if the node is now dead, remove it from the graph.  The node
1302     // may not be dead if the replacement process recursively simplified to
1303     // something else needing this node. This will also take care of adding any
1304     // operands which have lost a user to the worklist.
1305     recursivelyDeleteUnusedNodes(N);
1306   }
1307
1308   // If the root changed (e.g. it was a dead load, update the root).
1309   DAG.setRoot(Dummy.getValue());
1310   DAG.RemoveDeadNodes();
1311 }
1312
1313 SDValue DAGCombiner::visit(SDNode *N) {
1314   switch (N->getOpcode()) {
1315   default: break;
1316   case ISD::TokenFactor:        return visitTokenFactor(N);
1317   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1318   case ISD::ADD:                return visitADD(N);
1319   case ISD::SUB:                return visitSUB(N);
1320   case ISD::ADDC:               return visitADDC(N);
1321   case ISD::SUBC:               return visitSUBC(N);
1322   case ISD::ADDE:               return visitADDE(N);
1323   case ISD::SUBE:               return visitSUBE(N);
1324   case ISD::MUL:                return visitMUL(N);
1325   case ISD::SDIV:               return visitSDIV(N);
1326   case ISD::UDIV:               return visitUDIV(N);
1327   case ISD::SREM:               return visitSREM(N);
1328   case ISD::UREM:               return visitUREM(N);
1329   case ISD::MULHU:              return visitMULHU(N);
1330   case ISD::MULHS:              return visitMULHS(N);
1331   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1332   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1333   case ISD::SMULO:              return visitSMULO(N);
1334   case ISD::UMULO:              return visitUMULO(N);
1335   case ISD::SDIVREM:            return visitSDIVREM(N);
1336   case ISD::UDIVREM:            return visitUDIVREM(N);
1337   case ISD::AND:                return visitAND(N);
1338   case ISD::OR:                 return visitOR(N);
1339   case ISD::XOR:                return visitXOR(N);
1340   case ISD::SHL:                return visitSHL(N);
1341   case ISD::SRA:                return visitSRA(N);
1342   case ISD::SRL:                return visitSRL(N);
1343   case ISD::ROTR:
1344   case ISD::ROTL:               return visitRotate(N);
1345   case ISD::CTLZ:               return visitCTLZ(N);
1346   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1347   case ISD::CTTZ:               return visitCTTZ(N);
1348   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1349   case ISD::CTPOP:              return visitCTPOP(N);
1350   case ISD::SELECT:             return visitSELECT(N);
1351   case ISD::VSELECT:            return visitVSELECT(N);
1352   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1353   case ISD::SETCC:              return visitSETCC(N);
1354   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1355   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1356   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1357   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1358   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1359   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1360   case ISD::BITCAST:            return visitBITCAST(N);
1361   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1362   case ISD::FADD:               return visitFADD(N);
1363   case ISD::FSUB:               return visitFSUB(N);
1364   case ISD::FMUL:               return visitFMUL(N);
1365   case ISD::FMA:                return visitFMA(N);
1366   case ISD::FDIV:               return visitFDIV(N);
1367   case ISD::FREM:               return visitFREM(N);
1368   case ISD::FSQRT:              return visitFSQRT(N);
1369   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1370   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1371   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1372   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1373   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1374   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1375   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1376   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1377   case ISD::FNEG:               return visitFNEG(N);
1378   case ISD::FABS:               return visitFABS(N);
1379   case ISD::FFLOOR:             return visitFFLOOR(N);
1380   case ISD::FMINNUM:            return visitFMINNUM(N);
1381   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1382   case ISD::FCEIL:              return visitFCEIL(N);
1383   case ISD::FTRUNC:             return visitFTRUNC(N);
1384   case ISD::BRCOND:             return visitBRCOND(N);
1385   case ISD::BR_CC:              return visitBR_CC(N);
1386   case ISD::LOAD:               return visitLOAD(N);
1387   case ISD::STORE:              return visitSTORE(N);
1388   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1389   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1390   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1391   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1392   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1393   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1394   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1395   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1396   case ISD::MGATHER:            return visitMGATHER(N);
1397   case ISD::MLOAD:              return visitMLOAD(N);
1398   case ISD::MSCATTER:           return visitMSCATTER(N);
1399   case ISD::MSTORE:             return visitMSTORE(N);
1400   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1401   }
1402   return SDValue();
1403 }
1404
1405 SDValue DAGCombiner::combine(SDNode *N) {
1406   SDValue RV = visit(N);
1407
1408   // If nothing happened, try a target-specific DAG combine.
1409   if (!RV.getNode()) {
1410     assert(N->getOpcode() != ISD::DELETED_NODE &&
1411            "Node was deleted but visit returned NULL!");
1412
1413     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1414         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1415
1416       // Expose the DAG combiner to the target combiner impls.
1417       TargetLowering::DAGCombinerInfo
1418         DagCombineInfo(DAG, Level, false, this);
1419
1420       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1421     }
1422   }
1423
1424   // If nothing happened still, try promoting the operation.
1425   if (!RV.getNode()) {
1426     switch (N->getOpcode()) {
1427     default: break;
1428     case ISD::ADD:
1429     case ISD::SUB:
1430     case ISD::MUL:
1431     case ISD::AND:
1432     case ISD::OR:
1433     case ISD::XOR:
1434       RV = PromoteIntBinOp(SDValue(N, 0));
1435       break;
1436     case ISD::SHL:
1437     case ISD::SRA:
1438     case ISD::SRL:
1439       RV = PromoteIntShiftOp(SDValue(N, 0));
1440       break;
1441     case ISD::SIGN_EXTEND:
1442     case ISD::ZERO_EXTEND:
1443     case ISD::ANY_EXTEND:
1444       RV = PromoteExtend(SDValue(N, 0));
1445       break;
1446     case ISD::LOAD:
1447       if (PromoteLoad(SDValue(N, 0)))
1448         RV = SDValue(N, 0);
1449       break;
1450     }
1451   }
1452
1453   // If N is a commutative binary node, try commuting it to enable more
1454   // sdisel CSE.
1455   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1456       N->getNumValues() == 1) {
1457     SDValue N0 = N->getOperand(0);
1458     SDValue N1 = N->getOperand(1);
1459
1460     // Constant operands are canonicalized to RHS.
1461     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1462       SDValue Ops[] = {N1, N0};
1463       SDNode *CSENode;
1464       if (const BinaryWithFlagsSDNode *BinNode =
1465               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1466         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1467                                       BinNode->Flags.hasNoUnsignedWrap(),
1468                                       BinNode->Flags.hasNoSignedWrap(),
1469                                       BinNode->Flags.hasExact());
1470       } else {
1471         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1472       }
1473       if (CSENode)
1474         return SDValue(CSENode, 0);
1475     }
1476   }
1477
1478   return RV;
1479 }
1480
1481 /// Given a node, return its input chain if it has one, otherwise return a null
1482 /// sd operand.
1483 static SDValue getInputChainForNode(SDNode *N) {
1484   if (unsigned NumOps = N->getNumOperands()) {
1485     if (N->getOperand(0).getValueType() == MVT::Other)
1486       return N->getOperand(0);
1487     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1488       return N->getOperand(NumOps-1);
1489     for (unsigned i = 1; i < NumOps-1; ++i)
1490       if (N->getOperand(i).getValueType() == MVT::Other)
1491         return N->getOperand(i);
1492   }
1493   return SDValue();
1494 }
1495
1496 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1497   // If N has two operands, where one has an input chain equal to the other,
1498   // the 'other' chain is redundant.
1499   if (N->getNumOperands() == 2) {
1500     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1501       return N->getOperand(0);
1502     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1503       return N->getOperand(1);
1504   }
1505
1506   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1507   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1508   SmallPtrSet<SDNode*, 16> SeenOps;
1509   bool Changed = false;             // If we should replace this token factor.
1510
1511   // Start out with this token factor.
1512   TFs.push_back(N);
1513
1514   // Iterate through token factors.  The TFs grows when new token factors are
1515   // encountered.
1516   for (unsigned i = 0; i < TFs.size(); ++i) {
1517     SDNode *TF = TFs[i];
1518
1519     // Check each of the operands.
1520     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1521       SDValue Op = TF->getOperand(i);
1522
1523       switch (Op.getOpcode()) {
1524       case ISD::EntryToken:
1525         // Entry tokens don't need to be added to the list. They are
1526         // redundant.
1527         Changed = true;
1528         break;
1529
1530       case ISD::TokenFactor:
1531         if (Op.hasOneUse() &&
1532             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1533           // Queue up for processing.
1534           TFs.push_back(Op.getNode());
1535           // Clean up in case the token factor is removed.
1536           AddToWorklist(Op.getNode());
1537           Changed = true;
1538           break;
1539         }
1540         // Fall thru
1541
1542       default:
1543         // Only add if it isn't already in the list.
1544         if (SeenOps.insert(Op.getNode()).second)
1545           Ops.push_back(Op);
1546         else
1547           Changed = true;
1548         break;
1549       }
1550     }
1551   }
1552
1553   SDValue Result;
1554
1555   // If we've changed things around then replace token factor.
1556   if (Changed) {
1557     if (Ops.empty()) {
1558       // The entry token is the only possible outcome.
1559       Result = DAG.getEntryNode();
1560     } else {
1561       // New and improved token factor.
1562       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1563     }
1564
1565     // Add users to worklist if AA is enabled, since it may introduce
1566     // a lot of new chained token factors while removing memory deps.
1567     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1568       : DAG.getSubtarget().useAA();
1569     return CombineTo(N, Result, UseAA /*add to worklist*/);
1570   }
1571
1572   return Result;
1573 }
1574
1575 /// MERGE_VALUES can always be eliminated.
1576 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1577   WorklistRemover DeadNodes(*this);
1578   // Replacing results may cause a different MERGE_VALUES to suddenly
1579   // be CSE'd with N, and carry its uses with it. Iterate until no
1580   // uses remain, to ensure that the node can be safely deleted.
1581   // First add the users of this node to the work list so that they
1582   // can be tried again once they have new operands.
1583   AddUsersToWorklist(N);
1584   do {
1585     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1586       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1587   } while (!N->use_empty());
1588   deleteAndRecombine(N);
1589   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1590 }
1591
1592 static bool isNullConstant(SDValue V) {
1593   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1594   return Const != nullptr && Const->isNullValue();
1595 }
1596
1597 static bool isNullFPConstant(SDValue V) {
1598   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1599   return Const != nullptr && Const->isZero() && !Const->isNegative();
1600 }
1601
1602 static bool isAllOnesConstant(SDValue V) {
1603   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1604   return Const != nullptr && Const->isAllOnesValue();
1605 }
1606
1607 static bool isOneConstant(SDValue V) {
1608   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1609   return Const != nullptr && Const->isOne();
1610 }
1611
1612 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1613 /// ContantSDNode pointer else nullptr.
1614 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1615   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1616   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1617 }
1618
1619 SDValue DAGCombiner::visitADD(SDNode *N) {
1620   SDValue N0 = N->getOperand(0);
1621   SDValue N1 = N->getOperand(1);
1622   EVT VT = N0.getValueType();
1623
1624   // fold vector ops
1625   if (VT.isVector()) {
1626     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1627       return FoldedVOp;
1628
1629     // fold (add x, 0) -> x, vector edition
1630     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1631       return N0;
1632     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1633       return N1;
1634   }
1635
1636   // fold (add x, undef) -> undef
1637   if (N0.getOpcode() == ISD::UNDEF)
1638     return N0;
1639   if (N1.getOpcode() == ISD::UNDEF)
1640     return N1;
1641   // fold (add c1, c2) -> c1+c2
1642   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1643   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1644   if (N0C && N1C)
1645     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1646   // canonicalize constant to RHS
1647   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1648      !isConstantIntBuildVectorOrConstantInt(N1))
1649     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1650   // fold (add x, 0) -> x
1651   if (isNullConstant(N1))
1652     return N0;
1653   // fold (add Sym, c) -> Sym+c
1654   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1655     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1656         GA->getOpcode() == ISD::GlobalAddress)
1657       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1658                                   GA->getOffset() +
1659                                     (uint64_t)N1C->getSExtValue());
1660   // fold ((c1-A)+c2) -> (c1+c2)-A
1661   if (N1C && N0.getOpcode() == ISD::SUB)
1662     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1663       SDLoc DL(N);
1664       return DAG.getNode(ISD::SUB, DL, VT,
1665                          DAG.getConstant(N1C->getAPIntValue()+
1666                                          N0C->getAPIntValue(), DL, VT),
1667                          N0.getOperand(1));
1668     }
1669   // reassociate add
1670   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1671     return RADD;
1672   // fold ((0-A) + B) -> B-A
1673   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1674     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1675   // fold (A + (0-B)) -> A-B
1676   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1677     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1678   // fold (A+(B-A)) -> B
1679   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1680     return N1.getOperand(0);
1681   // fold ((B-A)+A) -> B
1682   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1683     return N0.getOperand(0);
1684   // fold (A+(B-(A+C))) to (B-C)
1685   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1686       N0 == N1.getOperand(1).getOperand(0))
1687     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1688                        N1.getOperand(1).getOperand(1));
1689   // fold (A+(B-(C+A))) to (B-C)
1690   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1691       N0 == N1.getOperand(1).getOperand(1))
1692     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1693                        N1.getOperand(1).getOperand(0));
1694   // fold (A+((B-A)+or-C)) to (B+or-C)
1695   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1696       N1.getOperand(0).getOpcode() == ISD::SUB &&
1697       N0 == N1.getOperand(0).getOperand(1))
1698     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1699                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1700
1701   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1702   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1703     SDValue N00 = N0.getOperand(0);
1704     SDValue N01 = N0.getOperand(1);
1705     SDValue N10 = N1.getOperand(0);
1706     SDValue N11 = N1.getOperand(1);
1707
1708     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1709       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1710                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1711                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1712   }
1713
1714   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1715     return SDValue(N, 0);
1716
1717   // fold (a+b) -> (a|b) iff a and b share no bits.
1718   if (VT.isInteger() && !VT.isVector()) {
1719     APInt LHSZero, LHSOne;
1720     APInt RHSZero, RHSOne;
1721     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1722
1723     if (LHSZero.getBoolValue()) {
1724       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1725
1726       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1727       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1728       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1729         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1730           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1731       }
1732     }
1733   }
1734
1735   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1736   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1737       isNullConstant(N1.getOperand(0).getOperand(0)))
1738     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1739                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1740                                    N1.getOperand(0).getOperand(1),
1741                                    N1.getOperand(1)));
1742   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1743       isNullConstant(N0.getOperand(0).getOperand(0)))
1744     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1745                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1746                                    N0.getOperand(0).getOperand(1),
1747                                    N0.getOperand(1)));
1748
1749   if (N1.getOpcode() == ISD::AND) {
1750     SDValue AndOp0 = N1.getOperand(0);
1751     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1752     unsigned DestBits = VT.getScalarType().getSizeInBits();
1753
1754     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1755     // and similar xforms where the inner op is either ~0 or 0.
1756     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1757       SDLoc DL(N);
1758       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1759     }
1760   }
1761
1762   // add (sext i1), X -> sub X, (zext i1)
1763   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1764       N0.getOperand(0).getValueType() == MVT::i1 &&
1765       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1766     SDLoc DL(N);
1767     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1768     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1769   }
1770
1771   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1772   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1773     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1774     if (TN->getVT() == MVT::i1) {
1775       SDLoc DL(N);
1776       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1777                                  DAG.getConstant(1, DL, VT));
1778       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1779     }
1780   }
1781
1782   return SDValue();
1783 }
1784
1785 SDValue DAGCombiner::visitADDC(SDNode *N) {
1786   SDValue N0 = N->getOperand(0);
1787   SDValue N1 = N->getOperand(1);
1788   EVT VT = N0.getValueType();
1789
1790   // If the flag result is dead, turn this into an ADD.
1791   if (!N->hasAnyUseOfValue(1))
1792     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1793                      DAG.getNode(ISD::CARRY_FALSE,
1794                                  SDLoc(N), MVT::Glue));
1795
1796   // canonicalize constant to RHS.
1797   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1798   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1799   if (N0C && !N1C)
1800     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1801
1802   // fold (addc x, 0) -> x + no carry out
1803   if (isNullConstant(N1))
1804     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1805                                         SDLoc(N), MVT::Glue));
1806
1807   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1808   APInt LHSZero, LHSOne;
1809   APInt RHSZero, RHSOne;
1810   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1811
1812   if (LHSZero.getBoolValue()) {
1813     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1814
1815     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1816     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1817     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1818       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1819                        DAG.getNode(ISD::CARRY_FALSE,
1820                                    SDLoc(N), MVT::Glue));
1821   }
1822
1823   return SDValue();
1824 }
1825
1826 SDValue DAGCombiner::visitADDE(SDNode *N) {
1827   SDValue N0 = N->getOperand(0);
1828   SDValue N1 = N->getOperand(1);
1829   SDValue CarryIn = N->getOperand(2);
1830
1831   // canonicalize constant to RHS
1832   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1833   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1834   if (N0C && !N1C)
1835     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1836                        N1, N0, CarryIn);
1837
1838   // fold (adde x, y, false) -> (addc x, y)
1839   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1840     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1841
1842   return SDValue();
1843 }
1844
1845 // Since it may not be valid to emit a fold to zero for vector initializers
1846 // check if we can before folding.
1847 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1848                              SelectionDAG &DAG,
1849                              bool LegalOperations, bool LegalTypes) {
1850   if (!VT.isVector())
1851     return DAG.getConstant(0, DL, VT);
1852   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1853     return DAG.getConstant(0, DL, VT);
1854   return SDValue();
1855 }
1856
1857 SDValue DAGCombiner::visitSUB(SDNode *N) {
1858   SDValue N0 = N->getOperand(0);
1859   SDValue N1 = N->getOperand(1);
1860   EVT VT = N0.getValueType();
1861
1862   // fold vector ops
1863   if (VT.isVector()) {
1864     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1865       return FoldedVOp;
1866
1867     // fold (sub x, 0) -> x, vector edition
1868     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1869       return N0;
1870   }
1871
1872   // fold (sub x, x) -> 0
1873   // FIXME: Refactor this and xor and other similar operations together.
1874   if (N0 == N1)
1875     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1876   // fold (sub c1, c2) -> c1-c2
1877   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1878   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1879   if (N0C && N1C)
1880     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1881   // fold (sub x, c) -> (add x, -c)
1882   if (N1C) {
1883     SDLoc DL(N);
1884     return DAG.getNode(ISD::ADD, DL, VT, N0,
1885                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1886   }
1887   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1888   if (isAllOnesConstant(N0))
1889     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1890   // fold A-(A-B) -> B
1891   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1892     return N1.getOperand(1);
1893   // fold (A+B)-A -> B
1894   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1895     return N0.getOperand(1);
1896   // fold (A+B)-B -> A
1897   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1898     return N0.getOperand(0);
1899   // fold C2-(A+C1) -> (C2-C1)-A
1900   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1901     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1902   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1903     SDLoc DL(N);
1904     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1905                                    DL, VT);
1906     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1907                        N1.getOperand(0));
1908   }
1909   // fold ((A+(B+or-C))-B) -> A+or-C
1910   if (N0.getOpcode() == ISD::ADD &&
1911       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1912        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1913       N0.getOperand(1).getOperand(0) == N1)
1914     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1915                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1916   // fold ((A+(C+B))-B) -> A+C
1917   if (N0.getOpcode() == ISD::ADD &&
1918       N0.getOperand(1).getOpcode() == ISD::ADD &&
1919       N0.getOperand(1).getOperand(1) == N1)
1920     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1921                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1922   // fold ((A-(B-C))-C) -> A-B
1923   if (N0.getOpcode() == ISD::SUB &&
1924       N0.getOperand(1).getOpcode() == ISD::SUB &&
1925       N0.getOperand(1).getOperand(1) == N1)
1926     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1927                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1928
1929   // If either operand of a sub is undef, the result is undef
1930   if (N0.getOpcode() == ISD::UNDEF)
1931     return N0;
1932   if (N1.getOpcode() == ISD::UNDEF)
1933     return N1;
1934
1935   // If the relocation model supports it, consider symbol offsets.
1936   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1937     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1938       // fold (sub Sym, c) -> Sym-c
1939       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1940         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1941                                     GA->getOffset() -
1942                                       (uint64_t)N1C->getSExtValue());
1943       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1944       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1945         if (GA->getGlobal() == GB->getGlobal())
1946           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1947                                  SDLoc(N), VT);
1948     }
1949
1950   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1951   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1952     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1953     if (TN->getVT() == MVT::i1) {
1954       SDLoc DL(N);
1955       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1956                                  DAG.getConstant(1, DL, VT));
1957       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1958     }
1959   }
1960
1961   return SDValue();
1962 }
1963
1964 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1965   SDValue N0 = N->getOperand(0);
1966   SDValue N1 = N->getOperand(1);
1967   EVT VT = N0.getValueType();
1968
1969   // If the flag result is dead, turn this into an SUB.
1970   if (!N->hasAnyUseOfValue(1))
1971     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1972                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1973                                  MVT::Glue));
1974
1975   // fold (subc x, x) -> 0 + no borrow
1976   if (N0 == N1) {
1977     SDLoc DL(N);
1978     return CombineTo(N, DAG.getConstant(0, DL, VT),
1979                      DAG.getNode(ISD::CARRY_FALSE, DL,
1980                                  MVT::Glue));
1981   }
1982
1983   // fold (subc x, 0) -> x + no borrow
1984   if (isNullConstant(N1))
1985     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1986                                         MVT::Glue));
1987
1988   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1989   if (isAllOnesConstant(N0))
1990     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1991                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1992                                  MVT::Glue));
1993
1994   return SDValue();
1995 }
1996
1997 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1998   SDValue N0 = N->getOperand(0);
1999   SDValue N1 = N->getOperand(1);
2000   SDValue CarryIn = N->getOperand(2);
2001
2002   // fold (sube x, y, false) -> (subc x, y)
2003   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2004     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2005
2006   return SDValue();
2007 }
2008
2009 SDValue DAGCombiner::visitMUL(SDNode *N) {
2010   SDValue N0 = N->getOperand(0);
2011   SDValue N1 = N->getOperand(1);
2012   EVT VT = N0.getValueType();
2013
2014   // fold (mul x, undef) -> 0
2015   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2016     return DAG.getConstant(0, SDLoc(N), VT);
2017
2018   bool N0IsConst = false;
2019   bool N1IsConst = false;
2020   bool N1IsOpaqueConst = false;
2021   bool N0IsOpaqueConst = false;
2022   APInt ConstValue0, ConstValue1;
2023   // fold vector ops
2024   if (VT.isVector()) {
2025     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2026       return FoldedVOp;
2027
2028     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2029     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2030   } else {
2031     N0IsConst = isa<ConstantSDNode>(N0);
2032     if (N0IsConst) {
2033       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2034       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2035     }
2036     N1IsConst = isa<ConstantSDNode>(N1);
2037     if (N1IsConst) {
2038       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2039       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2040     }
2041   }
2042
2043   // fold (mul c1, c2) -> c1*c2
2044   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2045     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2046                                       N0.getNode(), N1.getNode());
2047
2048   // canonicalize constant to RHS (vector doesn't have to splat)
2049   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2050      !isConstantIntBuildVectorOrConstantInt(N1))
2051     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2052   // fold (mul x, 0) -> 0
2053   if (N1IsConst && ConstValue1 == 0)
2054     return N1;
2055   // We require a splat of the entire scalar bit width for non-contiguous
2056   // bit patterns.
2057   bool IsFullSplat =
2058     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2059   // fold (mul x, 1) -> x
2060   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2061     return N0;
2062   // fold (mul x, -1) -> 0-x
2063   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2064     SDLoc DL(N);
2065     return DAG.getNode(ISD::SUB, DL, VT,
2066                        DAG.getConstant(0, DL, VT), N0);
2067   }
2068   // fold (mul x, (1 << c)) -> x << c
2069   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2070       IsFullSplat) {
2071     SDLoc DL(N);
2072     return DAG.getNode(ISD::SHL, DL, VT, N0,
2073                        DAG.getConstant(ConstValue1.logBase2(), DL,
2074                                        getShiftAmountTy(N0.getValueType())));
2075   }
2076   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2077   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2078       IsFullSplat) {
2079     unsigned Log2Val = (-ConstValue1).logBase2();
2080     SDLoc DL(N);
2081     // FIXME: If the input is something that is easily negated (e.g. a
2082     // single-use add), we should put the negate there.
2083     return DAG.getNode(ISD::SUB, DL, VT,
2084                        DAG.getConstant(0, DL, VT),
2085                        DAG.getNode(ISD::SHL, DL, VT, N0,
2086                             DAG.getConstant(Log2Val, DL,
2087                                       getShiftAmountTy(N0.getValueType()))));
2088   }
2089
2090   APInt Val;
2091   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2092   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2093       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2094                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2095     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2096                              N1, N0.getOperand(1));
2097     AddToWorklist(C3.getNode());
2098     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2099                        N0.getOperand(0), C3);
2100   }
2101
2102   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2103   // use.
2104   {
2105     SDValue Sh(nullptr,0), Y(nullptr,0);
2106     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2107     if (N0.getOpcode() == ISD::SHL &&
2108         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2109                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2110         N0.getNode()->hasOneUse()) {
2111       Sh = N0; Y = N1;
2112     } else if (N1.getOpcode() == ISD::SHL &&
2113                isa<ConstantSDNode>(N1.getOperand(1)) &&
2114                N1.getNode()->hasOneUse()) {
2115       Sh = N1; Y = N0;
2116     }
2117
2118     if (Sh.getNode()) {
2119       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2120                                 Sh.getOperand(0), Y);
2121       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2122                          Mul, Sh.getOperand(1));
2123     }
2124   }
2125
2126   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2127   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2128       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2129                      isa<ConstantSDNode>(N0.getOperand(1))))
2130     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2131                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2132                                    N0.getOperand(0), N1),
2133                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2134                                    N0.getOperand(1), N1));
2135
2136   // reassociate mul
2137   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2138     return RMUL;
2139
2140   return SDValue();
2141 }
2142
2143 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2144   SDValue N0 = N->getOperand(0);
2145   SDValue N1 = N->getOperand(1);
2146   EVT VT = N->getValueType(0);
2147
2148   // fold vector ops
2149   if (VT.isVector())
2150     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2151       return FoldedVOp;
2152
2153   // fold (sdiv c1, c2) -> c1/c2
2154   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2155   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2156   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2157     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2158   // fold (sdiv X, 1) -> X
2159   if (N1C && N1C->isOne())
2160     return N0;
2161   // fold (sdiv X, -1) -> 0-X
2162   if (N1C && N1C->isAllOnesValue()) {
2163     SDLoc DL(N);
2164     return DAG.getNode(ISD::SUB, DL, VT,
2165                        DAG.getConstant(0, DL, VT), N0);
2166   }
2167   // If we know the sign bits of both operands are zero, strength reduce to a
2168   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2169   if (!VT.isVector()) {
2170     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2171       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2172                          N0, N1);
2173   }
2174
2175   // fold (sdiv X, pow2) -> simple ops after legalize
2176   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2177       (N1C->getAPIntValue().isPowerOf2() ||
2178        (-N1C->getAPIntValue()).isPowerOf2())) {
2179     // If dividing by powers of two is cheap, then don't perform the following
2180     // fold.
2181     if (TLI.isPow2SDivCheap())
2182       return SDValue();
2183
2184     // Target-specific implementation of sdiv x, pow2.
2185     SDValue Res = BuildSDIVPow2(N);
2186     if (Res.getNode())
2187       return Res;
2188
2189     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2190     SDLoc DL(N);
2191
2192     // Splat the sign bit into the register
2193     SDValue SGN =
2194         DAG.getNode(ISD::SRA, DL, VT, N0,
2195                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2196                                     getShiftAmountTy(N0.getValueType())));
2197     AddToWorklist(SGN.getNode());
2198
2199     // Add (N0 < 0) ? abs2 - 1 : 0;
2200     SDValue SRL =
2201         DAG.getNode(ISD::SRL, DL, VT, SGN,
2202                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2203                                     getShiftAmountTy(SGN.getValueType())));
2204     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2205     AddToWorklist(SRL.getNode());
2206     AddToWorklist(ADD.getNode());    // Divide by pow2
2207     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2208                   DAG.getConstant(lg2, DL,
2209                                   getShiftAmountTy(ADD.getValueType())));
2210
2211     // If we're dividing by a positive value, we're done.  Otherwise, we must
2212     // negate the result.
2213     if (N1C->getAPIntValue().isNonNegative())
2214       return SRA;
2215
2216     AddToWorklist(SRA.getNode());
2217     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2218   }
2219
2220   // If integer divide is expensive and we satisfy the requirements, emit an
2221   // alternate sequence.
2222   if (N1C && !TLI.isIntDivCheap()) {
2223     SDValue Op = BuildSDIV(N);
2224     if (Op.getNode()) return Op;
2225   }
2226
2227   // undef / X -> 0
2228   if (N0.getOpcode() == ISD::UNDEF)
2229     return DAG.getConstant(0, SDLoc(N), VT);
2230   // X / undef -> undef
2231   if (N1.getOpcode() == ISD::UNDEF)
2232     return N1;
2233
2234   return SDValue();
2235 }
2236
2237 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2238   SDValue N0 = N->getOperand(0);
2239   SDValue N1 = N->getOperand(1);
2240   EVT VT = N->getValueType(0);
2241
2242   // fold vector ops
2243   if (VT.isVector())
2244     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2245       return FoldedVOp;
2246
2247   // fold (udiv c1, c2) -> c1/c2
2248   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2249   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2250   if (N0C && N1C)
2251     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2252                                                     N0C, N1C))
2253       return Folded;
2254   // fold (udiv x, (1 << c)) -> x >>u c
2255   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2256     SDLoc DL(N);
2257     return DAG.getNode(ISD::SRL, DL, VT, N0,
2258                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2259                                        getShiftAmountTy(N0.getValueType())));
2260   }
2261   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2262   if (N1.getOpcode() == ISD::SHL) {
2263     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2264       if (SHC->getAPIntValue().isPowerOf2()) {
2265         EVT ADDVT = N1.getOperand(1).getValueType();
2266         SDLoc DL(N);
2267         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2268                                   N1.getOperand(1),
2269                                   DAG.getConstant(SHC->getAPIntValue()
2270                                                                   .logBase2(),
2271                                                   DL, ADDVT));
2272         AddToWorklist(Add.getNode());
2273         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2274       }
2275     }
2276   }
2277   // fold (udiv x, c) -> alternate
2278   if (N1C && !TLI.isIntDivCheap()) {
2279     SDValue Op = BuildUDIV(N);
2280     if (Op.getNode()) return Op;
2281   }
2282
2283   // undef / X -> 0
2284   if (N0.getOpcode() == ISD::UNDEF)
2285     return DAG.getConstant(0, SDLoc(N), VT);
2286   // X / undef -> undef
2287   if (N1.getOpcode() == ISD::UNDEF)
2288     return N1;
2289
2290   return SDValue();
2291 }
2292
2293 SDValue DAGCombiner::visitSREM(SDNode *N) {
2294   SDValue N0 = N->getOperand(0);
2295   SDValue N1 = N->getOperand(1);
2296   EVT VT = N->getValueType(0);
2297
2298   // fold (srem c1, c2) -> c1%c2
2299   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2300   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2301   if (N0C && N1C)
2302     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2303                                                     N0C, N1C))
2304       return Folded;
2305   // If we know the sign bits of both operands are zero, strength reduce to a
2306   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2307   if (!VT.isVector()) {
2308     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2309       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2310   }
2311
2312   // If X/C can be simplified by the division-by-constant logic, lower
2313   // X%C to the equivalent of X-X/C*C.
2314   if (N1C && !N1C->isNullValue()) {
2315     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2316     AddToWorklist(Div.getNode());
2317     SDValue OptimizedDiv = combine(Div.getNode());
2318     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2319       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2320                                 OptimizedDiv, N1);
2321       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2322       AddToWorklist(Mul.getNode());
2323       return Sub;
2324     }
2325   }
2326
2327   // undef % X -> 0
2328   if (N0.getOpcode() == ISD::UNDEF)
2329     return DAG.getConstant(0, SDLoc(N), VT);
2330   // X % undef -> undef
2331   if (N1.getOpcode() == ISD::UNDEF)
2332     return N1;
2333
2334   return SDValue();
2335 }
2336
2337 SDValue DAGCombiner::visitUREM(SDNode *N) {
2338   SDValue N0 = N->getOperand(0);
2339   SDValue N1 = N->getOperand(1);
2340   EVT VT = N->getValueType(0);
2341
2342   // fold (urem c1, c2) -> c1%c2
2343   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2344   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2345   if (N0C && N1C)
2346     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2347                                                     N0C, N1C))
2348       return Folded;
2349   // fold (urem x, pow2) -> (and x, pow2-1)
2350   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2351       N1C->getAPIntValue().isPowerOf2()) {
2352     SDLoc DL(N);
2353     return DAG.getNode(ISD::AND, DL, VT, N0,
2354                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2355   }
2356   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2357   if (N1.getOpcode() == ISD::SHL) {
2358     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2359       if (SHC->getAPIntValue().isPowerOf2()) {
2360         SDLoc DL(N);
2361         SDValue Add =
2362           DAG.getNode(ISD::ADD, DL, VT, N1,
2363                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2364                                  VT));
2365         AddToWorklist(Add.getNode());
2366         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2367       }
2368     }
2369   }
2370
2371   // If X/C can be simplified by the division-by-constant logic, lower
2372   // X%C to the equivalent of X-X/C*C.
2373   if (N1C && !N1C->isNullValue()) {
2374     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2375     AddToWorklist(Div.getNode());
2376     SDValue OptimizedDiv = combine(Div.getNode());
2377     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2378       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2379                                 OptimizedDiv, N1);
2380       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2381       AddToWorklist(Mul.getNode());
2382       return Sub;
2383     }
2384   }
2385
2386   // undef % X -> 0
2387   if (N0.getOpcode() == ISD::UNDEF)
2388     return DAG.getConstant(0, SDLoc(N), VT);
2389   // X % undef -> undef
2390   if (N1.getOpcode() == ISD::UNDEF)
2391     return N1;
2392
2393   return SDValue();
2394 }
2395
2396 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2397   SDValue N0 = N->getOperand(0);
2398   SDValue N1 = N->getOperand(1);
2399   EVT VT = N->getValueType(0);
2400   SDLoc DL(N);
2401
2402   // fold (mulhs x, 0) -> 0
2403   if (isNullConstant(N1))
2404     return N1;
2405   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2406   if (isOneConstant(N1)) {
2407     SDLoc DL(N);
2408     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2409                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2410                                        DL,
2411                                        getShiftAmountTy(N0.getValueType())));
2412   }
2413   // fold (mulhs x, undef) -> 0
2414   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2415     return DAG.getConstant(0, SDLoc(N), VT);
2416
2417   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2418   // plus a shift.
2419   if (VT.isSimple() && !VT.isVector()) {
2420     MVT Simple = VT.getSimpleVT();
2421     unsigned SimpleSize = Simple.getSizeInBits();
2422     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2423     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2424       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2425       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2426       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2427       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2428             DAG.getConstant(SimpleSize, DL,
2429                             getShiftAmountTy(N1.getValueType())));
2430       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2431     }
2432   }
2433
2434   return SDValue();
2435 }
2436
2437 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2438   SDValue N0 = N->getOperand(0);
2439   SDValue N1 = N->getOperand(1);
2440   EVT VT = N->getValueType(0);
2441   SDLoc DL(N);
2442
2443   // fold (mulhu x, 0) -> 0
2444   if (isNullConstant(N1))
2445     return N1;
2446   // fold (mulhu x, 1) -> 0
2447   if (isOneConstant(N1))
2448     return DAG.getConstant(0, DL, N0.getValueType());
2449   // fold (mulhu x, undef) -> 0
2450   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2451     return DAG.getConstant(0, DL, VT);
2452
2453   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2454   // plus a shift.
2455   if (VT.isSimple() && !VT.isVector()) {
2456     MVT Simple = VT.getSimpleVT();
2457     unsigned SimpleSize = Simple.getSizeInBits();
2458     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2459     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2460       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2461       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2462       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2463       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2464             DAG.getConstant(SimpleSize, DL,
2465                             getShiftAmountTy(N1.getValueType())));
2466       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2467     }
2468   }
2469
2470   return SDValue();
2471 }
2472
2473 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2474 /// give the opcodes for the two computations that are being performed. Return
2475 /// true if a simplification was made.
2476 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2477                                                 unsigned HiOp) {
2478   // If the high half is not needed, just compute the low half.
2479   bool HiExists = N->hasAnyUseOfValue(1);
2480   if (!HiExists &&
2481       (!LegalOperations ||
2482        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2483     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2484     return CombineTo(N, Res, Res);
2485   }
2486
2487   // If the low half is not needed, just compute the high half.
2488   bool LoExists = N->hasAnyUseOfValue(0);
2489   if (!LoExists &&
2490       (!LegalOperations ||
2491        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2492     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2493     return CombineTo(N, Res, Res);
2494   }
2495
2496   // If both halves are used, return as it is.
2497   if (LoExists && HiExists)
2498     return SDValue();
2499
2500   // If the two computed results can be simplified separately, separate them.
2501   if (LoExists) {
2502     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2503     AddToWorklist(Lo.getNode());
2504     SDValue LoOpt = combine(Lo.getNode());
2505     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2506         (!LegalOperations ||
2507          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2508       return CombineTo(N, LoOpt, LoOpt);
2509   }
2510
2511   if (HiExists) {
2512     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2513     AddToWorklist(Hi.getNode());
2514     SDValue HiOpt = combine(Hi.getNode());
2515     if (HiOpt.getNode() && HiOpt != Hi &&
2516         (!LegalOperations ||
2517          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2518       return CombineTo(N, HiOpt, HiOpt);
2519   }
2520
2521   return SDValue();
2522 }
2523
2524 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2525   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2526   if (Res.getNode()) return Res;
2527
2528   EVT VT = N->getValueType(0);
2529   SDLoc DL(N);
2530
2531   // If the type is twice as wide is legal, transform the mulhu to a wider
2532   // multiply plus a shift.
2533   if (VT.isSimple() && !VT.isVector()) {
2534     MVT Simple = VT.getSimpleVT();
2535     unsigned SimpleSize = Simple.getSizeInBits();
2536     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2537     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2538       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2539       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2540       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2541       // Compute the high part as N1.
2542       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2543             DAG.getConstant(SimpleSize, DL,
2544                             getShiftAmountTy(Lo.getValueType())));
2545       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2546       // Compute the low part as N0.
2547       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2548       return CombineTo(N, Lo, Hi);
2549     }
2550   }
2551
2552   return SDValue();
2553 }
2554
2555 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2556   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2557   if (Res.getNode()) return Res;
2558
2559   EVT VT = N->getValueType(0);
2560   SDLoc DL(N);
2561
2562   // If the type is twice as wide is legal, transform the mulhu to a wider
2563   // multiply plus a shift.
2564   if (VT.isSimple() && !VT.isVector()) {
2565     MVT Simple = VT.getSimpleVT();
2566     unsigned SimpleSize = Simple.getSizeInBits();
2567     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2568     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2569       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2570       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2571       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2572       // Compute the high part as N1.
2573       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2574             DAG.getConstant(SimpleSize, DL,
2575                             getShiftAmountTy(Lo.getValueType())));
2576       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2577       // Compute the low part as N0.
2578       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2579       return CombineTo(N, Lo, Hi);
2580     }
2581   }
2582
2583   return SDValue();
2584 }
2585
2586 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2587   // (smulo x, 2) -> (saddo x, x)
2588   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2589     if (C2->getAPIntValue() == 2)
2590       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2591                          N->getOperand(0), N->getOperand(0));
2592
2593   return SDValue();
2594 }
2595
2596 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2597   // (umulo x, 2) -> (uaddo x, x)
2598   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2599     if (C2->getAPIntValue() == 2)
2600       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2601                          N->getOperand(0), N->getOperand(0));
2602
2603   return SDValue();
2604 }
2605
2606 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2607   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2608   if (Res.getNode()) return Res;
2609
2610   return SDValue();
2611 }
2612
2613 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2614   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2615   if (Res.getNode()) return Res;
2616
2617   return SDValue();
2618 }
2619
2620 /// If this is a binary operator with two operands of the same opcode, try to
2621 /// simplify it.
2622 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2623   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2624   EVT VT = N0.getValueType();
2625   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2626
2627   // Bail early if none of these transforms apply.
2628   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2629
2630   // For each of OP in AND/OR/XOR:
2631   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2632   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2633   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2634   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2635   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2636   //
2637   // do not sink logical op inside of a vector extend, since it may combine
2638   // into a vsetcc.
2639   EVT Op0VT = N0.getOperand(0).getValueType();
2640   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2641        N0.getOpcode() == ISD::SIGN_EXTEND ||
2642        N0.getOpcode() == ISD::BSWAP ||
2643        // Avoid infinite looping with PromoteIntBinOp.
2644        (N0.getOpcode() == ISD::ANY_EXTEND &&
2645         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2646        (N0.getOpcode() == ISD::TRUNCATE &&
2647         (!TLI.isZExtFree(VT, Op0VT) ||
2648          !TLI.isTruncateFree(Op0VT, VT)) &&
2649         TLI.isTypeLegal(Op0VT))) &&
2650       !VT.isVector() &&
2651       Op0VT == N1.getOperand(0).getValueType() &&
2652       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2653     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2654                                  N0.getOperand(0).getValueType(),
2655                                  N0.getOperand(0), N1.getOperand(0));
2656     AddToWorklist(ORNode.getNode());
2657     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2658   }
2659
2660   // For each of OP in SHL/SRL/SRA/AND...
2661   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2662   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2663   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2664   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2665        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2666       N0.getOperand(1) == N1.getOperand(1)) {
2667     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2668                                  N0.getOperand(0).getValueType(),
2669                                  N0.getOperand(0), N1.getOperand(0));
2670     AddToWorklist(ORNode.getNode());
2671     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2672                        ORNode, N0.getOperand(1));
2673   }
2674
2675   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2676   // Only perform this optimization after type legalization and before
2677   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2678   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2679   // we don't want to undo this promotion.
2680   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2681   // on scalars.
2682   if ((N0.getOpcode() == ISD::BITCAST ||
2683        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2684       Level == AfterLegalizeTypes) {
2685     SDValue In0 = N0.getOperand(0);
2686     SDValue In1 = N1.getOperand(0);
2687     EVT In0Ty = In0.getValueType();
2688     EVT In1Ty = In1.getValueType();
2689     SDLoc DL(N);
2690     // If both incoming values are integers, and the original types are the
2691     // same.
2692     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2693       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2694       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2695       AddToWorklist(Op.getNode());
2696       return BC;
2697     }
2698   }
2699
2700   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2701   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2702   // If both shuffles use the same mask, and both shuffle within a single
2703   // vector, then it is worthwhile to move the swizzle after the operation.
2704   // The type-legalizer generates this pattern when loading illegal
2705   // vector types from memory. In many cases this allows additional shuffle
2706   // optimizations.
2707   // There are other cases where moving the shuffle after the xor/and/or
2708   // is profitable even if shuffles don't perform a swizzle.
2709   // If both shuffles use the same mask, and both shuffles have the same first
2710   // or second operand, then it might still be profitable to move the shuffle
2711   // after the xor/and/or operation.
2712   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2713     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2714     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2715
2716     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2717            "Inputs to shuffles are not the same type");
2718
2719     // Check that both shuffles use the same mask. The masks are known to be of
2720     // the same length because the result vector type is the same.
2721     // Check also that shuffles have only one use to avoid introducing extra
2722     // instructions.
2723     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2724         SVN0->getMask().equals(SVN1->getMask())) {
2725       SDValue ShOp = N0->getOperand(1);
2726
2727       // Don't try to fold this node if it requires introducing a
2728       // build vector of all zeros that might be illegal at this stage.
2729       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2730         if (!LegalTypes)
2731           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2732         else
2733           ShOp = SDValue();
2734       }
2735
2736       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2737       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2738       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2739       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2740         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2741                                       N0->getOperand(0), N1->getOperand(0));
2742         AddToWorklist(NewNode.getNode());
2743         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2744                                     &SVN0->getMask()[0]);
2745       }
2746
2747       // Don't try to fold this node if it requires introducing a
2748       // build vector of all zeros that might be illegal at this stage.
2749       ShOp = N0->getOperand(0);
2750       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2751         if (!LegalTypes)
2752           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2753         else
2754           ShOp = SDValue();
2755       }
2756
2757       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2758       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2759       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2760       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2761         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2762                                       N0->getOperand(1), N1->getOperand(1));
2763         AddToWorklist(NewNode.getNode());
2764         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2765                                     &SVN0->getMask()[0]);
2766       }
2767     }
2768   }
2769
2770   return SDValue();
2771 }
2772
2773 /// This contains all DAGCombine rules which reduce two values combined by
2774 /// an And operation to a single value. This makes them reusable in the context
2775 /// of visitSELECT(). Rules involving constants are not included as
2776 /// visitSELECT() already handles those cases.
2777 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2778                                   SDNode *LocReference) {
2779   EVT VT = N1.getValueType();
2780
2781   // fold (and x, undef) -> 0
2782   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2783     return DAG.getConstant(0, SDLoc(LocReference), VT);
2784   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2785   SDValue LL, LR, RL, RR, CC0, CC1;
2786   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2787     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2788     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2789
2790     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2791         LL.getValueType().isInteger()) {
2792       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2793       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2794         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2795                                      LR.getValueType(), LL, RL);
2796         AddToWorklist(ORNode.getNode());
2797         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2798       }
2799       if (isAllOnesConstant(LR)) {
2800         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2801         if (Op1 == ISD::SETEQ) {
2802           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2803                                         LR.getValueType(), LL, RL);
2804           AddToWorklist(ANDNode.getNode());
2805           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2806         }
2807         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2808         if (Op1 == ISD::SETGT) {
2809           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2810                                        LR.getValueType(), LL, RL);
2811           AddToWorklist(ORNode.getNode());
2812           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2813         }
2814       }
2815     }
2816     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2817     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2818         Op0 == Op1 && LL.getValueType().isInteger() &&
2819       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2820                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2821       SDLoc DL(N0);
2822       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2823                                     LL, DAG.getConstant(1, DL,
2824                                                         LL.getValueType()));
2825       AddToWorklist(ADDNode.getNode());
2826       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2827                           DAG.getConstant(2, DL, LL.getValueType()),
2828                           ISD::SETUGE);
2829     }
2830     // canonicalize equivalent to ll == rl
2831     if (LL == RR && LR == RL) {
2832       Op1 = ISD::getSetCCSwappedOperands(Op1);
2833       std::swap(RL, RR);
2834     }
2835     if (LL == RL && LR == RR) {
2836       bool isInteger = LL.getValueType().isInteger();
2837       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2838       if (Result != ISD::SETCC_INVALID &&
2839           (!LegalOperations ||
2840            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2841             TLI.isOperationLegal(ISD::SETCC,
2842                             getSetCCResultType(N0.getSimpleValueType())))))
2843         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2844                             LL, LR, Result);
2845     }
2846   }
2847
2848   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2849       VT.getSizeInBits() <= 64) {
2850     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2851       APInt ADDC = ADDI->getAPIntValue();
2852       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2853         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2854         // immediate for an add, but it is legal if its top c2 bits are set,
2855         // transform the ADD so the immediate doesn't need to be materialized
2856         // in a register.
2857         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2858           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2859                                              SRLI->getZExtValue());
2860           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2861             ADDC |= Mask;
2862             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2863               SDLoc DL(N0);
2864               SDValue NewAdd =
2865                 DAG.getNode(ISD::ADD, DL, VT,
2866                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2867               CombineTo(N0.getNode(), NewAdd);
2868               // Return N so it doesn't get rechecked!
2869               return SDValue(LocReference, 0);
2870             }
2871           }
2872         }
2873       }
2874     }
2875   }
2876
2877   return SDValue();
2878 }
2879
2880 SDValue DAGCombiner::visitAND(SDNode *N) {
2881   SDValue N0 = N->getOperand(0);
2882   SDValue N1 = N->getOperand(1);
2883   EVT VT = N1.getValueType();
2884
2885   // fold vector ops
2886   if (VT.isVector()) {
2887     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2888       return FoldedVOp;
2889
2890     // fold (and x, 0) -> 0, vector edition
2891     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2892       // do not return N0, because undef node may exist in N0
2893       return DAG.getConstant(
2894           APInt::getNullValue(
2895               N0.getValueType().getScalarType().getSizeInBits()),
2896           SDLoc(N), N0.getValueType());
2897     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2898       // do not return N1, because undef node may exist in N1
2899       return DAG.getConstant(
2900           APInt::getNullValue(
2901               N1.getValueType().getScalarType().getSizeInBits()),
2902           SDLoc(N), N1.getValueType());
2903
2904     // fold (and x, -1) -> x, vector edition
2905     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2906       return N1;
2907     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2908       return N0;
2909   }
2910
2911   // fold (and c1, c2) -> c1&c2
2912   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2913   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2914   if (N0C && N1C && !N1C->isOpaque())
2915     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2916   // canonicalize constant to RHS
2917   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2918      !isConstantIntBuildVectorOrConstantInt(N1))
2919     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2920   // fold (and x, -1) -> x
2921   if (isAllOnesConstant(N1))
2922     return N0;
2923   // if (and x, c) is known to be zero, return 0
2924   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2925   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2926                                    APInt::getAllOnesValue(BitWidth)))
2927     return DAG.getConstant(0, SDLoc(N), VT);
2928   // reassociate and
2929   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2930     return RAND;
2931   // fold (and (or x, C), D) -> D if (C & D) == D
2932   if (N1C && N0.getOpcode() == ISD::OR)
2933     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2934       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2935         return N1;
2936   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2937   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2938     SDValue N0Op0 = N0.getOperand(0);
2939     APInt Mask = ~N1C->getAPIntValue();
2940     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2941     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2942       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2943                                  N0.getValueType(), N0Op0);
2944
2945       // Replace uses of the AND with uses of the Zero extend node.
2946       CombineTo(N, Zext);
2947
2948       // We actually want to replace all uses of the any_extend with the
2949       // zero_extend, to avoid duplicating things.  This will later cause this
2950       // AND to be folded.
2951       CombineTo(N0.getNode(), Zext);
2952       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2953     }
2954   }
2955   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2956   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2957   // already be zero by virtue of the width of the base type of the load.
2958   //
2959   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2960   // more cases.
2961   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2962        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2963       N0.getOpcode() == ISD::LOAD) {
2964     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2965                                          N0 : N0.getOperand(0) );
2966
2967     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2968     // This can be a pure constant or a vector splat, in which case we treat the
2969     // vector as a scalar and use the splat value.
2970     APInt Constant = APInt::getNullValue(1);
2971     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2972       Constant = C->getAPIntValue();
2973     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2974       APInt SplatValue, SplatUndef;
2975       unsigned SplatBitSize;
2976       bool HasAnyUndefs;
2977       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2978                                              SplatBitSize, HasAnyUndefs);
2979       if (IsSplat) {
2980         // Undef bits can contribute to a possible optimisation if set, so
2981         // set them.
2982         SplatValue |= SplatUndef;
2983
2984         // The splat value may be something like "0x00FFFFFF", which means 0 for
2985         // the first vector value and FF for the rest, repeating. We need a mask
2986         // that will apply equally to all members of the vector, so AND all the
2987         // lanes of the constant together.
2988         EVT VT = Vector->getValueType(0);
2989         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2990
2991         // If the splat value has been compressed to a bitlength lower
2992         // than the size of the vector lane, we need to re-expand it to
2993         // the lane size.
2994         if (BitWidth > SplatBitSize)
2995           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2996                SplatBitSize < BitWidth;
2997                SplatBitSize = SplatBitSize * 2)
2998             SplatValue |= SplatValue.shl(SplatBitSize);
2999
3000         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3001         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3002         if (SplatBitSize % BitWidth == 0) {
3003           Constant = APInt::getAllOnesValue(BitWidth);
3004           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3005             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3006         }
3007       }
3008     }
3009
3010     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3011     // actually legal and isn't going to get expanded, else this is a false
3012     // optimisation.
3013     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3014                                                     Load->getValueType(0),
3015                                                     Load->getMemoryVT());
3016
3017     // Resize the constant to the same size as the original memory access before
3018     // extension. If it is still the AllOnesValue then this AND is completely
3019     // unneeded.
3020     Constant =
3021       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3022
3023     bool B;
3024     switch (Load->getExtensionType()) {
3025     default: B = false; break;
3026     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3027     case ISD::ZEXTLOAD:
3028     case ISD::NON_EXTLOAD: B = true; break;
3029     }
3030
3031     if (B && Constant.isAllOnesValue()) {
3032       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3033       // preserve semantics once we get rid of the AND.
3034       SDValue NewLoad(Load, 0);
3035       if (Load->getExtensionType() == ISD::EXTLOAD) {
3036         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3037                               Load->getValueType(0), SDLoc(Load),
3038                               Load->getChain(), Load->getBasePtr(),
3039                               Load->getOffset(), Load->getMemoryVT(),
3040                               Load->getMemOperand());
3041         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3042         if (Load->getNumValues() == 3) {
3043           // PRE/POST_INC loads have 3 values.
3044           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3045                            NewLoad.getValue(2) };
3046           CombineTo(Load, To, 3, true);
3047         } else {
3048           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3049         }
3050       }
3051
3052       // Fold the AND away, taking care not to fold to the old load node if we
3053       // replaced it.
3054       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3055
3056       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3057     }
3058   }
3059
3060   // fold (and (load x), 255) -> (zextload x, i8)
3061   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3062   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3063   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3064               (N0.getOpcode() == ISD::ANY_EXTEND &&
3065                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3066     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3067     LoadSDNode *LN0 = HasAnyExt
3068       ? cast<LoadSDNode>(N0.getOperand(0))
3069       : cast<LoadSDNode>(N0);
3070     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3071         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3072       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3073       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3074         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3075         EVT LoadedVT = LN0->getMemoryVT();
3076         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3077
3078         if (ExtVT == LoadedVT &&
3079             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3080                                                     ExtVT))) {
3081
3082           SDValue NewLoad =
3083             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3084                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3085                            LN0->getMemOperand());
3086           AddToWorklist(N);
3087           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3088           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3089         }
3090
3091         // Do not change the width of a volatile load.
3092         // Do not generate loads of non-round integer types since these can
3093         // be expensive (and would be wrong if the type is not byte sized).
3094         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3095             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3096                                                     ExtVT))) {
3097           EVT PtrType = LN0->getOperand(1).getValueType();
3098
3099           unsigned Alignment = LN0->getAlignment();
3100           SDValue NewPtr = LN0->getBasePtr();
3101
3102           // For big endian targets, we need to add an offset to the pointer
3103           // to load the correct bytes.  For little endian systems, we merely
3104           // need to read fewer bytes from the same pointer.
3105           if (TLI.isBigEndian()) {
3106             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3107             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3108             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3109             SDLoc DL(LN0);
3110             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3111                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3112             Alignment = MinAlign(Alignment, PtrOff);
3113           }
3114
3115           AddToWorklist(NewPtr.getNode());
3116
3117           SDValue Load =
3118             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3119                            LN0->getChain(), NewPtr,
3120                            LN0->getPointerInfo(),
3121                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3122                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3123           AddToWorklist(N);
3124           CombineTo(LN0, Load, Load.getValue(1));
3125           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3126         }
3127       }
3128     }
3129   }
3130
3131   if (SDValue Combined = visitANDLike(N0, N1, N))
3132     return Combined;
3133
3134   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3135   if (N0.getOpcode() == N1.getOpcode()) {
3136     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3137     if (Tmp.getNode()) return Tmp;
3138   }
3139
3140   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3141   // fold (and (sra)) -> (and (srl)) when possible.
3142   if (!VT.isVector() &&
3143       SimplifyDemandedBits(SDValue(N, 0)))
3144     return SDValue(N, 0);
3145
3146   // fold (zext_inreg (extload x)) -> (zextload x)
3147   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3148     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3149     EVT MemVT = LN0->getMemoryVT();
3150     // If we zero all the possible extended bits, then we can turn this into
3151     // a zextload if we are running before legalize or the operation is legal.
3152     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3153     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3154                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3155         ((!LegalOperations && !LN0->isVolatile()) ||
3156          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3157       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3158                                        LN0->getChain(), LN0->getBasePtr(),
3159                                        MemVT, LN0->getMemOperand());
3160       AddToWorklist(N);
3161       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3162       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3163     }
3164   }
3165   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3166   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3167       N0.hasOneUse()) {
3168     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3169     EVT MemVT = LN0->getMemoryVT();
3170     // If we zero all the possible extended bits, then we can turn this into
3171     // a zextload if we are running before legalize or the operation is legal.
3172     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3173     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3174                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3175         ((!LegalOperations && !LN0->isVolatile()) ||
3176          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3177       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3178                                        LN0->getChain(), LN0->getBasePtr(),
3179                                        MemVT, LN0->getMemOperand());
3180       AddToWorklist(N);
3181       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3182       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3183     }
3184   }
3185   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3186   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3187     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3188                                        N0.getOperand(1), false);
3189     if (BSwap.getNode())
3190       return BSwap;
3191   }
3192
3193   return SDValue();
3194 }
3195
3196 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3197 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3198                                         bool DemandHighBits) {
3199   if (!LegalOperations)
3200     return SDValue();
3201
3202   EVT VT = N->getValueType(0);
3203   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3204     return SDValue();
3205   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3206     return SDValue();
3207
3208   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3209   bool LookPassAnd0 = false;
3210   bool LookPassAnd1 = false;
3211   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3212       std::swap(N0, N1);
3213   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3214       std::swap(N0, N1);
3215   if (N0.getOpcode() == ISD::AND) {
3216     if (!N0.getNode()->hasOneUse())
3217       return SDValue();
3218     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3219     if (!N01C || N01C->getZExtValue() != 0xFF00)
3220       return SDValue();
3221     N0 = N0.getOperand(0);
3222     LookPassAnd0 = true;
3223   }
3224
3225   if (N1.getOpcode() == ISD::AND) {
3226     if (!N1.getNode()->hasOneUse())
3227       return SDValue();
3228     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3229     if (!N11C || N11C->getZExtValue() != 0xFF)
3230       return SDValue();
3231     N1 = N1.getOperand(0);
3232     LookPassAnd1 = true;
3233   }
3234
3235   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3236     std::swap(N0, N1);
3237   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3238     return SDValue();
3239   if (!N0.getNode()->hasOneUse() ||
3240       !N1.getNode()->hasOneUse())
3241     return SDValue();
3242
3243   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3244   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3245   if (!N01C || !N11C)
3246     return SDValue();
3247   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3248     return SDValue();
3249
3250   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3251   SDValue N00 = N0->getOperand(0);
3252   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3253     if (!N00.getNode()->hasOneUse())
3254       return SDValue();
3255     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3256     if (!N001C || N001C->getZExtValue() != 0xFF)
3257       return SDValue();
3258     N00 = N00.getOperand(0);
3259     LookPassAnd0 = true;
3260   }
3261
3262   SDValue N10 = N1->getOperand(0);
3263   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3264     if (!N10.getNode()->hasOneUse())
3265       return SDValue();
3266     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3267     if (!N101C || N101C->getZExtValue() != 0xFF00)
3268       return SDValue();
3269     N10 = N10.getOperand(0);
3270     LookPassAnd1 = true;
3271   }
3272
3273   if (N00 != N10)
3274     return SDValue();
3275
3276   // Make sure everything beyond the low halfword gets set to zero since the SRL
3277   // 16 will clear the top bits.
3278   unsigned OpSizeInBits = VT.getSizeInBits();
3279   if (DemandHighBits && OpSizeInBits > 16) {
3280     // If the left-shift isn't masked out then the only way this is a bswap is
3281     // if all bits beyond the low 8 are 0. In that case the entire pattern
3282     // reduces to a left shift anyway: leave it for other parts of the combiner.
3283     if (!LookPassAnd0)
3284       return SDValue();
3285
3286     // However, if the right shift isn't masked out then it might be because
3287     // it's not needed. See if we can spot that too.
3288     if (!LookPassAnd1 &&
3289         !DAG.MaskedValueIsZero(
3290             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3291       return SDValue();
3292   }
3293
3294   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3295   if (OpSizeInBits > 16) {
3296     SDLoc DL(N);
3297     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3298                       DAG.getConstant(OpSizeInBits - 16, DL,
3299                                       getShiftAmountTy(VT)));
3300   }
3301   return Res;
3302 }
3303
3304 /// Return true if the specified node is an element that makes up a 32-bit
3305 /// packed halfword byteswap.
3306 /// ((x & 0x000000ff) << 8) |
3307 /// ((x & 0x0000ff00) >> 8) |
3308 /// ((x & 0x00ff0000) << 8) |
3309 /// ((x & 0xff000000) >> 8)
3310 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3311   if (!N.getNode()->hasOneUse())
3312     return false;
3313
3314   unsigned Opc = N.getOpcode();
3315   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3316     return false;
3317
3318   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3319   if (!N1C)
3320     return false;
3321
3322   unsigned Num;
3323   switch (N1C->getZExtValue()) {
3324   default:
3325     return false;
3326   case 0xFF:       Num = 0; break;
3327   case 0xFF00:     Num = 1; break;
3328   case 0xFF0000:   Num = 2; break;
3329   case 0xFF000000: Num = 3; break;
3330   }
3331
3332   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3333   SDValue N0 = N.getOperand(0);
3334   if (Opc == ISD::AND) {
3335     if (Num == 0 || Num == 2) {
3336       // (x >> 8) & 0xff
3337       // (x >> 8) & 0xff0000
3338       if (N0.getOpcode() != ISD::SRL)
3339         return false;
3340       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3341       if (!C || C->getZExtValue() != 8)
3342         return false;
3343     } else {
3344       // (x << 8) & 0xff00
3345       // (x << 8) & 0xff000000
3346       if (N0.getOpcode() != ISD::SHL)
3347         return false;
3348       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3349       if (!C || C->getZExtValue() != 8)
3350         return false;
3351     }
3352   } else if (Opc == ISD::SHL) {
3353     // (x & 0xff) << 8
3354     // (x & 0xff0000) << 8
3355     if (Num != 0 && Num != 2)
3356       return false;
3357     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3358     if (!C || C->getZExtValue() != 8)
3359       return false;
3360   } else { // Opc == ISD::SRL
3361     // (x & 0xff00) >> 8
3362     // (x & 0xff000000) >> 8
3363     if (Num != 1 && Num != 3)
3364       return false;
3365     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3366     if (!C || C->getZExtValue() != 8)
3367       return false;
3368   }
3369
3370   if (Parts[Num])
3371     return false;
3372
3373   Parts[Num] = N0.getOperand(0).getNode();
3374   return true;
3375 }
3376
3377 /// Match a 32-bit packed halfword bswap. That is
3378 /// ((x & 0x000000ff) << 8) |
3379 /// ((x & 0x0000ff00) >> 8) |
3380 /// ((x & 0x00ff0000) << 8) |
3381 /// ((x & 0xff000000) >> 8)
3382 /// => (rotl (bswap x), 16)
3383 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3384   if (!LegalOperations)
3385     return SDValue();
3386
3387   EVT VT = N->getValueType(0);
3388   if (VT != MVT::i32)
3389     return SDValue();
3390   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3391     return SDValue();
3392
3393   // Look for either
3394   // (or (or (and), (and)), (or (and), (and)))
3395   // (or (or (or (and), (and)), (and)), (and))
3396   if (N0.getOpcode() != ISD::OR)
3397     return SDValue();
3398   SDValue N00 = N0.getOperand(0);
3399   SDValue N01 = N0.getOperand(1);
3400   SDNode *Parts[4] = {};
3401
3402   if (N1.getOpcode() == ISD::OR &&
3403       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3404     // (or (or (and), (and)), (or (and), (and)))
3405     SDValue N000 = N00.getOperand(0);
3406     if (!isBSwapHWordElement(N000, Parts))
3407       return SDValue();
3408
3409     SDValue N001 = N00.getOperand(1);
3410     if (!isBSwapHWordElement(N001, Parts))
3411       return SDValue();
3412     SDValue N010 = N01.getOperand(0);
3413     if (!isBSwapHWordElement(N010, Parts))
3414       return SDValue();
3415     SDValue N011 = N01.getOperand(1);
3416     if (!isBSwapHWordElement(N011, Parts))
3417       return SDValue();
3418   } else {
3419     // (or (or (or (and), (and)), (and)), (and))
3420     if (!isBSwapHWordElement(N1, Parts))
3421       return SDValue();
3422     if (!isBSwapHWordElement(N01, Parts))
3423       return SDValue();
3424     if (N00.getOpcode() != ISD::OR)
3425       return SDValue();
3426     SDValue N000 = N00.getOperand(0);
3427     if (!isBSwapHWordElement(N000, Parts))
3428       return SDValue();
3429     SDValue N001 = N00.getOperand(1);
3430     if (!isBSwapHWordElement(N001, Parts))
3431       return SDValue();
3432   }
3433
3434   // Make sure the parts are all coming from the same node.
3435   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3436     return SDValue();
3437
3438   SDLoc DL(N);
3439   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3440                               SDValue(Parts[0], 0));
3441
3442   // Result of the bswap should be rotated by 16. If it's not legal, then
3443   // do  (x << 16) | (x >> 16).
3444   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3445   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3446     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3447   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3448     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3449   return DAG.getNode(ISD::OR, DL, VT,
3450                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3451                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3452 }
3453
3454 /// This contains all DAGCombine rules which reduce two values combined by
3455 /// an Or operation to a single value \see visitANDLike().
3456 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3457   EVT VT = N1.getValueType();
3458   // fold (or x, undef) -> -1
3459   if (!LegalOperations &&
3460       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3461     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3462     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3463                            SDLoc(LocReference), VT);
3464   }
3465   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3466   SDValue LL, LR, RL, RR, CC0, CC1;
3467   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3468     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3469     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3470
3471     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3472       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3473       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3474       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3475         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3476                                      LR.getValueType(), LL, RL);
3477         AddToWorklist(ORNode.getNode());
3478         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3479       }
3480       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3481       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3482       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3483         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3484                                       LR.getValueType(), LL, RL);
3485         AddToWorklist(ANDNode.getNode());
3486         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3487       }
3488     }
3489     // canonicalize equivalent to ll == rl
3490     if (LL == RR && LR == RL) {
3491       Op1 = ISD::getSetCCSwappedOperands(Op1);
3492       std::swap(RL, RR);
3493     }
3494     if (LL == RL && LR == RR) {
3495       bool isInteger = LL.getValueType().isInteger();
3496       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3497       if (Result != ISD::SETCC_INVALID &&
3498           (!LegalOperations ||
3499            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3500             TLI.isOperationLegal(ISD::SETCC,
3501               getSetCCResultType(N0.getValueType())))))
3502         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3503                             LL, LR, Result);
3504     }
3505   }
3506
3507   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3508   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3509       // Don't increase # computations.
3510       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3511     // We can only do this xform if we know that bits from X that are set in C2
3512     // but not in C1 are already zero.  Likewise for Y.
3513     if (const ConstantSDNode *N0O1C =
3514         getAsNonOpaqueConstant(N0.getOperand(1))) {
3515       if (const ConstantSDNode *N1O1C =
3516           getAsNonOpaqueConstant(N1.getOperand(1))) {
3517         // We can only do this xform if we know that bits from X that are set in
3518         // C2 but not in C1 are already zero.  Likewise for Y.
3519         const APInt &LHSMask = N0O1C->getAPIntValue();
3520         const APInt &RHSMask = N1O1C->getAPIntValue();
3521
3522         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3523             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3524           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3525                                   N0.getOperand(0), N1.getOperand(0));
3526           SDLoc DL(LocReference);
3527           return DAG.getNode(ISD::AND, DL, VT, X,
3528                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3529         }
3530       }
3531     }
3532   }
3533
3534   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3535   if (N0.getOpcode() == ISD::AND &&
3536       N1.getOpcode() == ISD::AND &&
3537       N0.getOperand(0) == N1.getOperand(0) &&
3538       // Don't increase # computations.
3539       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3540     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3541                             N0.getOperand(1), N1.getOperand(1));
3542     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3543   }
3544
3545   return SDValue();
3546 }
3547
3548 SDValue DAGCombiner::visitOR(SDNode *N) {
3549   SDValue N0 = N->getOperand(0);
3550   SDValue N1 = N->getOperand(1);
3551   EVT VT = N1.getValueType();
3552
3553   // fold vector ops
3554   if (VT.isVector()) {
3555     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3556       return FoldedVOp;
3557
3558     // fold (or x, 0) -> x, vector edition
3559     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3560       return N1;
3561     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3562       return N0;
3563
3564     // fold (or x, -1) -> -1, vector edition
3565     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3566       // do not return N0, because undef node may exist in N0
3567       return DAG.getConstant(
3568           APInt::getAllOnesValue(
3569               N0.getValueType().getScalarType().getSizeInBits()),
3570           SDLoc(N), N0.getValueType());
3571     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3572       // do not return N1, because undef node may exist in N1
3573       return DAG.getConstant(
3574           APInt::getAllOnesValue(
3575               N1.getValueType().getScalarType().getSizeInBits()),
3576           SDLoc(N), N1.getValueType());
3577
3578     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3579     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3580     // Do this only if the resulting shuffle is legal.
3581     if (isa<ShuffleVectorSDNode>(N0) &&
3582         isa<ShuffleVectorSDNode>(N1) &&
3583         // Avoid folding a node with illegal type.
3584         TLI.isTypeLegal(VT) &&
3585         N0->getOperand(1) == N1->getOperand(1) &&
3586         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3587       bool CanFold = true;
3588       unsigned NumElts = VT.getVectorNumElements();
3589       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3590       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3591       // We construct two shuffle masks:
3592       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3593       // and N1 as the second operand.
3594       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3595       // and N0 as the second operand.
3596       // We do this because OR is commutable and therefore there might be
3597       // two ways to fold this node into a shuffle.
3598       SmallVector<int,4> Mask1;
3599       SmallVector<int,4> Mask2;
3600
3601       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3602         int M0 = SV0->getMaskElt(i);
3603         int M1 = SV1->getMaskElt(i);
3604
3605         // Both shuffle indexes are undef. Propagate Undef.
3606         if (M0 < 0 && M1 < 0) {
3607           Mask1.push_back(M0);
3608           Mask2.push_back(M0);
3609           continue;
3610         }
3611
3612         if (M0 < 0 || M1 < 0 ||
3613             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3614             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3615           CanFold = false;
3616           break;
3617         }
3618
3619         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3620         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3621       }
3622
3623       if (CanFold) {
3624         // Fold this sequence only if the resulting shuffle is 'legal'.
3625         if (TLI.isShuffleMaskLegal(Mask1, VT))
3626           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3627                                       N1->getOperand(0), &Mask1[0]);
3628         if (TLI.isShuffleMaskLegal(Mask2, VT))
3629           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3630                                       N0->getOperand(0), &Mask2[0]);
3631       }
3632     }
3633   }
3634
3635   // fold (or c1, c2) -> c1|c2
3636   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3637   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3638   if (N0C && N1C && !N1C->isOpaque())
3639     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3640   // canonicalize constant to RHS
3641   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3642      !isConstantIntBuildVectorOrConstantInt(N1))
3643     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3644   // fold (or x, 0) -> x
3645   if (isNullConstant(N1))
3646     return N0;
3647   // fold (or x, -1) -> -1
3648   if (isAllOnesConstant(N1))
3649     return N1;
3650   // fold (or x, c) -> c iff (x & ~c) == 0
3651   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3652     return N1;
3653
3654   if (SDValue Combined = visitORLike(N0, N1, N))
3655     return Combined;
3656
3657   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3658   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3659   if (BSwap.getNode())
3660     return BSwap;
3661   BSwap = MatchBSwapHWordLow(N, N0, N1);
3662   if (BSwap.getNode())
3663     return BSwap;
3664
3665   // reassociate or
3666   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3667     return ROR;
3668   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3669   // iff (c1 & c2) == 0.
3670   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3671              isa<ConstantSDNode>(N0.getOperand(1))) {
3672     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3673     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3674       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3675                                                    N1C, C1))
3676         return DAG.getNode(
3677             ISD::AND, SDLoc(N), VT,
3678             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3679       return SDValue();
3680     }
3681   }
3682   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3683   if (N0.getOpcode() == N1.getOpcode()) {
3684     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3685     if (Tmp.getNode()) return Tmp;
3686   }
3687
3688   // See if this is some rotate idiom.
3689   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3690     return SDValue(Rot, 0);
3691
3692   // Simplify the operands using demanded-bits information.
3693   if (!VT.isVector() &&
3694       SimplifyDemandedBits(SDValue(N, 0)))
3695     return SDValue(N, 0);
3696
3697   return SDValue();
3698 }
3699
3700 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3701 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3702   if (Op.getOpcode() == ISD::AND) {
3703     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3704       Mask = Op.getOperand(1);
3705       Op = Op.getOperand(0);
3706     } else {
3707       return false;
3708     }
3709   }
3710
3711   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3712     Shift = Op;
3713     return true;
3714   }
3715
3716   return false;
3717 }
3718
3719 // Return true if we can prove that, whenever Neg and Pos are both in the
3720 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3721 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3722 //
3723 //     (or (shift1 X, Neg), (shift2 X, Pos))
3724 //
3725 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3726 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3727 // to consider shift amounts with defined behavior.
3728 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3729   // If OpSize is a power of 2 then:
3730   //
3731   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3732   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3733   //
3734   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3735   // for the stronger condition:
3736   //
3737   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3738   //
3739   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3740   // we can just replace Neg with Neg' for the rest of the function.
3741   //
3742   // In other cases we check for the even stronger condition:
3743   //
3744   //     Neg == OpSize - Pos                                    [B]
3745   //
3746   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3747   // behavior if Pos == 0 (and consequently Neg == OpSize).
3748   //
3749   // We could actually use [A] whenever OpSize is a power of 2, but the
3750   // only extra cases that it would match are those uninteresting ones
3751   // where Neg and Pos are never in range at the same time.  E.g. for
3752   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3753   // as well as (sub 32, Pos), but:
3754   //
3755   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3756   //
3757   // always invokes undefined behavior for 32-bit X.
3758   //
3759   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3760   unsigned MaskLoBits = 0;
3761   if (Neg.getOpcode() == ISD::AND &&
3762       isPowerOf2_64(OpSize) &&
3763       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3764       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3765     Neg = Neg.getOperand(0);
3766     MaskLoBits = Log2_64(OpSize);
3767   }
3768
3769   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3770   if (Neg.getOpcode() != ISD::SUB)
3771     return 0;
3772   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3773   if (!NegC)
3774     return 0;
3775   SDValue NegOp1 = Neg.getOperand(1);
3776
3777   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3778   // Pos'.  The truncation is redundant for the purpose of the equality.
3779   if (MaskLoBits &&
3780       Pos.getOpcode() == ISD::AND &&
3781       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3782       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3783     Pos = Pos.getOperand(0);
3784
3785   // The condition we need is now:
3786   //
3787   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3788   //
3789   // If NegOp1 == Pos then we need:
3790   //
3791   //              OpSize & Mask == NegC & Mask
3792   //
3793   // (because "x & Mask" is a truncation and distributes through subtraction).
3794   APInt Width;
3795   if (Pos == NegOp1)
3796     Width = NegC->getAPIntValue();
3797   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3798   // Then the condition we want to prove becomes:
3799   //
3800   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3801   //
3802   // which, again because "x & Mask" is a truncation, becomes:
3803   //
3804   //                NegC & Mask == (OpSize - PosC) & Mask
3805   //              OpSize & Mask == (NegC + PosC) & Mask
3806   else if (Pos.getOpcode() == ISD::ADD &&
3807            Pos.getOperand(0) == NegOp1 &&
3808            Pos.getOperand(1).getOpcode() == ISD::Constant)
3809     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3810              NegC->getAPIntValue());
3811   else
3812     return false;
3813
3814   // Now we just need to check that OpSize & Mask == Width & Mask.
3815   if (MaskLoBits)
3816     // Opsize & Mask is 0 since Mask is Opsize - 1.
3817     return Width.getLoBits(MaskLoBits) == 0;
3818   return Width == OpSize;
3819 }
3820
3821 // A subroutine of MatchRotate used once we have found an OR of two opposite
3822 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3823 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3824 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3825 // Neg with outer conversions stripped away.
3826 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3827                                        SDValue Neg, SDValue InnerPos,
3828                                        SDValue InnerNeg, unsigned PosOpcode,
3829                                        unsigned NegOpcode, SDLoc DL) {
3830   // fold (or (shl x, (*ext y)),
3831   //          (srl x, (*ext (sub 32, y)))) ->
3832   //   (rotl x, y) or (rotr x, (sub 32, y))
3833   //
3834   // fold (or (shl x, (*ext (sub 32, y))),
3835   //          (srl x, (*ext y))) ->
3836   //   (rotr x, y) or (rotl x, (sub 32, y))
3837   EVT VT = Shifted.getValueType();
3838   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3839     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3840     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3841                        HasPos ? Pos : Neg).getNode();
3842   }
3843
3844   return nullptr;
3845 }
3846
3847 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3848 // idioms for rotate, and if the target supports rotation instructions, generate
3849 // a rot[lr].
3850 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3851   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3852   EVT VT = LHS.getValueType();
3853   if (!TLI.isTypeLegal(VT)) return nullptr;
3854
3855   // The target must have at least one rotate flavor.
3856   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3857   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3858   if (!HasROTL && !HasROTR) return nullptr;
3859
3860   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3861   SDValue LHSShift;   // The shift.
3862   SDValue LHSMask;    // AND value if any.
3863   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3864     return nullptr; // Not part of a rotate.
3865
3866   SDValue RHSShift;   // The shift.
3867   SDValue RHSMask;    // AND value if any.
3868   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3869     return nullptr; // Not part of a rotate.
3870
3871   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3872     return nullptr;   // Not shifting the same value.
3873
3874   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3875     return nullptr;   // Shifts must disagree.
3876
3877   // Canonicalize shl to left side in a shl/srl pair.
3878   if (RHSShift.getOpcode() == ISD::SHL) {
3879     std::swap(LHS, RHS);
3880     std::swap(LHSShift, RHSShift);
3881     std::swap(LHSMask , RHSMask );
3882   }
3883
3884   unsigned OpSizeInBits = VT.getSizeInBits();
3885   SDValue LHSShiftArg = LHSShift.getOperand(0);
3886   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3887   SDValue RHSShiftArg = RHSShift.getOperand(0);
3888   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3889
3890   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3891   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3892   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3893       RHSShiftAmt.getOpcode() == ISD::Constant) {
3894     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3895     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3896     if ((LShVal + RShVal) != OpSizeInBits)
3897       return nullptr;
3898
3899     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3900                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3901
3902     // If there is an AND of either shifted operand, apply it to the result.
3903     if (LHSMask.getNode() || RHSMask.getNode()) {
3904       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3905
3906       if (LHSMask.getNode()) {
3907         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3908         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3909       }
3910       if (RHSMask.getNode()) {
3911         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3912         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3913       }
3914
3915       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3916     }
3917
3918     return Rot.getNode();
3919   }
3920
3921   // If there is a mask here, and we have a variable shift, we can't be sure
3922   // that we're masking out the right stuff.
3923   if (LHSMask.getNode() || RHSMask.getNode())
3924     return nullptr;
3925
3926   // If the shift amount is sign/zext/any-extended just peel it off.
3927   SDValue LExtOp0 = LHSShiftAmt;
3928   SDValue RExtOp0 = RHSShiftAmt;
3929   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3930        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3931        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3932        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3933       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3934        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3935        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3936        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3937     LExtOp0 = LHSShiftAmt.getOperand(0);
3938     RExtOp0 = RHSShiftAmt.getOperand(0);
3939   }
3940
3941   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3942                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3943   if (TryL)
3944     return TryL;
3945
3946   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3947                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3948   if (TryR)
3949     return TryR;
3950
3951   return nullptr;
3952 }
3953
3954 SDValue DAGCombiner::visitXOR(SDNode *N) {
3955   SDValue N0 = N->getOperand(0);
3956   SDValue N1 = N->getOperand(1);
3957   EVT VT = N0.getValueType();
3958
3959   // fold vector ops
3960   if (VT.isVector()) {
3961     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3962       return FoldedVOp;
3963
3964     // fold (xor x, 0) -> x, vector edition
3965     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3966       return N1;
3967     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3968       return N0;
3969   }
3970
3971   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3972   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3973     return DAG.getConstant(0, SDLoc(N), VT);
3974   // fold (xor x, undef) -> undef
3975   if (N0.getOpcode() == ISD::UNDEF)
3976     return N0;
3977   if (N1.getOpcode() == ISD::UNDEF)
3978     return N1;
3979   // fold (xor c1, c2) -> c1^c2
3980   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3981   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3982   if (N0C && N1C)
3983     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3984   // canonicalize constant to RHS
3985   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3986      !isConstantIntBuildVectorOrConstantInt(N1))
3987     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3988   // fold (xor x, 0) -> x
3989   if (isNullConstant(N1))
3990     return N0;
3991   // reassociate xor
3992   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3993     return RXOR;
3994
3995   // fold !(x cc y) -> (x !cc y)
3996   SDValue LHS, RHS, CC;
3997   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3998     bool isInt = LHS.getValueType().isInteger();
3999     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4000                                                isInt);
4001
4002     if (!LegalOperations ||
4003         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4004       switch (N0.getOpcode()) {
4005       default:
4006         llvm_unreachable("Unhandled SetCC Equivalent!");
4007       case ISD::SETCC:
4008         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4009       case ISD::SELECT_CC:
4010         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4011                                N0.getOperand(3), NotCC);
4012       }
4013     }
4014   }
4015
4016   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4017   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4018       N0.getNode()->hasOneUse() &&
4019       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4020     SDValue V = N0.getOperand(0);
4021     SDLoc DL(N0);
4022     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4023                     DAG.getConstant(1, DL, V.getValueType()));
4024     AddToWorklist(V.getNode());
4025     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4026   }
4027
4028   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4029   if (isOneConstant(N1) && VT == MVT::i1 &&
4030       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4031     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4032     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4033       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4034       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4035       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4036       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4037       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4038     }
4039   }
4040   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4041   if (isAllOnesConstant(N1) &&
4042       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4043     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4044     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4045       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4046       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4047       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4048       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4049       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4050     }
4051   }
4052   // fold (xor (and x, y), y) -> (and (not x), y)
4053   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4054       N0->getOperand(1) == N1) {
4055     SDValue X = N0->getOperand(0);
4056     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4057     AddToWorklist(NotX.getNode());
4058     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4059   }
4060   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4061   if (N1C && N0.getOpcode() == ISD::XOR) {
4062     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4063       SDLoc DL(N);
4064       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4065                          DAG.getConstant(N1C->getAPIntValue() ^
4066                                          N00C->getAPIntValue(), DL, VT));
4067     }
4068     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4069       SDLoc DL(N);
4070       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4071                          DAG.getConstant(N1C->getAPIntValue() ^
4072                                          N01C->getAPIntValue(), DL, VT));
4073     }
4074   }
4075   // fold (xor x, x) -> 0
4076   if (N0 == N1)
4077     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4078
4079   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4080   // Here is a concrete example of this equivalence:
4081   // i16   x ==  14
4082   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4083   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4084   //
4085   // =>
4086   //
4087   // i16     ~1      == 0b1111111111111110
4088   // i16 rol(~1, 14) == 0b1011111111111111
4089   //
4090   // Some additional tips to help conceptualize this transform:
4091   // - Try to see the operation as placing a single zero in a value of all ones.
4092   // - There exists no value for x which would allow the result to contain zero.
4093   // - Values of x larger than the bitwidth are undefined and do not require a
4094   //   consistent result.
4095   // - Pushing the zero left requires shifting one bits in from the right.
4096   // A rotate left of ~1 is a nice way of achieving the desired result.
4097   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4098       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4099     SDLoc DL(N);
4100     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4101                        N0.getOperand(1));
4102   }
4103
4104   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4105   if (N0.getOpcode() == N1.getOpcode()) {
4106     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4107     if (Tmp.getNode()) return Tmp;
4108   }
4109
4110   // Simplify the expression using non-local knowledge.
4111   if (!VT.isVector() &&
4112       SimplifyDemandedBits(SDValue(N, 0)))
4113     return SDValue(N, 0);
4114
4115   return SDValue();
4116 }
4117
4118 /// Handle transforms common to the three shifts, when the shift amount is a
4119 /// constant.
4120 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4121   SDNode *LHS = N->getOperand(0).getNode();
4122   if (!LHS->hasOneUse()) return SDValue();
4123
4124   // We want to pull some binops through shifts, so that we have (and (shift))
4125   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4126   // thing happens with address calculations, so it's important to canonicalize
4127   // it.
4128   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4129
4130   switch (LHS->getOpcode()) {
4131   default: return SDValue();
4132   case ISD::OR:
4133   case ISD::XOR:
4134     HighBitSet = false; // We can only transform sra if the high bit is clear.
4135     break;
4136   case ISD::AND:
4137     HighBitSet = true;  // We can only transform sra if the high bit is set.
4138     break;
4139   case ISD::ADD:
4140     if (N->getOpcode() != ISD::SHL)
4141       return SDValue(); // only shl(add) not sr[al](add).
4142     HighBitSet = false; // We can only transform sra if the high bit is clear.
4143     break;
4144   }
4145
4146   // We require the RHS of the binop to be a constant and not opaque as well.
4147   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4148   if (!BinOpCst) return SDValue();
4149
4150   // FIXME: disable this unless the input to the binop is a shift by a constant.
4151   // If it is not a shift, it pessimizes some common cases like:
4152   //
4153   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4154   //    int bar(int *X, int i) { return X[i & 255]; }
4155   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4156   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4157        BinOpLHSVal->getOpcode() != ISD::SRA &&
4158        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4159       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4160     return SDValue();
4161
4162   EVT VT = N->getValueType(0);
4163
4164   // If this is a signed shift right, and the high bit is modified by the
4165   // logical operation, do not perform the transformation. The highBitSet
4166   // boolean indicates the value of the high bit of the constant which would
4167   // cause it to be modified for this operation.
4168   if (N->getOpcode() == ISD::SRA) {
4169     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4170     if (BinOpRHSSignSet != HighBitSet)
4171       return SDValue();
4172   }
4173
4174   if (!TLI.isDesirableToCommuteWithShift(LHS))
4175     return SDValue();
4176
4177   // Fold the constants, shifting the binop RHS by the shift amount.
4178   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4179                                N->getValueType(0),
4180                                LHS->getOperand(1), N->getOperand(1));
4181   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4182
4183   // Create the new shift.
4184   SDValue NewShift = DAG.getNode(N->getOpcode(),
4185                                  SDLoc(LHS->getOperand(0)),
4186                                  VT, LHS->getOperand(0), N->getOperand(1));
4187
4188   // Create the new binop.
4189   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4190 }
4191
4192 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4193   assert(N->getOpcode() == ISD::TRUNCATE);
4194   assert(N->getOperand(0).getOpcode() == ISD::AND);
4195
4196   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4197   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4198     SDValue N01 = N->getOperand(0).getOperand(1);
4199
4200     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4201       if (!N01C->isOpaque()) {
4202         EVT TruncVT = N->getValueType(0);
4203         SDValue N00 = N->getOperand(0).getOperand(0);
4204         APInt TruncC = N01C->getAPIntValue();
4205         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4206         SDLoc DL(N);
4207
4208         return DAG.getNode(ISD::AND, DL, TruncVT,
4209                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4210                            DAG.getConstant(TruncC, DL, TruncVT));
4211       }
4212     }
4213   }
4214
4215   return SDValue();
4216 }
4217
4218 SDValue DAGCombiner::visitRotate(SDNode *N) {
4219   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4220   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4221       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4222     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4223     if (NewOp1.getNode())
4224       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4225                          N->getOperand(0), NewOp1);
4226   }
4227   return SDValue();
4228 }
4229
4230 SDValue DAGCombiner::visitSHL(SDNode *N) {
4231   SDValue N0 = N->getOperand(0);
4232   SDValue N1 = N->getOperand(1);
4233   EVT VT = N0.getValueType();
4234   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4235
4236   // fold vector ops
4237   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4238   if (VT.isVector()) {
4239     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4240       return FoldedVOp;
4241
4242     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4243     // If setcc produces all-one true value then:
4244     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4245     if (N1CV && N1CV->isConstant()) {
4246       if (N0.getOpcode() == ISD::AND) {
4247         SDValue N00 = N0->getOperand(0);
4248         SDValue N01 = N0->getOperand(1);
4249         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4250
4251         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4252             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4253                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4254           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4255                                                      N01CV, N1CV))
4256             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4257         }
4258       } else {
4259         N1C = isConstOrConstSplat(N1);
4260       }
4261     }
4262   }
4263
4264   // fold (shl c1, c2) -> c1<<c2
4265   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4266   if (N0C && N1C && !N1C->isOpaque())
4267     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4268   // fold (shl 0, x) -> 0
4269   if (isNullConstant(N0))
4270     return N0;
4271   // fold (shl x, c >= size(x)) -> undef
4272   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4273     return DAG.getUNDEF(VT);
4274   // fold (shl x, 0) -> x
4275   if (N1C && N1C->isNullValue())
4276     return N0;
4277   // fold (shl undef, x) -> 0
4278   if (N0.getOpcode() == ISD::UNDEF)
4279     return DAG.getConstant(0, SDLoc(N), VT);
4280   // if (shl x, c) is known to be zero, return 0
4281   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4282                             APInt::getAllOnesValue(OpSizeInBits)))
4283     return DAG.getConstant(0, SDLoc(N), VT);
4284   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4285   if (N1.getOpcode() == ISD::TRUNCATE &&
4286       N1.getOperand(0).getOpcode() == ISD::AND) {
4287     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4288     if (NewOp1.getNode())
4289       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4290   }
4291
4292   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4293     return SDValue(N, 0);
4294
4295   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4296   if (N1C && N0.getOpcode() == ISD::SHL) {
4297     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4298       uint64_t c1 = N0C1->getZExtValue();
4299       uint64_t c2 = N1C->getZExtValue();
4300       SDLoc DL(N);
4301       if (c1 + c2 >= OpSizeInBits)
4302         return DAG.getConstant(0, DL, VT);
4303       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4304                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4305     }
4306   }
4307
4308   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4309   // For this to be valid, the second form must not preserve any of the bits
4310   // that are shifted out by the inner shift in the first form.  This means
4311   // the outer shift size must be >= the number of bits added by the ext.
4312   // As a corollary, we don't care what kind of ext it is.
4313   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4314               N0.getOpcode() == ISD::ANY_EXTEND ||
4315               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4316       N0.getOperand(0).getOpcode() == ISD::SHL) {
4317     SDValue N0Op0 = N0.getOperand(0);
4318     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4319       uint64_t c1 = N0Op0C1->getZExtValue();
4320       uint64_t c2 = N1C->getZExtValue();
4321       EVT InnerShiftVT = N0Op0.getValueType();
4322       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4323       if (c2 >= OpSizeInBits - InnerShiftSize) {
4324         SDLoc DL(N0);
4325         if (c1 + c2 >= OpSizeInBits)
4326           return DAG.getConstant(0, DL, VT);
4327         return DAG.getNode(ISD::SHL, DL, VT,
4328                            DAG.getNode(N0.getOpcode(), DL, VT,
4329                                        N0Op0->getOperand(0)),
4330                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4331       }
4332     }
4333   }
4334
4335   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4336   // Only fold this if the inner zext has no other uses to avoid increasing
4337   // the total number of instructions.
4338   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4339       N0.getOperand(0).getOpcode() == ISD::SRL) {
4340     SDValue N0Op0 = N0.getOperand(0);
4341     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4342       uint64_t c1 = N0Op0C1->getZExtValue();
4343       if (c1 < VT.getScalarSizeInBits()) {
4344         uint64_t c2 = N1C->getZExtValue();
4345         if (c1 == c2) {
4346           SDValue NewOp0 = N0.getOperand(0);
4347           EVT CountVT = NewOp0.getOperand(1).getValueType();
4348           SDLoc DL(N);
4349           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4350                                        NewOp0,
4351                                        DAG.getConstant(c2, DL, CountVT));
4352           AddToWorklist(NewSHL.getNode());
4353           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4354         }
4355       }
4356     }
4357   }
4358
4359   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4360   //                               (and (srl x, (sub c1, c2), MASK)
4361   // Only fold this if the inner shift has no other uses -- if it does, folding
4362   // this will increase the total number of instructions.
4363   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4364     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4365       uint64_t c1 = N0C1->getZExtValue();
4366       if (c1 < OpSizeInBits) {
4367         uint64_t c2 = N1C->getZExtValue();
4368         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4369         SDValue Shift;
4370         if (c2 > c1) {
4371           Mask = Mask.shl(c2 - c1);
4372           SDLoc DL(N);
4373           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4374                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4375         } else {
4376           Mask = Mask.lshr(c1 - c2);
4377           SDLoc DL(N);
4378           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4379                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4380         }
4381         SDLoc DL(N0);
4382         return DAG.getNode(ISD::AND, DL, VT, Shift,
4383                            DAG.getConstant(Mask, DL, VT));
4384       }
4385     }
4386   }
4387   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4388   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4389     unsigned BitSize = VT.getScalarSizeInBits();
4390     SDLoc DL(N);
4391     SDValue HiBitsMask =
4392       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4393                                             BitSize - N1C->getZExtValue()),
4394                       DL, VT);
4395     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4396                        HiBitsMask);
4397   }
4398
4399   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4400   // Variant of version done on multiply, except mul by a power of 2 is turned
4401   // into a shift.
4402   APInt Val;
4403   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4404       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4405        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4406     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4407     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4408     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4409   }
4410
4411   if (N1C && !N1C->isOpaque()) {
4412     SDValue NewSHL = visitShiftByConstant(N, N1C);
4413     if (NewSHL.getNode())
4414       return NewSHL;
4415   }
4416
4417   return SDValue();
4418 }
4419
4420 SDValue DAGCombiner::visitSRA(SDNode *N) {
4421   SDValue N0 = N->getOperand(0);
4422   SDValue N1 = N->getOperand(1);
4423   EVT VT = N0.getValueType();
4424   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4425
4426   // fold vector ops
4427   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4428   if (VT.isVector()) {
4429     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4430       return FoldedVOp;
4431
4432     N1C = isConstOrConstSplat(N1);
4433   }
4434
4435   // fold (sra c1, c2) -> (sra c1, c2)
4436   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4437   if (N0C && N1C && !N1C->isOpaque())
4438     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4439   // fold (sra 0, x) -> 0
4440   if (isNullConstant(N0))
4441     return N0;
4442   // fold (sra -1, x) -> -1
4443   if (isAllOnesConstant(N0))
4444     return N0;
4445   // fold (sra x, (setge c, size(x))) -> undef
4446   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4447     return DAG.getUNDEF(VT);
4448   // fold (sra x, 0) -> x
4449   if (N1C && N1C->isNullValue())
4450     return N0;
4451   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4452   // sext_inreg.
4453   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4454     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4455     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4456     if (VT.isVector())
4457       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4458                                ExtVT, VT.getVectorNumElements());
4459     if ((!LegalOperations ||
4460          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4461       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4462                          N0.getOperand(0), DAG.getValueType(ExtVT));
4463   }
4464
4465   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4466   if (N1C && N0.getOpcode() == ISD::SRA) {
4467     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4468       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4469       if (Sum >= OpSizeInBits)
4470         Sum = OpSizeInBits - 1;
4471       SDLoc DL(N);
4472       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4473                          DAG.getConstant(Sum, DL, N1.getValueType()));
4474     }
4475   }
4476
4477   // fold (sra (shl X, m), (sub result_size, n))
4478   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4479   // result_size - n != m.
4480   // If truncate is free for the target sext(shl) is likely to result in better
4481   // code.
4482   if (N0.getOpcode() == ISD::SHL && N1C) {
4483     // Get the two constanst of the shifts, CN0 = m, CN = n.
4484     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4485     if (N01C) {
4486       LLVMContext &Ctx = *DAG.getContext();
4487       // Determine what the truncate's result bitsize and type would be.
4488       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4489
4490       if (VT.isVector())
4491         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4492
4493       // Determine the residual right-shift amount.
4494       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4495
4496       // If the shift is not a no-op (in which case this should be just a sign
4497       // extend already), the truncated to type is legal, sign_extend is legal
4498       // on that type, and the truncate to that type is both legal and free,
4499       // perform the transform.
4500       if ((ShiftAmt > 0) &&
4501           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4502           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4503           TLI.isTruncateFree(VT, TruncVT)) {
4504
4505         SDLoc DL(N);
4506         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4507             getShiftAmountTy(N0.getOperand(0).getValueType()));
4508         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4509                                     N0.getOperand(0), Amt);
4510         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4511                                     Shift);
4512         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4513                            N->getValueType(0), Trunc);
4514       }
4515     }
4516   }
4517
4518   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4519   if (N1.getOpcode() == ISD::TRUNCATE &&
4520       N1.getOperand(0).getOpcode() == ISD::AND) {
4521     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4522     if (NewOp1.getNode())
4523       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4524   }
4525
4526   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4527   //      if c1 is equal to the number of bits the trunc removes
4528   if (N0.getOpcode() == ISD::TRUNCATE &&
4529       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4530        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4531       N0.getOperand(0).hasOneUse() &&
4532       N0.getOperand(0).getOperand(1).hasOneUse() &&
4533       N1C) {
4534     SDValue N0Op0 = N0.getOperand(0);
4535     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4536       unsigned LargeShiftVal = LargeShift->getZExtValue();
4537       EVT LargeVT = N0Op0.getValueType();
4538
4539       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4540         SDLoc DL(N);
4541         SDValue Amt =
4542           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4543                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4544         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4545                                   N0Op0.getOperand(0), Amt);
4546         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4547       }
4548     }
4549   }
4550
4551   // Simplify, based on bits shifted out of the LHS.
4552   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4553     return SDValue(N, 0);
4554
4555
4556   // If the sign bit is known to be zero, switch this to a SRL.
4557   if (DAG.SignBitIsZero(N0))
4558     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4559
4560   if (N1C && !N1C->isOpaque()) {
4561     SDValue NewSRA = visitShiftByConstant(N, N1C);
4562     if (NewSRA.getNode())
4563       return NewSRA;
4564   }
4565
4566   return SDValue();
4567 }
4568
4569 SDValue DAGCombiner::visitSRL(SDNode *N) {
4570   SDValue N0 = N->getOperand(0);
4571   SDValue N1 = N->getOperand(1);
4572   EVT VT = N0.getValueType();
4573   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4574
4575   // fold vector ops
4576   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4577   if (VT.isVector()) {
4578     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4579       return FoldedVOp;
4580
4581     N1C = isConstOrConstSplat(N1);
4582   }
4583
4584   // fold (srl c1, c2) -> c1 >>u c2
4585   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4586   if (N0C && N1C && !N1C->isOpaque())
4587     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4588   // fold (srl 0, x) -> 0
4589   if (isNullConstant(N0))
4590     return N0;
4591   // fold (srl x, c >= size(x)) -> undef
4592   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4593     return DAG.getUNDEF(VT);
4594   // fold (srl x, 0) -> x
4595   if (N1C && N1C->isNullValue())
4596     return N0;
4597   // if (srl x, c) is known to be zero, return 0
4598   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4599                                    APInt::getAllOnesValue(OpSizeInBits)))
4600     return DAG.getConstant(0, SDLoc(N), VT);
4601
4602   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4603   if (N1C && N0.getOpcode() == ISD::SRL) {
4604     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4605       uint64_t c1 = N01C->getZExtValue();
4606       uint64_t c2 = N1C->getZExtValue();
4607       SDLoc DL(N);
4608       if (c1 + c2 >= OpSizeInBits)
4609         return DAG.getConstant(0, DL, VT);
4610       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4611                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4612     }
4613   }
4614
4615   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4616   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4617       N0.getOperand(0).getOpcode() == ISD::SRL &&
4618       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4619     uint64_t c1 =
4620       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4621     uint64_t c2 = N1C->getZExtValue();
4622     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4623     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4624     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4625     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4626     if (c1 + OpSizeInBits == InnerShiftSize) {
4627       SDLoc DL(N0);
4628       if (c1 + c2 >= InnerShiftSize)
4629         return DAG.getConstant(0, DL, VT);
4630       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4631                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4632                                      N0.getOperand(0)->getOperand(0),
4633                                      DAG.getConstant(c1 + c2, DL,
4634                                                      ShiftCountVT)));
4635     }
4636   }
4637
4638   // fold (srl (shl x, c), c) -> (and x, cst2)
4639   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4640     unsigned BitSize = N0.getScalarValueSizeInBits();
4641     if (BitSize <= 64) {
4642       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4643       SDLoc DL(N);
4644       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4645                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4646     }
4647   }
4648
4649   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4650   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4651     // Shifting in all undef bits?
4652     EVT SmallVT = N0.getOperand(0).getValueType();
4653     unsigned BitSize = SmallVT.getScalarSizeInBits();
4654     if (N1C->getZExtValue() >= BitSize)
4655       return DAG.getUNDEF(VT);
4656
4657     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4658       uint64_t ShiftAmt = N1C->getZExtValue();
4659       SDLoc DL0(N0);
4660       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4661                                        N0.getOperand(0),
4662                           DAG.getConstant(ShiftAmt, DL0,
4663                                           getShiftAmountTy(SmallVT)));
4664       AddToWorklist(SmallShift.getNode());
4665       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4666       SDLoc DL(N);
4667       return DAG.getNode(ISD::AND, DL, VT,
4668                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4669                          DAG.getConstant(Mask, DL, VT));
4670     }
4671   }
4672
4673   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4674   // bit, which is unmodified by sra.
4675   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4676     if (N0.getOpcode() == ISD::SRA)
4677       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4678   }
4679
4680   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4681   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4682       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4683     APInt KnownZero, KnownOne;
4684     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4685
4686     // If any of the input bits are KnownOne, then the input couldn't be all
4687     // zeros, thus the result of the srl will always be zero.
4688     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4689
4690     // If all of the bits input the to ctlz node are known to be zero, then
4691     // the result of the ctlz is "32" and the result of the shift is one.
4692     APInt UnknownBits = ~KnownZero;
4693     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4694
4695     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4696     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4697       // Okay, we know that only that the single bit specified by UnknownBits
4698       // could be set on input to the CTLZ node. If this bit is set, the SRL
4699       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4700       // to an SRL/XOR pair, which is likely to simplify more.
4701       unsigned ShAmt = UnknownBits.countTrailingZeros();
4702       SDValue Op = N0.getOperand(0);
4703
4704       if (ShAmt) {
4705         SDLoc DL(N0);
4706         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4707                   DAG.getConstant(ShAmt, DL,
4708                                   getShiftAmountTy(Op.getValueType())));
4709         AddToWorklist(Op.getNode());
4710       }
4711
4712       SDLoc DL(N);
4713       return DAG.getNode(ISD::XOR, DL, VT,
4714                          Op, DAG.getConstant(1, DL, VT));
4715     }
4716   }
4717
4718   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4719   if (N1.getOpcode() == ISD::TRUNCATE &&
4720       N1.getOperand(0).getOpcode() == ISD::AND) {
4721     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4722     if (NewOp1.getNode())
4723       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4724   }
4725
4726   // fold operands of srl based on knowledge that the low bits are not
4727   // demanded.
4728   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4729     return SDValue(N, 0);
4730
4731   if (N1C && !N1C->isOpaque()) {
4732     SDValue NewSRL = visitShiftByConstant(N, N1C);
4733     if (NewSRL.getNode())
4734       return NewSRL;
4735   }
4736
4737   // Attempt to convert a srl of a load into a narrower zero-extending load.
4738   SDValue NarrowLoad = ReduceLoadWidth(N);
4739   if (NarrowLoad.getNode())
4740     return NarrowLoad;
4741
4742   // Here is a common situation. We want to optimize:
4743   //
4744   //   %a = ...
4745   //   %b = and i32 %a, 2
4746   //   %c = srl i32 %b, 1
4747   //   brcond i32 %c ...
4748   //
4749   // into
4750   //
4751   //   %a = ...
4752   //   %b = and %a, 2
4753   //   %c = setcc eq %b, 0
4754   //   brcond %c ...
4755   //
4756   // However when after the source operand of SRL is optimized into AND, the SRL
4757   // itself may not be optimized further. Look for it and add the BRCOND into
4758   // the worklist.
4759   if (N->hasOneUse()) {
4760     SDNode *Use = *N->use_begin();
4761     if (Use->getOpcode() == ISD::BRCOND)
4762       AddToWorklist(Use);
4763     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4764       // Also look pass the truncate.
4765       Use = *Use->use_begin();
4766       if (Use->getOpcode() == ISD::BRCOND)
4767         AddToWorklist(Use);
4768     }
4769   }
4770
4771   return SDValue();
4772 }
4773
4774 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4775   SDValue N0 = N->getOperand(0);
4776   EVT VT = N->getValueType(0);
4777
4778   // fold (ctlz c1) -> c2
4779   if (isConstantIntBuildVectorOrConstantInt(N0))
4780     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4781   return SDValue();
4782 }
4783
4784 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4785   SDValue N0 = N->getOperand(0);
4786   EVT VT = N->getValueType(0);
4787
4788   // fold (ctlz_zero_undef c1) -> c2
4789   if (isConstantIntBuildVectorOrConstantInt(N0))
4790     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4791   return SDValue();
4792 }
4793
4794 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4795   SDValue N0 = N->getOperand(0);
4796   EVT VT = N->getValueType(0);
4797
4798   // fold (cttz c1) -> c2
4799   if (isConstantIntBuildVectorOrConstantInt(N0))
4800     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4801   return SDValue();
4802 }
4803
4804 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4805   SDValue N0 = N->getOperand(0);
4806   EVT VT = N->getValueType(0);
4807
4808   // fold (cttz_zero_undef c1) -> c2
4809   if (isConstantIntBuildVectorOrConstantInt(N0))
4810     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4811   return SDValue();
4812 }
4813
4814 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4815   SDValue N0 = N->getOperand(0);
4816   EVT VT = N->getValueType(0);
4817
4818   // fold (ctpop c1) -> c2
4819   if (isConstantIntBuildVectorOrConstantInt(N0))
4820     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4821   return SDValue();
4822 }
4823
4824
4825 /// \brief Generate Min/Max node
4826 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4827                                    SDValue True, SDValue False,
4828                                    ISD::CondCode CC, const TargetLowering &TLI,
4829                                    SelectionDAG &DAG) {
4830   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4831     return SDValue();
4832
4833   switch (CC) {
4834   case ISD::SETOLT:
4835   case ISD::SETOLE:
4836   case ISD::SETLT:
4837   case ISD::SETLE:
4838   case ISD::SETULT:
4839   case ISD::SETULE: {
4840     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4841     if (TLI.isOperationLegal(Opcode, VT))
4842       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4843     return SDValue();
4844   }
4845   case ISD::SETOGT:
4846   case ISD::SETOGE:
4847   case ISD::SETGT:
4848   case ISD::SETGE:
4849   case ISD::SETUGT:
4850   case ISD::SETUGE: {
4851     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4852     if (TLI.isOperationLegal(Opcode, VT))
4853       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4854     return SDValue();
4855   }
4856   default:
4857     return SDValue();
4858   }
4859 }
4860
4861 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4862   SDValue N0 = N->getOperand(0);
4863   SDValue N1 = N->getOperand(1);
4864   SDValue N2 = N->getOperand(2);
4865   EVT VT = N->getValueType(0);
4866   EVT VT0 = N0.getValueType();
4867
4868   // fold (select C, X, X) -> X
4869   if (N1 == N2)
4870     return N1;
4871   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4872     // fold (select true, X, Y) -> X
4873     // fold (select false, X, Y) -> Y
4874     return !N0C->isNullValue() ? N1 : N2;
4875   }
4876   // fold (select C, 1, X) -> (or C, X)
4877   if (VT == MVT::i1 && isOneConstant(N1))
4878     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4879   // fold (select C, 0, 1) -> (xor C, 1)
4880   // We can't do this reliably if integer based booleans have different contents
4881   // to floating point based booleans. This is because we can't tell whether we
4882   // have an integer-based boolean or a floating-point-based boolean unless we
4883   // can find the SETCC that produced it and inspect its operands. This is
4884   // fairly easy if C is the SETCC node, but it can potentially be
4885   // undiscoverable (or not reasonably discoverable). For example, it could be
4886   // in another basic block or it could require searching a complicated
4887   // expression.
4888   if (VT.isInteger() &&
4889       (VT0 == MVT::i1 || (VT0.isInteger() &&
4890                           TLI.getBooleanContents(false, false) ==
4891                               TLI.getBooleanContents(false, true) &&
4892                           TLI.getBooleanContents(false, false) ==
4893                               TargetLowering::ZeroOrOneBooleanContent)) &&
4894       isNullConstant(N1) && isOneConstant(N2)) {
4895     SDValue XORNode;
4896     if (VT == VT0) {
4897       SDLoc DL(N);
4898       return DAG.getNode(ISD::XOR, DL, VT0,
4899                          N0, DAG.getConstant(1, DL, VT0));
4900     }
4901     SDLoc DL0(N0);
4902     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4903                           N0, DAG.getConstant(1, DL0, VT0));
4904     AddToWorklist(XORNode.getNode());
4905     if (VT.bitsGT(VT0))
4906       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4907     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4908   }
4909   // fold (select C, 0, X) -> (and (not C), X)
4910   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4911     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4912     AddToWorklist(NOTNode.getNode());
4913     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4914   }
4915   // fold (select C, X, 1) -> (or (not C), X)
4916   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4917     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4918     AddToWorklist(NOTNode.getNode());
4919     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4920   }
4921   // fold (select C, X, 0) -> (and C, X)
4922   if (VT == MVT::i1 && isNullConstant(N2))
4923     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4924   // fold (select X, X, Y) -> (or X, Y)
4925   // fold (select X, 1, Y) -> (or X, Y)
4926   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4927     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4928   // fold (select X, Y, X) -> (and X, Y)
4929   // fold (select X, Y, 0) -> (and X, Y)
4930   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4931     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4932
4933   // If we can fold this based on the true/false value, do so.
4934   if (SimplifySelectOps(N, N1, N2))
4935     return SDValue(N, 0);  // Don't revisit N.
4936
4937   // fold selects based on a setcc into other things, such as min/max/abs
4938   if (N0.getOpcode() == ISD::SETCC) {
4939     // select x, y (fcmp lt x, y) -> fminnum x, y
4940     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4941     //
4942     // This is OK if we don't care about what happens if either operand is a
4943     // NaN.
4944     //
4945
4946     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4947     // no signed zeros as well as no nans.
4948     const TargetOptions &Options = DAG.getTarget().Options;
4949     if (Options.UnsafeFPMath &&
4950         VT.isFloatingPoint() && N0.hasOneUse() &&
4951         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4952       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4953
4954       SDValue FMinMax =
4955           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4956                               N1, N2, CC, TLI, DAG);
4957       if (FMinMax)
4958         return FMinMax;
4959     }
4960
4961     if ((!LegalOperations &&
4962          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4963         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4964       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4965                          N0.getOperand(0), N0.getOperand(1),
4966                          N1, N2, N0.getOperand(2));
4967     return SimplifySelect(SDLoc(N), N0, N1, N2);
4968   }
4969
4970   if (VT0 == MVT::i1) {
4971     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4972       // select (and Cond0, Cond1), X, Y
4973       //   -> select Cond0, (select Cond1, X, Y), Y
4974       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4975         SDValue Cond0 = N0->getOperand(0);
4976         SDValue Cond1 = N0->getOperand(1);
4977         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4978                                           N1.getValueType(), Cond1, N1, N2);
4979         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4980                            InnerSelect, N2);
4981       }
4982       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4983       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4984         SDValue Cond0 = N0->getOperand(0);
4985         SDValue Cond1 = N0->getOperand(1);
4986         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4987                                           N1.getValueType(), Cond1, N1, N2);
4988         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4989                            InnerSelect);
4990       }
4991     }
4992
4993     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4994     if (N1->getOpcode() == ISD::SELECT) {
4995       SDValue N1_0 = N1->getOperand(0);
4996       SDValue N1_1 = N1->getOperand(1);
4997       SDValue N1_2 = N1->getOperand(2);
4998       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4999         // Create the actual and node if we can generate good code for it.
5000         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5001           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5002                                     N0, N1_0);
5003           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5004                              N1_1, N2);
5005         }
5006         // Otherwise see if we can optimize the "and" to a better pattern.
5007         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5008           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5009                              N1_1, N2);
5010       }
5011     }
5012     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5013     if (N2->getOpcode() == ISD::SELECT) {
5014       SDValue N2_0 = N2->getOperand(0);
5015       SDValue N2_1 = N2->getOperand(1);
5016       SDValue N2_2 = N2->getOperand(2);
5017       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5018         // Create the actual or node if we can generate good code for it.
5019         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5020           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5021                                    N0, N2_0);
5022           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5023                              N1, N2_2);
5024         }
5025         // Otherwise see if we can optimize to a better pattern.
5026         if (SDValue Combined = visitORLike(N0, N2_0, N))
5027           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5028                              N1, N2_2);
5029       }
5030     }
5031   }
5032
5033   return SDValue();
5034 }
5035
5036 static
5037 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5038   SDLoc DL(N);
5039   EVT LoVT, HiVT;
5040   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5041
5042   // Split the inputs.
5043   SDValue Lo, Hi, LL, LH, RL, RH;
5044   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5045   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5046
5047   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5048   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5049
5050   return std::make_pair(Lo, Hi);
5051 }
5052
5053 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5054 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5055 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5056   SDLoc dl(N);
5057   SDValue Cond = N->getOperand(0);
5058   SDValue LHS = N->getOperand(1);
5059   SDValue RHS = N->getOperand(2);
5060   EVT VT = N->getValueType(0);
5061   int NumElems = VT.getVectorNumElements();
5062   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5063          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5064          Cond.getOpcode() == ISD::BUILD_VECTOR);
5065
5066   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5067   // binary ones here.
5068   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5069     return SDValue();
5070
5071   // We're sure we have an even number of elements due to the
5072   // concat_vectors we have as arguments to vselect.
5073   // Skip BV elements until we find one that's not an UNDEF
5074   // After we find an UNDEF element, keep looping until we get to half the
5075   // length of the BV and see if all the non-undef nodes are the same.
5076   ConstantSDNode *BottomHalf = nullptr;
5077   for (int i = 0; i < NumElems / 2; ++i) {
5078     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5079       continue;
5080
5081     if (BottomHalf == nullptr)
5082       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5083     else if (Cond->getOperand(i).getNode() != BottomHalf)
5084       return SDValue();
5085   }
5086
5087   // Do the same for the second half of the BuildVector
5088   ConstantSDNode *TopHalf = nullptr;
5089   for (int i = NumElems / 2; i < NumElems; ++i) {
5090     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5091       continue;
5092
5093     if (TopHalf == nullptr)
5094       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5095     else if (Cond->getOperand(i).getNode() != TopHalf)
5096       return SDValue();
5097   }
5098
5099   assert(TopHalf && BottomHalf &&
5100          "One half of the selector was all UNDEFs and the other was all the "
5101          "same value. This should have been addressed before this function.");
5102   return DAG.getNode(
5103       ISD::CONCAT_VECTORS, dl, VT,
5104       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5105       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5106 }
5107
5108 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5109
5110   if (Level >= AfterLegalizeTypes)
5111     return SDValue();
5112
5113   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5114   SDValue Mask = MSC->getMask();
5115   SDValue Data  = MSC->getValue();
5116   SDLoc DL(N);
5117
5118   // If the MSCATTER data type requires splitting and the mask is provided by a
5119   // SETCC, then split both nodes and its operands before legalization. This
5120   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5121   // and enables future optimizations (e.g. min/max pattern matching on X86).
5122   if (Mask.getOpcode() != ISD::SETCC)
5123     return SDValue();
5124
5125   // Check if any splitting is required.
5126   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5127       TargetLowering::TypeSplitVector)
5128     return SDValue();
5129   SDValue MaskLo, MaskHi, Lo, Hi;
5130   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5131
5132   EVT LoVT, HiVT;
5133   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5134
5135   SDValue Chain = MSC->getChain();
5136
5137   EVT MemoryVT = MSC->getMemoryVT();
5138   unsigned Alignment = MSC->getOriginalAlignment();
5139
5140   EVT LoMemVT, HiMemVT;
5141   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5142
5143   SDValue DataLo, DataHi;
5144   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5145
5146   SDValue BasePtr = MSC->getBasePtr();
5147   SDValue IndexLo, IndexHi;
5148   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5149
5150   MachineMemOperand *MMO = DAG.getMachineFunction().
5151     getMachineMemOperand(MSC->getPointerInfo(), 
5152                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5153                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5154
5155   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5156   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5157                             DL, OpsLo, MMO);
5158
5159   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5160   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5161                             DL, OpsHi, MMO);
5162
5163   AddToWorklist(Lo.getNode());
5164   AddToWorklist(Hi.getNode());
5165
5166   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5167 }
5168
5169 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5170
5171   if (Level >= AfterLegalizeTypes)
5172     return SDValue();
5173
5174   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5175   SDValue Mask = MST->getMask();
5176   SDValue Data  = MST->getValue();
5177   SDLoc DL(N);
5178
5179   // If the MSTORE data type requires splitting and the mask is provided by a
5180   // SETCC, then split both nodes and its operands before legalization. This
5181   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5182   // and enables future optimizations (e.g. min/max pattern matching on X86).
5183   if (Mask.getOpcode() == ISD::SETCC) {
5184
5185     // Check if any splitting is required.
5186     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5187         TargetLowering::TypeSplitVector)
5188       return SDValue();
5189
5190     SDValue MaskLo, MaskHi, Lo, Hi;
5191     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5192
5193     EVT LoVT, HiVT;
5194     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5195
5196     SDValue Chain = MST->getChain();
5197     SDValue Ptr   = MST->getBasePtr();
5198
5199     EVT MemoryVT = MST->getMemoryVT();
5200     unsigned Alignment = MST->getOriginalAlignment();
5201
5202     // if Alignment is equal to the vector size,
5203     // take the half of it for the second part
5204     unsigned SecondHalfAlignment =
5205       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5206          Alignment/2 : Alignment;
5207
5208     EVT LoMemVT, HiMemVT;
5209     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5210
5211     SDValue DataLo, DataHi;
5212     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5213
5214     MachineMemOperand *MMO = DAG.getMachineFunction().
5215       getMachineMemOperand(MST->getPointerInfo(),
5216                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5217                            Alignment, MST->getAAInfo(), MST->getRanges());
5218
5219     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5220                             MST->isTruncatingStore());
5221
5222     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5223     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5224                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5225
5226     MMO = DAG.getMachineFunction().
5227       getMachineMemOperand(MST->getPointerInfo(),
5228                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5229                            SecondHalfAlignment, MST->getAAInfo(),
5230                            MST->getRanges());
5231
5232     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5233                             MST->isTruncatingStore());
5234
5235     AddToWorklist(Lo.getNode());
5236     AddToWorklist(Hi.getNode());
5237
5238     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5239   }
5240   return SDValue();
5241 }
5242
5243 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5244
5245   if (Level >= AfterLegalizeTypes)
5246     return SDValue();
5247
5248   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5249   SDValue Mask = MGT->getMask();
5250   SDLoc DL(N);
5251
5252   // If the MGATHER result requires splitting and the mask is provided by a
5253   // SETCC, then split both nodes and its operands before legalization. This
5254   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5255   // and enables future optimizations (e.g. min/max pattern matching on X86).
5256
5257   if (Mask.getOpcode() != ISD::SETCC)
5258     return SDValue();
5259
5260   EVT VT = N->getValueType(0);
5261
5262   // Check if any splitting is required.
5263   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5264       TargetLowering::TypeSplitVector)
5265     return SDValue();
5266
5267   SDValue MaskLo, MaskHi, Lo, Hi;
5268   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5269
5270   SDValue Src0 = MGT->getValue();
5271   SDValue Src0Lo, Src0Hi;
5272   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5273
5274   EVT LoVT, HiVT;
5275   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5276
5277   SDValue Chain = MGT->getChain();
5278   EVT MemoryVT = MGT->getMemoryVT();
5279   unsigned Alignment = MGT->getOriginalAlignment();
5280
5281   EVT LoMemVT, HiMemVT;
5282   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5283
5284   SDValue BasePtr = MGT->getBasePtr();
5285   SDValue Index = MGT->getIndex();
5286   SDValue IndexLo, IndexHi;
5287   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5288
5289   MachineMemOperand *MMO = DAG.getMachineFunction().
5290     getMachineMemOperand(MGT->getPointerInfo(), 
5291                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5292                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5293
5294   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5295   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5296                             MMO);
5297
5298   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5299   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5300                             MMO);
5301
5302   AddToWorklist(Lo.getNode());
5303   AddToWorklist(Hi.getNode());
5304
5305   // Build a factor node to remember that this load is independent of the
5306   // other one.
5307   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5308                       Hi.getValue(1));
5309
5310   // Legalized the chain result - switch anything that used the old chain to
5311   // use the new one.
5312   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5313
5314   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5315
5316   SDValue RetOps[] = { GatherRes, Chain };
5317   return DAG.getMergeValues(RetOps, DL);
5318 }
5319
5320 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5321
5322   if (Level >= AfterLegalizeTypes)
5323     return SDValue();
5324
5325   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5326   SDValue Mask = MLD->getMask();
5327   SDLoc DL(N);
5328
5329   // If the MLOAD result requires splitting and the mask is provided by a
5330   // SETCC, then split both nodes and its operands before legalization. This
5331   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5332   // and enables future optimizations (e.g. min/max pattern matching on X86).
5333
5334   if (Mask.getOpcode() == ISD::SETCC) {
5335     EVT VT = N->getValueType(0);
5336
5337     // Check if any splitting is required.
5338     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5339         TargetLowering::TypeSplitVector)
5340       return SDValue();
5341
5342     SDValue MaskLo, MaskHi, Lo, Hi;
5343     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5344
5345     SDValue Src0 = MLD->getSrc0();
5346     SDValue Src0Lo, Src0Hi;
5347     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5348
5349     EVT LoVT, HiVT;
5350     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5351
5352     SDValue Chain = MLD->getChain();
5353     SDValue Ptr   = MLD->getBasePtr();
5354     EVT MemoryVT = MLD->getMemoryVT();
5355     unsigned Alignment = MLD->getOriginalAlignment();
5356
5357     // if Alignment is equal to the vector size,
5358     // take the half of it for the second part
5359     unsigned SecondHalfAlignment =
5360       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5361          Alignment/2 : Alignment;
5362
5363     EVT LoMemVT, HiMemVT;
5364     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5365
5366     MachineMemOperand *MMO = DAG.getMachineFunction().
5367     getMachineMemOperand(MLD->getPointerInfo(),
5368                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5369                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5370
5371     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5372                            ISD::NON_EXTLOAD);
5373
5374     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5375     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5376                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5377
5378     MMO = DAG.getMachineFunction().
5379     getMachineMemOperand(MLD->getPointerInfo(),
5380                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5381                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5382
5383     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5384                            ISD::NON_EXTLOAD);
5385
5386     AddToWorklist(Lo.getNode());
5387     AddToWorklist(Hi.getNode());
5388
5389     // Build a factor node to remember that this load is independent of the
5390     // other one.
5391     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5392                         Hi.getValue(1));
5393
5394     // Legalized the chain result - switch anything that used the old chain to
5395     // use the new one.
5396     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5397
5398     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5399
5400     SDValue RetOps[] = { LoadRes, Chain };
5401     return DAG.getMergeValues(RetOps, DL);
5402   }
5403   return SDValue();
5404 }
5405
5406 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5407   SDValue N0 = N->getOperand(0);
5408   SDValue N1 = N->getOperand(1);
5409   SDValue N2 = N->getOperand(2);
5410   SDLoc DL(N);
5411
5412   // Canonicalize integer abs.
5413   // vselect (setg[te] X,  0),  X, -X ->
5414   // vselect (setgt    X, -1),  X, -X ->
5415   // vselect (setl[te] X,  0), -X,  X ->
5416   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5417   if (N0.getOpcode() == ISD::SETCC) {
5418     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5419     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5420     bool isAbs = false;
5421     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5422
5423     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5424          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5425         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5426       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5427     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5428              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5429       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5430
5431     if (isAbs) {
5432       EVT VT = LHS.getValueType();
5433       SDValue Shift = DAG.getNode(
5434           ISD::SRA, DL, VT, LHS,
5435           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5436       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5437       AddToWorklist(Shift.getNode());
5438       AddToWorklist(Add.getNode());
5439       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5440     }
5441   }
5442
5443   if (SimplifySelectOps(N, N1, N2))
5444     return SDValue(N, 0);  // Don't revisit N.
5445
5446   // If the VSELECT result requires splitting and the mask is provided by a
5447   // SETCC, then split both nodes and its operands before legalization. This
5448   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5449   // and enables future optimizations (e.g. min/max pattern matching on X86).
5450   if (N0.getOpcode() == ISD::SETCC) {
5451     EVT VT = N->getValueType(0);
5452
5453     // Check if any splitting is required.
5454     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5455         TargetLowering::TypeSplitVector)
5456       return SDValue();
5457
5458     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5459     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5460     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5461     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5462
5463     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5464     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5465
5466     // Add the new VSELECT nodes to the work list in case they need to be split
5467     // again.
5468     AddToWorklist(Lo.getNode());
5469     AddToWorklist(Hi.getNode());
5470
5471     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5472   }
5473
5474   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5475   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5476     return N1;
5477   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5478   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5479     return N2;
5480
5481   // The ConvertSelectToConcatVector function is assuming both the above
5482   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5483   // and addressed.
5484   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5485       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5486       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5487     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5488     if (CV.getNode())
5489       return CV;
5490   }
5491
5492   return SDValue();
5493 }
5494
5495 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5496   SDValue N0 = N->getOperand(0);
5497   SDValue N1 = N->getOperand(1);
5498   SDValue N2 = N->getOperand(2);
5499   SDValue N3 = N->getOperand(3);
5500   SDValue N4 = N->getOperand(4);
5501   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5502
5503   // fold select_cc lhs, rhs, x, x, cc -> x
5504   if (N2 == N3)
5505     return N2;
5506
5507   // Determine if the condition we're dealing with is constant
5508   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5509                               N0, N1, CC, SDLoc(N), false);
5510   if (SCC.getNode()) {
5511     AddToWorklist(SCC.getNode());
5512
5513     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5514       if (!SCCC->isNullValue())
5515         return N2;    // cond always true -> true val
5516       else
5517         return N3;    // cond always false -> false val
5518     } else if (SCC->getOpcode() == ISD::UNDEF) {
5519       // When the condition is UNDEF, just return the first operand. This is
5520       // coherent the DAG creation, no setcc node is created in this case
5521       return N2;
5522     } else if (SCC.getOpcode() == ISD::SETCC) {
5523       // Fold to a simpler select_cc
5524       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5525                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5526                          SCC.getOperand(2));
5527     }
5528   }
5529
5530   // If we can fold this based on the true/false value, do so.
5531   if (SimplifySelectOps(N, N2, N3))
5532     return SDValue(N, 0);  // Don't revisit N.
5533
5534   // fold select_cc into other things, such as min/max/abs
5535   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5536 }
5537
5538 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5539   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5540                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5541                        SDLoc(N));
5542 }
5543
5544 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5545 // dag node into a ConstantSDNode or a build_vector of constants.
5546 // This function is called by the DAGCombiner when visiting sext/zext/aext
5547 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5548 // Vector extends are not folded if operations are legal; this is to
5549 // avoid introducing illegal build_vector dag nodes.
5550 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5551                                          SelectionDAG &DAG, bool LegalTypes,
5552                                          bool LegalOperations) {
5553   unsigned Opcode = N->getOpcode();
5554   SDValue N0 = N->getOperand(0);
5555   EVT VT = N->getValueType(0);
5556
5557   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5558          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5559          && "Expected EXTEND dag node in input!");
5560
5561   // fold (sext c1) -> c1
5562   // fold (zext c1) -> c1
5563   // fold (aext c1) -> c1
5564   if (isa<ConstantSDNode>(N0))
5565     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5566
5567   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5568   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5569   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5570   EVT SVT = VT.getScalarType();
5571   if (!(VT.isVector() &&
5572       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5573       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5574     return nullptr;
5575
5576   // We can fold this node into a build_vector.
5577   unsigned VTBits = SVT.getSizeInBits();
5578   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5579   unsigned ShAmt = VTBits - EVTBits;
5580   SmallVector<SDValue, 8> Elts;
5581   unsigned NumElts = VT.getVectorNumElements();
5582   SDLoc DL(N);
5583
5584   for (unsigned i=0; i != NumElts; ++i) {
5585     SDValue Op = N0->getOperand(i);
5586     if (Op->getOpcode() == ISD::UNDEF) {
5587       Elts.push_back(DAG.getUNDEF(SVT));
5588       continue;
5589     }
5590
5591     SDLoc DL(Op);
5592     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5593     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5594     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5595       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5596                                      DL, SVT));
5597     else
5598       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5599                                      DL, SVT));
5600   }
5601
5602   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5603 }
5604
5605 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5606 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5607 // transformation. Returns true if extension are possible and the above
5608 // mentioned transformation is profitable.
5609 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5610                                     unsigned ExtOpc,
5611                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5612                                     const TargetLowering &TLI) {
5613   bool HasCopyToRegUses = false;
5614   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5615   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5616                             UE = N0.getNode()->use_end();
5617        UI != UE; ++UI) {
5618     SDNode *User = *UI;
5619     if (User == N)
5620       continue;
5621     if (UI.getUse().getResNo() != N0.getResNo())
5622       continue;
5623     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5624     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5625       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5626       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5627         // Sign bits will be lost after a zext.
5628         return false;
5629       bool Add = false;
5630       for (unsigned i = 0; i != 2; ++i) {
5631         SDValue UseOp = User->getOperand(i);
5632         if (UseOp == N0)
5633           continue;
5634         if (!isa<ConstantSDNode>(UseOp))
5635           return false;
5636         Add = true;
5637       }
5638       if (Add)
5639         ExtendNodes.push_back(User);
5640       continue;
5641     }
5642     // If truncates aren't free and there are users we can't
5643     // extend, it isn't worthwhile.
5644     if (!isTruncFree)
5645       return false;
5646     // Remember if this value is live-out.
5647     if (User->getOpcode() == ISD::CopyToReg)
5648       HasCopyToRegUses = true;
5649   }
5650
5651   if (HasCopyToRegUses) {
5652     bool BothLiveOut = false;
5653     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5654          UI != UE; ++UI) {
5655       SDUse &Use = UI.getUse();
5656       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5657         BothLiveOut = true;
5658         break;
5659       }
5660     }
5661     if (BothLiveOut)
5662       // Both unextended and extended values are live out. There had better be
5663       // a good reason for the transformation.
5664       return ExtendNodes.size();
5665   }
5666   return true;
5667 }
5668
5669 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5670                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5671                                   ISD::NodeType ExtType) {
5672   // Extend SetCC uses if necessary.
5673   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5674     SDNode *SetCC = SetCCs[i];
5675     SmallVector<SDValue, 4> Ops;
5676
5677     for (unsigned j = 0; j != 2; ++j) {
5678       SDValue SOp = SetCC->getOperand(j);
5679       if (SOp == Trunc)
5680         Ops.push_back(ExtLoad);
5681       else
5682         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5683     }
5684
5685     Ops.push_back(SetCC->getOperand(2));
5686     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5687   }
5688 }
5689
5690 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5691 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5692   SDValue N0 = N->getOperand(0);
5693   EVT DstVT = N->getValueType(0);
5694   EVT SrcVT = N0.getValueType();
5695
5696   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5697           N->getOpcode() == ISD::ZERO_EXTEND) &&
5698          "Unexpected node type (not an extend)!");
5699
5700   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5701   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5702   //   (v8i32 (sext (v8i16 (load x))))
5703   // into:
5704   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5705   //                          (v4i32 (sextload (x + 16)))))
5706   // Where uses of the original load, i.e.:
5707   //   (v8i16 (load x))
5708   // are replaced with:
5709   //   (v8i16 (truncate
5710   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5711   //                            (v4i32 (sextload (x + 16)))))))
5712   //
5713   // This combine is only applicable to illegal, but splittable, vectors.
5714   // All legal types, and illegal non-vector types, are handled elsewhere.
5715   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5716   //
5717   if (N0->getOpcode() != ISD::LOAD)
5718     return SDValue();
5719
5720   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5721
5722   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5723       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5724       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5725     return SDValue();
5726
5727   SmallVector<SDNode *, 4> SetCCs;
5728   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5729     return SDValue();
5730
5731   ISD::LoadExtType ExtType =
5732       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5733
5734   // Try to split the vector types to get down to legal types.
5735   EVT SplitSrcVT = SrcVT;
5736   EVT SplitDstVT = DstVT;
5737   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5738          SplitSrcVT.getVectorNumElements() > 1) {
5739     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5740     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5741   }
5742
5743   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5744     return SDValue();
5745
5746   SDLoc DL(N);
5747   const unsigned NumSplits =
5748       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5749   const unsigned Stride = SplitSrcVT.getStoreSize();
5750   SmallVector<SDValue, 4> Loads;
5751   SmallVector<SDValue, 4> Chains;
5752
5753   SDValue BasePtr = LN0->getBasePtr();
5754   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5755     const unsigned Offset = Idx * Stride;
5756     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5757
5758     SDValue SplitLoad = DAG.getExtLoad(
5759         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5760         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5761         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5762         Align, LN0->getAAInfo());
5763
5764     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5765                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5766
5767     Loads.push_back(SplitLoad.getValue(0));
5768     Chains.push_back(SplitLoad.getValue(1));
5769   }
5770
5771   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5772   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5773
5774   CombineTo(N, NewValue);
5775
5776   // Replace uses of the original load (before extension)
5777   // with a truncate of the concatenated sextloaded vectors.
5778   SDValue Trunc =
5779       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5780   CombineTo(N0.getNode(), Trunc, NewChain);
5781   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5782                   (ISD::NodeType)N->getOpcode());
5783   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5784 }
5785
5786 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5787   SDValue N0 = N->getOperand(0);
5788   EVT VT = N->getValueType(0);
5789
5790   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5791                                               LegalOperations))
5792     return SDValue(Res, 0);
5793
5794   // fold (sext (sext x)) -> (sext x)
5795   // fold (sext (aext x)) -> (sext x)
5796   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5797     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5798                        N0.getOperand(0));
5799
5800   if (N0.getOpcode() == ISD::TRUNCATE) {
5801     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5802     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5803     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5804     if (NarrowLoad.getNode()) {
5805       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5806       if (NarrowLoad.getNode() != N0.getNode()) {
5807         CombineTo(N0.getNode(), NarrowLoad);
5808         // CombineTo deleted the truncate, if needed, but not what's under it.
5809         AddToWorklist(oye);
5810       }
5811       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5812     }
5813
5814     // See if the value being truncated is already sign extended.  If so, just
5815     // eliminate the trunc/sext pair.
5816     SDValue Op = N0.getOperand(0);
5817     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5818     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5819     unsigned DestBits = VT.getScalarType().getSizeInBits();
5820     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5821
5822     if (OpBits == DestBits) {
5823       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5824       // bits, it is already ready.
5825       if (NumSignBits > DestBits-MidBits)
5826         return Op;
5827     } else if (OpBits < DestBits) {
5828       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5829       // bits, just sext from i32.
5830       if (NumSignBits > OpBits-MidBits)
5831         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5832     } else {
5833       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5834       // bits, just truncate to i32.
5835       if (NumSignBits > OpBits-MidBits)
5836         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5837     }
5838
5839     // fold (sext (truncate x)) -> (sextinreg x).
5840     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5841                                                  N0.getValueType())) {
5842       if (OpBits < DestBits)
5843         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5844       else if (OpBits > DestBits)
5845         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5846       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5847                          DAG.getValueType(N0.getValueType()));
5848     }
5849   }
5850
5851   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5852   // Only generate vector extloads when 1) they're legal, and 2) they are
5853   // deemed desirable by the target.
5854   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5855       ((!LegalOperations && !VT.isVector() &&
5856         !cast<LoadSDNode>(N0)->isVolatile()) ||
5857        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5858     bool DoXform = true;
5859     SmallVector<SDNode*, 4> SetCCs;
5860     if (!N0.hasOneUse())
5861       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5862     if (VT.isVector())
5863       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5864     if (DoXform) {
5865       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5866       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5867                                        LN0->getChain(),
5868                                        LN0->getBasePtr(), N0.getValueType(),
5869                                        LN0->getMemOperand());
5870       CombineTo(N, ExtLoad);
5871       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5872                                   N0.getValueType(), ExtLoad);
5873       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5874       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5875                       ISD::SIGN_EXTEND);
5876       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5877     }
5878   }
5879
5880   // fold (sext (load x)) to multiple smaller sextloads.
5881   // Only on illegal but splittable vectors.
5882   if (SDValue ExtLoad = CombineExtLoad(N))
5883     return ExtLoad;
5884
5885   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5886   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5887   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5888       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5889     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5890     EVT MemVT = LN0->getMemoryVT();
5891     if ((!LegalOperations && !LN0->isVolatile()) ||
5892         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5893       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5894                                        LN0->getChain(),
5895                                        LN0->getBasePtr(), MemVT,
5896                                        LN0->getMemOperand());
5897       CombineTo(N, ExtLoad);
5898       CombineTo(N0.getNode(),
5899                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5900                             N0.getValueType(), ExtLoad),
5901                 ExtLoad.getValue(1));
5902       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5903     }
5904   }
5905
5906   // fold (sext (and/or/xor (load x), cst)) ->
5907   //      (and/or/xor (sextload x), (sext cst))
5908   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5909        N0.getOpcode() == ISD::XOR) &&
5910       isa<LoadSDNode>(N0.getOperand(0)) &&
5911       N0.getOperand(1).getOpcode() == ISD::Constant &&
5912       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5913       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5914     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5915     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5916       bool DoXform = true;
5917       SmallVector<SDNode*, 4> SetCCs;
5918       if (!N0.hasOneUse())
5919         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5920                                           SetCCs, TLI);
5921       if (DoXform) {
5922         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5923                                          LN0->getChain(), LN0->getBasePtr(),
5924                                          LN0->getMemoryVT(),
5925                                          LN0->getMemOperand());
5926         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5927         Mask = Mask.sext(VT.getSizeInBits());
5928         SDLoc DL(N);
5929         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5930                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5931         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5932                                     SDLoc(N0.getOperand(0)),
5933                                     N0.getOperand(0).getValueType(), ExtLoad);
5934         CombineTo(N, And);
5935         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5936         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5937                         ISD::SIGN_EXTEND);
5938         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5939       }
5940     }
5941   }
5942
5943   if (N0.getOpcode() == ISD::SETCC) {
5944     EVT N0VT = N0.getOperand(0).getValueType();
5945     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5946     // Only do this before legalize for now.
5947     if (VT.isVector() && !LegalOperations &&
5948         TLI.getBooleanContents(N0VT) ==
5949             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5950       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5951       // of the same size as the compared operands. Only optimize sext(setcc())
5952       // if this is the case.
5953       EVT SVT = getSetCCResultType(N0VT);
5954
5955       // We know that the # elements of the results is the same as the
5956       // # elements of the compare (and the # elements of the compare result
5957       // for that matter).  Check to see that they are the same size.  If so,
5958       // we know that the element size of the sext'd result matches the
5959       // element size of the compare operands.
5960       if (VT.getSizeInBits() == SVT.getSizeInBits())
5961         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5962                              N0.getOperand(1),
5963                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5964
5965       // If the desired elements are smaller or larger than the source
5966       // elements we can use a matching integer vector type and then
5967       // truncate/sign extend
5968       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5969       if (SVT == MatchingVectorType) {
5970         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5971                                N0.getOperand(0), N0.getOperand(1),
5972                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5973         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5974       }
5975     }
5976
5977     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5978     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5979     SDLoc DL(N);
5980     SDValue NegOne =
5981       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5982     SDValue SCC =
5983       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5984                        NegOne, DAG.getConstant(0, DL, VT),
5985                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5986     if (SCC.getNode()) return SCC;
5987
5988     if (!VT.isVector()) {
5989       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5990       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5991         SDLoc DL(N);
5992         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5993         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5994                                      N0.getOperand(0), N0.getOperand(1), CC);
5995         return DAG.getSelect(DL, VT, SetCC,
5996                              NegOne, DAG.getConstant(0, DL, VT));
5997       }
5998     }
5999   }
6000
6001   // fold (sext x) -> (zext x) if the sign bit is known zero.
6002   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6003       DAG.SignBitIsZero(N0))
6004     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6005
6006   return SDValue();
6007 }
6008
6009 // isTruncateOf - If N is a truncate of some other value, return true, record
6010 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6011 // This function computes KnownZero to avoid a duplicated call to
6012 // computeKnownBits in the caller.
6013 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6014                          APInt &KnownZero) {
6015   APInt KnownOne;
6016   if (N->getOpcode() == ISD::TRUNCATE) {
6017     Op = N->getOperand(0);
6018     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6019     return true;
6020   }
6021
6022   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6023       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6024     return false;
6025
6026   SDValue Op0 = N->getOperand(0);
6027   SDValue Op1 = N->getOperand(1);
6028   assert(Op0.getValueType() == Op1.getValueType());
6029
6030   if (isNullConstant(Op0))
6031     Op = Op1;
6032   else if (isNullConstant(Op1))
6033     Op = Op0;
6034   else
6035     return false;
6036
6037   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6038
6039   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6040     return false;
6041
6042   return true;
6043 }
6044
6045 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6046   SDValue N0 = N->getOperand(0);
6047   EVT VT = N->getValueType(0);
6048
6049   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6050                                               LegalOperations))
6051     return SDValue(Res, 0);
6052
6053   // fold (zext (zext x)) -> (zext x)
6054   // fold (zext (aext x)) -> (zext x)
6055   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6056     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6057                        N0.getOperand(0));
6058
6059   // fold (zext (truncate x)) -> (zext x) or
6060   //      (zext (truncate x)) -> (truncate x)
6061   // This is valid when the truncated bits of x are already zero.
6062   // FIXME: We should extend this to work for vectors too.
6063   SDValue Op;
6064   APInt KnownZero;
6065   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6066     APInt TruncatedBits =
6067       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6068       APInt(Op.getValueSizeInBits(), 0) :
6069       APInt::getBitsSet(Op.getValueSizeInBits(),
6070                         N0.getValueSizeInBits(),
6071                         std::min(Op.getValueSizeInBits(),
6072                                  VT.getSizeInBits()));
6073     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6074       if (VT.bitsGT(Op.getValueType()))
6075         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6076       if (VT.bitsLT(Op.getValueType()))
6077         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6078
6079       return Op;
6080     }
6081   }
6082
6083   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6084   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6085   if (N0.getOpcode() == ISD::TRUNCATE) {
6086     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6087     if (NarrowLoad.getNode()) {
6088       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6089       if (NarrowLoad.getNode() != N0.getNode()) {
6090         CombineTo(N0.getNode(), NarrowLoad);
6091         // CombineTo deleted the truncate, if needed, but not what's under it.
6092         AddToWorklist(oye);
6093       }
6094       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6095     }
6096   }
6097
6098   // fold (zext (truncate x)) -> (and x, mask)
6099   if (N0.getOpcode() == ISD::TRUNCATE &&
6100       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6101
6102     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6103     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6104     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6105     if (NarrowLoad.getNode()) {
6106       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6107       if (NarrowLoad.getNode() != N0.getNode()) {
6108         CombineTo(N0.getNode(), NarrowLoad);
6109         // CombineTo deleted the truncate, if needed, but not what's under it.
6110         AddToWorklist(oye);
6111       }
6112       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6113     }
6114
6115     SDValue Op = N0.getOperand(0);
6116     if (Op.getValueType().bitsLT(VT)) {
6117       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6118       AddToWorklist(Op.getNode());
6119     } else if (Op.getValueType().bitsGT(VT)) {
6120       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6121       AddToWorklist(Op.getNode());
6122     }
6123     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6124                                   N0.getValueType().getScalarType());
6125   }
6126
6127   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6128   // if either of the casts is not free.
6129   if (N0.getOpcode() == ISD::AND &&
6130       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6131       N0.getOperand(1).getOpcode() == ISD::Constant &&
6132       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6133                            N0.getValueType()) ||
6134        !TLI.isZExtFree(N0.getValueType(), VT))) {
6135     SDValue X = N0.getOperand(0).getOperand(0);
6136     if (X.getValueType().bitsLT(VT)) {
6137       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6138     } else if (X.getValueType().bitsGT(VT)) {
6139       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6140     }
6141     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6142     Mask = Mask.zext(VT.getSizeInBits());
6143     SDLoc DL(N);
6144     return DAG.getNode(ISD::AND, DL, VT,
6145                        X, DAG.getConstant(Mask, DL, VT));
6146   }
6147
6148   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6149   // Only generate vector extloads when 1) they're legal, and 2) they are
6150   // deemed desirable by the target.
6151   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6152       ((!LegalOperations && !VT.isVector() &&
6153         !cast<LoadSDNode>(N0)->isVolatile()) ||
6154        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6155     bool DoXform = true;
6156     SmallVector<SDNode*, 4> SetCCs;
6157     if (!N0.hasOneUse())
6158       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6159     if (VT.isVector())
6160       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6161     if (DoXform) {
6162       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6164                                        LN0->getChain(),
6165                                        LN0->getBasePtr(), N0.getValueType(),
6166                                        LN0->getMemOperand());
6167       CombineTo(N, ExtLoad);
6168       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6169                                   N0.getValueType(), ExtLoad);
6170       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6171
6172       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6173                       ISD::ZERO_EXTEND);
6174       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6175     }
6176   }
6177
6178   // fold (zext (load x)) to multiple smaller zextloads.
6179   // Only on illegal but splittable vectors.
6180   if (SDValue ExtLoad = CombineExtLoad(N))
6181     return ExtLoad;
6182
6183   // fold (zext (and/or/xor (load x), cst)) ->
6184   //      (and/or/xor (zextload x), (zext cst))
6185   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6186        N0.getOpcode() == ISD::XOR) &&
6187       isa<LoadSDNode>(N0.getOperand(0)) &&
6188       N0.getOperand(1).getOpcode() == ISD::Constant &&
6189       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6190       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6191     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6192     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6193       bool DoXform = true;
6194       SmallVector<SDNode*, 4> SetCCs;
6195       if (!N0.hasOneUse())
6196         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6197                                           SetCCs, TLI);
6198       if (DoXform) {
6199         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6200                                          LN0->getChain(), LN0->getBasePtr(),
6201                                          LN0->getMemoryVT(),
6202                                          LN0->getMemOperand());
6203         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6204         Mask = Mask.zext(VT.getSizeInBits());
6205         SDLoc DL(N);
6206         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6207                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6208         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6209                                     SDLoc(N0.getOperand(0)),
6210                                     N0.getOperand(0).getValueType(), ExtLoad);
6211         CombineTo(N, And);
6212         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6213         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6214                         ISD::ZERO_EXTEND);
6215         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6216       }
6217     }
6218   }
6219
6220   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6221   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6222   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6223       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6224     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6225     EVT MemVT = LN0->getMemoryVT();
6226     if ((!LegalOperations && !LN0->isVolatile()) ||
6227         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6228       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6229                                        LN0->getChain(),
6230                                        LN0->getBasePtr(), MemVT,
6231                                        LN0->getMemOperand());
6232       CombineTo(N, ExtLoad);
6233       CombineTo(N0.getNode(),
6234                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6235                             ExtLoad),
6236                 ExtLoad.getValue(1));
6237       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6238     }
6239   }
6240
6241   if (N0.getOpcode() == ISD::SETCC) {
6242     if (!LegalOperations && VT.isVector() &&
6243         N0.getValueType().getVectorElementType() == MVT::i1) {
6244       EVT N0VT = N0.getOperand(0).getValueType();
6245       if (getSetCCResultType(N0VT) == N0.getValueType())
6246         return SDValue();
6247
6248       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6249       // Only do this before legalize for now.
6250       EVT EltVT = VT.getVectorElementType();
6251       SDLoc DL(N);
6252       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6253                                     DAG.getConstant(1, DL, EltVT));
6254       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6255         // We know that the # elements of the results is the same as the
6256         // # elements of the compare (and the # elements of the compare result
6257         // for that matter).  Check to see that they are the same size.  If so,
6258         // we know that the element size of the sext'd result matches the
6259         // element size of the compare operands.
6260         return DAG.getNode(ISD::AND, DL, VT,
6261                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6262                                          N0.getOperand(1),
6263                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6264                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6265                                        OneOps));
6266
6267       // If the desired elements are smaller or larger than the source
6268       // elements we can use a matching integer vector type and then
6269       // truncate/sign extend
6270       EVT MatchingElementType =
6271         EVT::getIntegerVT(*DAG.getContext(),
6272                           N0VT.getScalarType().getSizeInBits());
6273       EVT MatchingVectorType =
6274         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6275                          N0VT.getVectorNumElements());
6276       SDValue VsetCC =
6277         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6278                       N0.getOperand(1),
6279                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6280       return DAG.getNode(ISD::AND, DL, VT,
6281                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6282                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6283     }
6284
6285     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6286     SDLoc DL(N);
6287     SDValue SCC =
6288       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6289                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6290                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6291     if (SCC.getNode()) return SCC;
6292   }
6293
6294   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6295   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6296       isa<ConstantSDNode>(N0.getOperand(1)) &&
6297       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6298       N0.hasOneUse()) {
6299     SDValue ShAmt = N0.getOperand(1);
6300     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6301     if (N0.getOpcode() == ISD::SHL) {
6302       SDValue InnerZExt = N0.getOperand(0);
6303       // If the original shl may be shifting out bits, do not perform this
6304       // transformation.
6305       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6306         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6307       if (ShAmtVal > KnownZeroBits)
6308         return SDValue();
6309     }
6310
6311     SDLoc DL(N);
6312
6313     // Ensure that the shift amount is wide enough for the shifted value.
6314     if (VT.getSizeInBits() >= 256)
6315       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6316
6317     return DAG.getNode(N0.getOpcode(), DL, VT,
6318                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6319                        ShAmt);
6320   }
6321
6322   return SDValue();
6323 }
6324
6325 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6326   SDValue N0 = N->getOperand(0);
6327   EVT VT = N->getValueType(0);
6328
6329   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6330                                               LegalOperations))
6331     return SDValue(Res, 0);
6332
6333   // fold (aext (aext x)) -> (aext x)
6334   // fold (aext (zext x)) -> (zext x)
6335   // fold (aext (sext x)) -> (sext x)
6336   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6337       N0.getOpcode() == ISD::ZERO_EXTEND ||
6338       N0.getOpcode() == ISD::SIGN_EXTEND)
6339     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6340
6341   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6342   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6343   if (N0.getOpcode() == ISD::TRUNCATE) {
6344     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6345     if (NarrowLoad.getNode()) {
6346       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6347       if (NarrowLoad.getNode() != N0.getNode()) {
6348         CombineTo(N0.getNode(), NarrowLoad);
6349         // CombineTo deleted the truncate, if needed, but not what's under it.
6350         AddToWorklist(oye);
6351       }
6352       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6353     }
6354   }
6355
6356   // fold (aext (truncate x))
6357   if (N0.getOpcode() == ISD::TRUNCATE) {
6358     SDValue TruncOp = N0.getOperand(0);
6359     if (TruncOp.getValueType() == VT)
6360       return TruncOp; // x iff x size == zext size.
6361     if (TruncOp.getValueType().bitsGT(VT))
6362       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6363     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6364   }
6365
6366   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6367   // if the trunc is not free.
6368   if (N0.getOpcode() == ISD::AND &&
6369       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6370       N0.getOperand(1).getOpcode() == ISD::Constant &&
6371       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6372                           N0.getValueType())) {
6373     SDValue X = N0.getOperand(0).getOperand(0);
6374     if (X.getValueType().bitsLT(VT)) {
6375       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6376     } else if (X.getValueType().bitsGT(VT)) {
6377       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6378     }
6379     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6380     Mask = Mask.zext(VT.getSizeInBits());
6381     SDLoc DL(N);
6382     return DAG.getNode(ISD::AND, DL, VT,
6383                        X, DAG.getConstant(Mask, DL, VT));
6384   }
6385
6386   // fold (aext (load x)) -> (aext (truncate (extload x)))
6387   // None of the supported targets knows how to perform load and any_ext
6388   // on vectors in one instruction.  We only perform this transformation on
6389   // scalars.
6390   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6391       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6392       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6393     bool DoXform = true;
6394     SmallVector<SDNode*, 4> SetCCs;
6395     if (!N0.hasOneUse())
6396       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6397     if (DoXform) {
6398       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6399       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6400                                        LN0->getChain(),
6401                                        LN0->getBasePtr(), N0.getValueType(),
6402                                        LN0->getMemOperand());
6403       CombineTo(N, ExtLoad);
6404       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6405                                   N0.getValueType(), ExtLoad);
6406       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6407       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6408                       ISD::ANY_EXTEND);
6409       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6410     }
6411   }
6412
6413   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6414   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6415   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6416   if (N0.getOpcode() == ISD::LOAD &&
6417       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6418       N0.hasOneUse()) {
6419     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6420     ISD::LoadExtType ExtType = LN0->getExtensionType();
6421     EVT MemVT = LN0->getMemoryVT();
6422     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6423       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6424                                        VT, LN0->getChain(), LN0->getBasePtr(),
6425                                        MemVT, LN0->getMemOperand());
6426       CombineTo(N, ExtLoad);
6427       CombineTo(N0.getNode(),
6428                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6429                             N0.getValueType(), ExtLoad),
6430                 ExtLoad.getValue(1));
6431       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6432     }
6433   }
6434
6435   if (N0.getOpcode() == ISD::SETCC) {
6436     // For vectors:
6437     // aext(setcc) -> vsetcc
6438     // aext(setcc) -> truncate(vsetcc)
6439     // aext(setcc) -> aext(vsetcc)
6440     // Only do this before legalize for now.
6441     if (VT.isVector() && !LegalOperations) {
6442       EVT N0VT = N0.getOperand(0).getValueType();
6443         // We know that the # elements of the results is the same as the
6444         // # elements of the compare (and the # elements of the compare result
6445         // for that matter).  Check to see that they are the same size.  If so,
6446         // we know that the element size of the sext'd result matches the
6447         // element size of the compare operands.
6448       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6449         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6450                              N0.getOperand(1),
6451                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6452       // If the desired elements are smaller or larger than the source
6453       // elements we can use a matching integer vector type and then
6454       // truncate/any extend
6455       else {
6456         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6457         SDValue VsetCC =
6458           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6459                         N0.getOperand(1),
6460                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6461         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6462       }
6463     }
6464
6465     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6466     SDLoc DL(N);
6467     SDValue SCC =
6468       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6469                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6470                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6471     if (SCC.getNode())
6472       return SCC;
6473   }
6474
6475   return SDValue();
6476 }
6477
6478 /// See if the specified operand can be simplified with the knowledge that only
6479 /// the bits specified by Mask are used.  If so, return the simpler operand,
6480 /// otherwise return a null SDValue.
6481 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6482   switch (V.getOpcode()) {
6483   default: break;
6484   case ISD::Constant: {
6485     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6486     assert(CV && "Const value should be ConstSDNode.");
6487     const APInt &CVal = CV->getAPIntValue();
6488     APInt NewVal = CVal & Mask;
6489     if (NewVal != CVal)
6490       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6491     break;
6492   }
6493   case ISD::OR:
6494   case ISD::XOR:
6495     // If the LHS or RHS don't contribute bits to the or, drop them.
6496     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6497       return V.getOperand(1);
6498     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6499       return V.getOperand(0);
6500     break;
6501   case ISD::SRL:
6502     // Only look at single-use SRLs.
6503     if (!V.getNode()->hasOneUse())
6504       break;
6505     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6506       // See if we can recursively simplify the LHS.
6507       unsigned Amt = RHSC->getZExtValue();
6508
6509       // Watch out for shift count overflow though.
6510       if (Amt >= Mask.getBitWidth()) break;
6511       APInt NewMask = Mask << Amt;
6512       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6513       if (SimplifyLHS.getNode())
6514         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6515                            SimplifyLHS, V.getOperand(1));
6516     }
6517   }
6518   return SDValue();
6519 }
6520
6521 /// If the result of a wider load is shifted to right of N  bits and then
6522 /// truncated to a narrower type and where N is a multiple of number of bits of
6523 /// the narrower type, transform it to a narrower load from address + N / num of
6524 /// bits of new type. If the result is to be extended, also fold the extension
6525 /// to form a extending load.
6526 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6527   unsigned Opc = N->getOpcode();
6528
6529   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6530   SDValue N0 = N->getOperand(0);
6531   EVT VT = N->getValueType(0);
6532   EVT ExtVT = VT;
6533
6534   // This transformation isn't valid for vector loads.
6535   if (VT.isVector())
6536     return SDValue();
6537
6538   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6539   // extended to VT.
6540   if (Opc == ISD::SIGN_EXTEND_INREG) {
6541     ExtType = ISD::SEXTLOAD;
6542     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6543   } else if (Opc == ISD::SRL) {
6544     // Another special-case: SRL is basically zero-extending a narrower value.
6545     ExtType = ISD::ZEXTLOAD;
6546     N0 = SDValue(N, 0);
6547     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6548     if (!N01) return SDValue();
6549     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6550                               VT.getSizeInBits() - N01->getZExtValue());
6551   }
6552   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6553     return SDValue();
6554
6555   unsigned EVTBits = ExtVT.getSizeInBits();
6556
6557   // Do not generate loads of non-round integer types since these can
6558   // be expensive (and would be wrong if the type is not byte sized).
6559   if (!ExtVT.isRound())
6560     return SDValue();
6561
6562   unsigned ShAmt = 0;
6563   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6564     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6565       ShAmt = N01->getZExtValue();
6566       // Is the shift amount a multiple of size of VT?
6567       if ((ShAmt & (EVTBits-1)) == 0) {
6568         N0 = N0.getOperand(0);
6569         // Is the load width a multiple of size of VT?
6570         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6571           return SDValue();
6572       }
6573
6574       // At this point, we must have a load or else we can't do the transform.
6575       if (!isa<LoadSDNode>(N0)) return SDValue();
6576
6577       // Because a SRL must be assumed to *need* to zero-extend the high bits
6578       // (as opposed to anyext the high bits), we can't combine the zextload
6579       // lowering of SRL and an sextload.
6580       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6581         return SDValue();
6582
6583       // If the shift amount is larger than the input type then we're not
6584       // accessing any of the loaded bytes.  If the load was a zextload/extload
6585       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6586       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6587         return SDValue();
6588     }
6589   }
6590
6591   // If the load is shifted left (and the result isn't shifted back right),
6592   // we can fold the truncate through the shift.
6593   unsigned ShLeftAmt = 0;
6594   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6595       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6596     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6597       ShLeftAmt = N01->getZExtValue();
6598       N0 = N0.getOperand(0);
6599     }
6600   }
6601
6602   // If we haven't found a load, we can't narrow it.  Don't transform one with
6603   // multiple uses, this would require adding a new load.
6604   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6605     return SDValue();
6606
6607   // Don't change the width of a volatile load.
6608   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6609   if (LN0->isVolatile())
6610     return SDValue();
6611
6612   // Verify that we are actually reducing a load width here.
6613   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6614     return SDValue();
6615
6616   // For the transform to be legal, the load must produce only two values
6617   // (the value loaded and the chain).  Don't transform a pre-increment
6618   // load, for example, which produces an extra value.  Otherwise the
6619   // transformation is not equivalent, and the downstream logic to replace
6620   // uses gets things wrong.
6621   if (LN0->getNumValues() > 2)
6622     return SDValue();
6623
6624   // If the load that we're shrinking is an extload and we're not just
6625   // discarding the extension we can't simply shrink the load. Bail.
6626   // TODO: It would be possible to merge the extensions in some cases.
6627   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6628       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6629     return SDValue();
6630
6631   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6632     return SDValue();
6633
6634   EVT PtrType = N0.getOperand(1).getValueType();
6635
6636   if (PtrType == MVT::Untyped || PtrType.isExtended())
6637     // It's not possible to generate a constant of extended or untyped type.
6638     return SDValue();
6639
6640   // For big endian targets, we need to adjust the offset to the pointer to
6641   // load the correct bytes.
6642   if (TLI.isBigEndian()) {
6643     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6644     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6645     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6646   }
6647
6648   uint64_t PtrOff = ShAmt / 8;
6649   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6650   SDLoc DL(LN0);
6651   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6652                                PtrType, LN0->getBasePtr(),
6653                                DAG.getConstant(PtrOff, DL, PtrType));
6654   AddToWorklist(NewPtr.getNode());
6655
6656   SDValue Load;
6657   if (ExtType == ISD::NON_EXTLOAD)
6658     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6659                         LN0->getPointerInfo().getWithOffset(PtrOff),
6660                         LN0->isVolatile(), LN0->isNonTemporal(),
6661                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6662   else
6663     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6664                           LN0->getPointerInfo().getWithOffset(PtrOff),
6665                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6666                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6667
6668   // Replace the old load's chain with the new load's chain.
6669   WorklistRemover DeadNodes(*this);
6670   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6671
6672   // Shift the result left, if we've swallowed a left shift.
6673   SDValue Result = Load;
6674   if (ShLeftAmt != 0) {
6675     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6676     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6677       ShImmTy = VT;
6678     // If the shift amount is as large as the result size (but, presumably,
6679     // no larger than the source) then the useful bits of the result are
6680     // zero; we can't simply return the shortened shift, because the result
6681     // of that operation is undefined.
6682     SDLoc DL(N0);
6683     if (ShLeftAmt >= VT.getSizeInBits())
6684       Result = DAG.getConstant(0, DL, VT);
6685     else
6686       Result = DAG.getNode(ISD::SHL, DL, VT,
6687                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6688   }
6689
6690   // Return the new loaded value.
6691   return Result;
6692 }
6693
6694 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6695   SDValue N0 = N->getOperand(0);
6696   SDValue N1 = N->getOperand(1);
6697   EVT VT = N->getValueType(0);
6698   EVT EVT = cast<VTSDNode>(N1)->getVT();
6699   unsigned VTBits = VT.getScalarType().getSizeInBits();
6700   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6701
6702   // fold (sext_in_reg c1) -> c1
6703   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6704     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6705
6706   // If the input is already sign extended, just drop the extension.
6707   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6708     return N0;
6709
6710   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6711   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6712       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6713     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6714                        N0.getOperand(0), N1);
6715
6716   // fold (sext_in_reg (sext x)) -> (sext x)
6717   // fold (sext_in_reg (aext x)) -> (sext x)
6718   // if x is small enough.
6719   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6720     SDValue N00 = N0.getOperand(0);
6721     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6722         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6723       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6724   }
6725
6726   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6727   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6728     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6729
6730   // fold operands of sext_in_reg based on knowledge that the top bits are not
6731   // demanded.
6732   if (SimplifyDemandedBits(SDValue(N, 0)))
6733     return SDValue(N, 0);
6734
6735   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6736   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6737   SDValue NarrowLoad = ReduceLoadWidth(N);
6738   if (NarrowLoad.getNode())
6739     return NarrowLoad;
6740
6741   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6742   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6743   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6744   if (N0.getOpcode() == ISD::SRL) {
6745     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6746       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6747         // We can turn this into an SRA iff the input to the SRL is already sign
6748         // extended enough.
6749         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6750         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6751           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6752                              N0.getOperand(0), N0.getOperand(1));
6753       }
6754   }
6755
6756   // fold (sext_inreg (extload x)) -> (sextload x)
6757   if (ISD::isEXTLoad(N0.getNode()) &&
6758       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6759       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6760       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6761        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6762     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6763     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6764                                      LN0->getChain(),
6765                                      LN0->getBasePtr(), EVT,
6766                                      LN0->getMemOperand());
6767     CombineTo(N, ExtLoad);
6768     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6769     AddToWorklist(ExtLoad.getNode());
6770     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6771   }
6772   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6773   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6774       N0.hasOneUse() &&
6775       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6776       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6777        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6778     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6779     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6780                                      LN0->getChain(),
6781                                      LN0->getBasePtr(), EVT,
6782                                      LN0->getMemOperand());
6783     CombineTo(N, ExtLoad);
6784     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6785     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6786   }
6787
6788   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6789   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6790     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6791                                        N0.getOperand(1), false);
6792     if (BSwap.getNode())
6793       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6794                          BSwap, N1);
6795   }
6796
6797   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6798   // into a build_vector.
6799   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6800     SmallVector<SDValue, 8> Elts;
6801     unsigned NumElts = N0->getNumOperands();
6802     unsigned ShAmt = VTBits - EVTBits;
6803
6804     for (unsigned i = 0; i != NumElts; ++i) {
6805       SDValue Op = N0->getOperand(i);
6806       if (Op->getOpcode() == ISD::UNDEF) {
6807         Elts.push_back(Op);
6808         continue;
6809       }
6810
6811       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6812       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6813       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6814                                      SDLoc(Op), Op.getValueType()));
6815     }
6816
6817     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6818   }
6819
6820   return SDValue();
6821 }
6822
6823 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6824   SDValue N0 = N->getOperand(0);
6825   EVT VT = N->getValueType(0);
6826
6827   if (N0.getOpcode() == ISD::UNDEF)
6828     return DAG.getUNDEF(VT);
6829
6830   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6831                                               LegalOperations))
6832     return SDValue(Res, 0);
6833
6834   return SDValue();
6835 }
6836
6837 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6838   SDValue N0 = N->getOperand(0);
6839   EVT VT = N->getValueType(0);
6840   bool isLE = TLI.isLittleEndian();
6841
6842   // noop truncate
6843   if (N0.getValueType() == N->getValueType(0))
6844     return N0;
6845   // fold (truncate c1) -> c1
6846   if (isConstantIntBuildVectorOrConstantInt(N0))
6847     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6848   // fold (truncate (truncate x)) -> (truncate x)
6849   if (N0.getOpcode() == ISD::TRUNCATE)
6850     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6851   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6852   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6853       N0.getOpcode() == ISD::SIGN_EXTEND ||
6854       N0.getOpcode() == ISD::ANY_EXTEND) {
6855     if (N0.getOperand(0).getValueType().bitsLT(VT))
6856       // if the source is smaller than the dest, we still need an extend
6857       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6858                          N0.getOperand(0));
6859     if (N0.getOperand(0).getValueType().bitsGT(VT))
6860       // if the source is larger than the dest, than we just need the truncate
6861       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6862     // if the source and dest are the same type, we can drop both the extend
6863     // and the truncate.
6864     return N0.getOperand(0);
6865   }
6866
6867   // Fold extract-and-trunc into a narrow extract. For example:
6868   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6869   //   i32 y = TRUNCATE(i64 x)
6870   //        -- becomes --
6871   //   v16i8 b = BITCAST (v2i64 val)
6872   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6873   //
6874   // Note: We only run this optimization after type legalization (which often
6875   // creates this pattern) and before operation legalization after which
6876   // we need to be more careful about the vector instructions that we generate.
6877   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6878       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6879
6880     EVT VecTy = N0.getOperand(0).getValueType();
6881     EVT ExTy = N0.getValueType();
6882     EVT TrTy = N->getValueType(0);
6883
6884     unsigned NumElem = VecTy.getVectorNumElements();
6885     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6886
6887     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6888     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6889
6890     SDValue EltNo = N0->getOperand(1);
6891     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6892       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6893       EVT IndexTy = TLI.getVectorIdxTy();
6894       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6895
6896       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6897                               NVT, N0.getOperand(0));
6898
6899       SDLoc DL(N);
6900       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6901                          DL, TrTy, V,
6902                          DAG.getConstant(Index, DL, IndexTy));
6903     }
6904   }
6905
6906   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6907   if (N0.getOpcode() == ISD::SELECT) {
6908     EVT SrcVT = N0.getValueType();
6909     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6910         TLI.isTruncateFree(SrcVT, VT)) {
6911       SDLoc SL(N0);
6912       SDValue Cond = N0.getOperand(0);
6913       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6914       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6915       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6916     }
6917   }
6918
6919   // Fold a series of buildvector, bitcast, and truncate if possible.
6920   // For example fold
6921   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6922   //   (2xi32 (buildvector x, y)).
6923   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6924       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6925       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6926       N0.getOperand(0).hasOneUse()) {
6927
6928     SDValue BuildVect = N0.getOperand(0);
6929     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6930     EVT TruncVecEltTy = VT.getVectorElementType();
6931
6932     // Check that the element types match.
6933     if (BuildVectEltTy == TruncVecEltTy) {
6934       // Now we only need to compute the offset of the truncated elements.
6935       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6936       unsigned TruncVecNumElts = VT.getVectorNumElements();
6937       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6938
6939       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6940              "Invalid number of elements");
6941
6942       SmallVector<SDValue, 8> Opnds;
6943       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6944         Opnds.push_back(BuildVect.getOperand(i));
6945
6946       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6947     }
6948   }
6949
6950   // See if we can simplify the input to this truncate through knowledge that
6951   // only the low bits are being used.
6952   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6953   // Currently we only perform this optimization on scalars because vectors
6954   // may have different active low bits.
6955   if (!VT.isVector()) {
6956     SDValue Shorter =
6957       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6958                                                VT.getSizeInBits()));
6959     if (Shorter.getNode())
6960       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6961   }
6962   // fold (truncate (load x)) -> (smaller load x)
6963   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6964   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6965     SDValue Reduced = ReduceLoadWidth(N);
6966     if (Reduced.getNode())
6967       return Reduced;
6968     // Handle the case where the load remains an extending load even
6969     // after truncation.
6970     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6971       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6972       if (!LN0->isVolatile() &&
6973           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6974         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6975                                          VT, LN0->getChain(), LN0->getBasePtr(),
6976                                          LN0->getMemoryVT(),
6977                                          LN0->getMemOperand());
6978         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6979         return NewLoad;
6980       }
6981     }
6982   }
6983   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6984   // where ... are all 'undef'.
6985   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6986     SmallVector<EVT, 8> VTs;
6987     SDValue V;
6988     unsigned Idx = 0;
6989     unsigned NumDefs = 0;
6990
6991     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6992       SDValue X = N0.getOperand(i);
6993       if (X.getOpcode() != ISD::UNDEF) {
6994         V = X;
6995         Idx = i;
6996         NumDefs++;
6997       }
6998       // Stop if more than one members are non-undef.
6999       if (NumDefs > 1)
7000         break;
7001       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7002                                      VT.getVectorElementType(),
7003                                      X.getValueType().getVectorNumElements()));
7004     }
7005
7006     if (NumDefs == 0)
7007       return DAG.getUNDEF(VT);
7008
7009     if (NumDefs == 1) {
7010       assert(V.getNode() && "The single defined operand is empty!");
7011       SmallVector<SDValue, 8> Opnds;
7012       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7013         if (i != Idx) {
7014           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7015           continue;
7016         }
7017         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7018         AddToWorklist(NV.getNode());
7019         Opnds.push_back(NV);
7020       }
7021       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7022     }
7023   }
7024
7025   // Simplify the operands using demanded-bits information.
7026   if (!VT.isVector() &&
7027       SimplifyDemandedBits(SDValue(N, 0)))
7028     return SDValue(N, 0);
7029
7030   return SDValue();
7031 }
7032
7033 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7034   SDValue Elt = N->getOperand(i);
7035   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7036     return Elt.getNode();
7037   return Elt.getOperand(Elt.getResNo()).getNode();
7038 }
7039
7040 /// build_pair (load, load) -> load
7041 /// if load locations are consecutive.
7042 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7043   assert(N->getOpcode() == ISD::BUILD_PAIR);
7044
7045   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7046   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7047   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7048       LD1->getAddressSpace() != LD2->getAddressSpace())
7049     return SDValue();
7050   EVT LD1VT = LD1->getValueType(0);
7051
7052   if (ISD::isNON_EXTLoad(LD2) &&
7053       LD2->hasOneUse() &&
7054       // If both are volatile this would reduce the number of volatile loads.
7055       // If one is volatile it might be ok, but play conservative and bail out.
7056       !LD1->isVolatile() &&
7057       !LD2->isVolatile() &&
7058       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7059     unsigned Align = LD1->getAlignment();
7060     unsigned NewAlign = TLI.getDataLayout()->
7061       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7062
7063     if (NewAlign <= Align &&
7064         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7065       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7066                          LD1->getBasePtr(), LD1->getPointerInfo(),
7067                          false, false, false, Align);
7068   }
7069
7070   return SDValue();
7071 }
7072
7073 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7074   SDValue N0 = N->getOperand(0);
7075   EVT VT = N->getValueType(0);
7076
7077   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7078   // Only do this before legalize, since afterward the target may be depending
7079   // on the bitconvert.
7080   // First check to see if this is all constant.
7081   if (!LegalTypes &&
7082       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7083       VT.isVector()) {
7084     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7085
7086     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7087     assert(!DestEltVT.isVector() &&
7088            "Element type of vector ValueType must not be vector!");
7089     if (isSimple)
7090       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7091   }
7092
7093   // If the input is a constant, let getNode fold it.
7094   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7095     // If we can't allow illegal operations, we need to check that this is just
7096     // a fp -> int or int -> conversion and that the resulting operation will
7097     // be legal.
7098     if (!LegalOperations ||
7099         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7100          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7101         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7102          TLI.isOperationLegal(ISD::Constant, VT)))
7103       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7104   }
7105
7106   // (conv (conv x, t1), t2) -> (conv x, t2)
7107   if (N0.getOpcode() == ISD::BITCAST)
7108     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7109                        N0.getOperand(0));
7110
7111   // fold (conv (load x)) -> (load (conv*)x)
7112   // If the resultant load doesn't need a higher alignment than the original!
7113   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7114       // Do not change the width of a volatile load.
7115       !cast<LoadSDNode>(N0)->isVolatile() &&
7116       // Do not remove the cast if the types differ in endian layout.
7117       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7118       TLI.hasBigEndianPartOrdering(VT) &&
7119       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7120       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7121     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7122     unsigned Align = TLI.getDataLayout()->
7123       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7124     unsigned OrigAlign = LN0->getAlignment();
7125
7126     if (Align <= OrigAlign) {
7127       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7128                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7129                                  LN0->isVolatile(), LN0->isNonTemporal(),
7130                                  LN0->isInvariant(), OrigAlign,
7131                                  LN0->getAAInfo());
7132       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7133       return Load;
7134     }
7135   }
7136
7137   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7138   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7139   // This often reduces constant pool loads.
7140   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7141        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7142       N0.getNode()->hasOneUse() && VT.isInteger() &&
7143       !VT.isVector() && !N0.getValueType().isVector()) {
7144     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7145                                   N0.getOperand(0));
7146     AddToWorklist(NewConv.getNode());
7147
7148     SDLoc DL(N);
7149     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7150     if (N0.getOpcode() == ISD::FNEG)
7151       return DAG.getNode(ISD::XOR, DL, VT,
7152                          NewConv, DAG.getConstant(SignBit, DL, VT));
7153     assert(N0.getOpcode() == ISD::FABS);
7154     return DAG.getNode(ISD::AND, DL, VT,
7155                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7156   }
7157
7158   // fold (bitconvert (fcopysign cst, x)) ->
7159   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7160   // Note that we don't handle (copysign x, cst) because this can always be
7161   // folded to an fneg or fabs.
7162   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7163       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7164       VT.isInteger() && !VT.isVector()) {
7165     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7166     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7167     if (isTypeLegal(IntXVT)) {
7168       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7169                               IntXVT, N0.getOperand(1));
7170       AddToWorklist(X.getNode());
7171
7172       // If X has a different width than the result/lhs, sext it or truncate it.
7173       unsigned VTWidth = VT.getSizeInBits();
7174       if (OrigXWidth < VTWidth) {
7175         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7176         AddToWorklist(X.getNode());
7177       } else if (OrigXWidth > VTWidth) {
7178         // To get the sign bit in the right place, we have to shift it right
7179         // before truncating.
7180         SDLoc DL(X);
7181         X = DAG.getNode(ISD::SRL, DL,
7182                         X.getValueType(), X,
7183                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7184                                         X.getValueType()));
7185         AddToWorklist(X.getNode());
7186         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7187         AddToWorklist(X.getNode());
7188       }
7189
7190       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7191       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7192                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7193       AddToWorklist(X.getNode());
7194
7195       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7196                                 VT, N0.getOperand(0));
7197       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7198                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7199       AddToWorklist(Cst.getNode());
7200
7201       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7202     }
7203   }
7204
7205   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7206   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7207     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7208     if (CombineLD.getNode())
7209       return CombineLD;
7210   }
7211
7212   // Remove double bitcasts from shuffles - this is often a legacy of
7213   // XformToShuffleWithZero being used to combine bitmaskings (of
7214   // float vectors bitcast to integer vectors) into shuffles.
7215   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7216   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7217       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7218       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7219       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7220     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7221
7222     // If operands are a bitcast, peek through if it casts the original VT.
7223     // If operands are a UNDEF or constant, just bitcast back to original VT.
7224     auto PeekThroughBitcast = [&](SDValue Op) {
7225       if (Op.getOpcode() == ISD::BITCAST &&
7226           Op.getOperand(0)->getValueType(0) == VT)
7227         return SDValue(Op.getOperand(0));
7228       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7229           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7230         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7231       return SDValue();
7232     };
7233
7234     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7235     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7236     if (!(SV0 && SV1))
7237       return SDValue();
7238
7239     int MaskScale =
7240         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7241     SmallVector<int, 8> NewMask;
7242     for (int M : SVN->getMask())
7243       for (int i = 0; i != MaskScale; ++i)
7244         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7245
7246     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7247     if (!LegalMask) {
7248       std::swap(SV0, SV1);
7249       ShuffleVectorSDNode::commuteMask(NewMask);
7250       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7251     }
7252
7253     if (LegalMask)
7254       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7255   }
7256
7257   return SDValue();
7258 }
7259
7260 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7261   EVT VT = N->getValueType(0);
7262   return CombineConsecutiveLoads(N, VT);
7263 }
7264
7265 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7266 /// operands. DstEltVT indicates the destination element value type.
7267 SDValue DAGCombiner::
7268 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7269   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7270
7271   // If this is already the right type, we're done.
7272   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7273
7274   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7275   unsigned DstBitSize = DstEltVT.getSizeInBits();
7276
7277   // If this is a conversion of N elements of one type to N elements of another
7278   // type, convert each element.  This handles FP<->INT cases.
7279   if (SrcBitSize == DstBitSize) {
7280     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7281                               BV->getValueType(0).getVectorNumElements());
7282
7283     // Due to the FP element handling below calling this routine recursively,
7284     // we can end up with a scalar-to-vector node here.
7285     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7286       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7287                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7288                                      DstEltVT, BV->getOperand(0)));
7289
7290     SmallVector<SDValue, 8> Ops;
7291     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7292       SDValue Op = BV->getOperand(i);
7293       // If the vector element type is not legal, the BUILD_VECTOR operands
7294       // are promoted and implicitly truncated.  Make that explicit here.
7295       if (Op.getValueType() != SrcEltVT)
7296         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7297       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7298                                 DstEltVT, Op));
7299       AddToWorklist(Ops.back().getNode());
7300     }
7301     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7302   }
7303
7304   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7305   // handle annoying details of growing/shrinking FP values, we convert them to
7306   // int first.
7307   if (SrcEltVT.isFloatingPoint()) {
7308     // Convert the input float vector to a int vector where the elements are the
7309     // same sizes.
7310     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7311     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7312     SrcEltVT = IntVT;
7313   }
7314
7315   // Now we know the input is an integer vector.  If the output is a FP type,
7316   // convert to integer first, then to FP of the right size.
7317   if (DstEltVT.isFloatingPoint()) {
7318     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7319     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7320
7321     // Next, convert to FP elements of the same size.
7322     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7323   }
7324
7325   SDLoc DL(BV);
7326
7327   // Okay, we know the src/dst types are both integers of differing types.
7328   // Handling growing first.
7329   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7330   if (SrcBitSize < DstBitSize) {
7331     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7332
7333     SmallVector<SDValue, 8> Ops;
7334     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7335          i += NumInputsPerOutput) {
7336       bool isLE = TLI.isLittleEndian();
7337       APInt NewBits = APInt(DstBitSize, 0);
7338       bool EltIsUndef = true;
7339       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7340         // Shift the previously computed bits over.
7341         NewBits <<= SrcBitSize;
7342         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7343         if (Op.getOpcode() == ISD::UNDEF) continue;
7344         EltIsUndef = false;
7345
7346         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7347                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7348       }
7349
7350       if (EltIsUndef)
7351         Ops.push_back(DAG.getUNDEF(DstEltVT));
7352       else
7353         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7354     }
7355
7356     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7357     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7358   }
7359
7360   // Finally, this must be the case where we are shrinking elements: each input
7361   // turns into multiple outputs.
7362   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7363   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7364                             NumOutputsPerInput*BV->getNumOperands());
7365   SmallVector<SDValue, 8> Ops;
7366
7367   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7368     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7369       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7370       continue;
7371     }
7372
7373     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7374                   getAPIntValue().zextOrTrunc(SrcBitSize);
7375
7376     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7377       APInt ThisVal = OpVal.trunc(DstBitSize);
7378       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7379       OpVal = OpVal.lshr(DstBitSize);
7380     }
7381
7382     // For big endian targets, swap the order of the pieces of each element.
7383     if (TLI.isBigEndian())
7384       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7385   }
7386
7387   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7388 }
7389
7390 /// Try to perform FMA combining on a given FADD node.
7391 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7392   SDValue N0 = N->getOperand(0);
7393   SDValue N1 = N->getOperand(1);
7394   EVT VT = N->getValueType(0);
7395   SDLoc SL(N);
7396
7397   const TargetOptions &Options = DAG.getTarget().Options;
7398   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7399                        Options.UnsafeFPMath);
7400
7401   // Floating-point multiply-add with intermediate rounding.
7402   bool HasFMAD = (LegalOperations &&
7403                   TLI.isOperationLegal(ISD::FMAD, VT));
7404
7405   // Floating-point multiply-add without intermediate rounding.
7406   bool HasFMA = ((!LegalOperations ||
7407                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7408                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7409                  UnsafeFPMath);
7410
7411   // No valid opcode, do not combine.
7412   if (!HasFMAD && !HasFMA)
7413     return SDValue();
7414
7415   // Always prefer FMAD to FMA for precision.
7416   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7417   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7418   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7419
7420   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7421   if (N0.getOpcode() == ISD::FMUL &&
7422       (Aggressive || N0->hasOneUse())) {
7423     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7424                        N0.getOperand(0), N0.getOperand(1), N1);
7425   }
7426
7427   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7428   // Note: Commutes FADD operands.
7429   if (N1.getOpcode() == ISD::FMUL &&
7430       (Aggressive || N1->hasOneUse())) {
7431     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7432                        N1.getOperand(0), N1.getOperand(1), N0);
7433   }
7434
7435   // Look through FP_EXTEND nodes to do more combining.
7436   if (UnsafeFPMath && LookThroughFPExt) {
7437     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7438     if (N0.getOpcode() == ISD::FP_EXTEND) {
7439       SDValue N00 = N0.getOperand(0);
7440       if (N00.getOpcode() == ISD::FMUL)
7441         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7442                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7443                                        N00.getOperand(0)),
7444                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7445                                        N00.getOperand(1)), N1);
7446     }
7447
7448     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7449     // Note: Commutes FADD operands.
7450     if (N1.getOpcode() == ISD::FP_EXTEND) {
7451       SDValue N10 = N1.getOperand(0);
7452       if (N10.getOpcode() == ISD::FMUL)
7453         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7454                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7455                                        N10.getOperand(0)),
7456                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7457                                        N10.getOperand(1)), N0);
7458     }
7459   }
7460
7461   // More folding opportunities when target permits.
7462   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7463     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7464     if (N0.getOpcode() == PreferredFusedOpcode &&
7465         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7466       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7467                          N0.getOperand(0), N0.getOperand(1),
7468                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7469                                      N0.getOperand(2).getOperand(0),
7470                                      N0.getOperand(2).getOperand(1),
7471                                      N1));
7472     }
7473
7474     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7475     if (N1->getOpcode() == PreferredFusedOpcode &&
7476         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7477       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7478                          N1.getOperand(0), N1.getOperand(1),
7479                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7480                                      N1.getOperand(2).getOperand(0),
7481                                      N1.getOperand(2).getOperand(1),
7482                                      N0));
7483     }
7484
7485     if (UnsafeFPMath && LookThroughFPExt) {
7486       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7487       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7488       auto FoldFAddFMAFPExtFMul = [&] (
7489           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7490         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7491                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7492                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7493                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7494                                        Z));
7495       };
7496       if (N0.getOpcode() == PreferredFusedOpcode) {
7497         SDValue N02 = N0.getOperand(2);
7498         if (N02.getOpcode() == ISD::FP_EXTEND) {
7499           SDValue N020 = N02.getOperand(0);
7500           if (N020.getOpcode() == ISD::FMUL)
7501             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7502                                         N020.getOperand(0), N020.getOperand(1),
7503                                         N1);
7504         }
7505       }
7506
7507       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7508       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7509       // FIXME: This turns two single-precision and one double-precision
7510       // operation into two double-precision operations, which might not be
7511       // interesting for all targets, especially GPUs.
7512       auto FoldFAddFPExtFMAFMul = [&] (
7513           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7514         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7515                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7516                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7517                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7518                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7519                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7520                                        Z));
7521       };
7522       if (N0.getOpcode() == ISD::FP_EXTEND) {
7523         SDValue N00 = N0.getOperand(0);
7524         if (N00.getOpcode() == PreferredFusedOpcode) {
7525           SDValue N002 = N00.getOperand(2);
7526           if (N002.getOpcode() == ISD::FMUL)
7527             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7528                                         N002.getOperand(0), N002.getOperand(1),
7529                                         N1);
7530         }
7531       }
7532
7533       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7534       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7535       if (N1.getOpcode() == PreferredFusedOpcode) {
7536         SDValue N12 = N1.getOperand(2);
7537         if (N12.getOpcode() == ISD::FP_EXTEND) {
7538           SDValue N120 = N12.getOperand(0);
7539           if (N120.getOpcode() == ISD::FMUL)
7540             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7541                                         N120.getOperand(0), N120.getOperand(1),
7542                                         N0);
7543         }
7544       }
7545
7546       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7547       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7548       // FIXME: This turns two single-precision and one double-precision
7549       // operation into two double-precision operations, which might not be
7550       // interesting for all targets, especially GPUs.
7551       if (N1.getOpcode() == ISD::FP_EXTEND) {
7552         SDValue N10 = N1.getOperand(0);
7553         if (N10.getOpcode() == PreferredFusedOpcode) {
7554           SDValue N102 = N10.getOperand(2);
7555           if (N102.getOpcode() == ISD::FMUL)
7556             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7557                                         N102.getOperand(0), N102.getOperand(1),
7558                                         N0);
7559         }
7560       }
7561     }
7562   }
7563
7564   return SDValue();
7565 }
7566
7567 /// Try to perform FMA combining on a given FSUB node.
7568 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7569   SDValue N0 = N->getOperand(0);
7570   SDValue N1 = N->getOperand(1);
7571   EVT VT = N->getValueType(0);
7572   SDLoc SL(N);
7573
7574   const TargetOptions &Options = DAG.getTarget().Options;
7575   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7576                        Options.UnsafeFPMath);
7577
7578   // Floating-point multiply-add with intermediate rounding.
7579   bool HasFMAD = (LegalOperations &&
7580                   TLI.isOperationLegal(ISD::FMAD, VT));
7581
7582   // Floating-point multiply-add without intermediate rounding.
7583   bool HasFMA = ((!LegalOperations ||
7584                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7585                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7586                  UnsafeFPMath);
7587
7588   // No valid opcode, do not combine.
7589   if (!HasFMAD && !HasFMA)
7590     return SDValue();
7591
7592   // Always prefer FMAD to FMA for precision.
7593   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7594   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7595   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7596
7597   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7598   if (N0.getOpcode() == ISD::FMUL &&
7599       (Aggressive || N0->hasOneUse())) {
7600     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7601                        N0.getOperand(0), N0.getOperand(1),
7602                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7603   }
7604
7605   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7606   // Note: Commutes FSUB operands.
7607   if (N1.getOpcode() == ISD::FMUL &&
7608       (Aggressive || N1->hasOneUse()))
7609     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7610                        DAG.getNode(ISD::FNEG, SL, VT,
7611                                    N1.getOperand(0)),
7612                        N1.getOperand(1), N0);
7613
7614   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7615   if (N0.getOpcode() == ISD::FNEG &&
7616       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7617       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7618     SDValue N00 = N0.getOperand(0).getOperand(0);
7619     SDValue N01 = N0.getOperand(0).getOperand(1);
7620     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7621                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7622                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7623   }
7624
7625   // Look through FP_EXTEND nodes to do more combining.
7626   if (UnsafeFPMath && LookThroughFPExt) {
7627     // fold (fsub (fpext (fmul x, y)), z)
7628     //   -> (fma (fpext x), (fpext y), (fneg z))
7629     if (N0.getOpcode() == ISD::FP_EXTEND) {
7630       SDValue N00 = N0.getOperand(0);
7631       if (N00.getOpcode() == ISD::FMUL)
7632         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7633                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7634                                        N00.getOperand(0)),
7635                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7636                                        N00.getOperand(1)),
7637                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7638     }
7639
7640     // fold (fsub x, (fpext (fmul y, z)))
7641     //   -> (fma (fneg (fpext y)), (fpext z), x)
7642     // Note: Commutes FSUB operands.
7643     if (N1.getOpcode() == ISD::FP_EXTEND) {
7644       SDValue N10 = N1.getOperand(0);
7645       if (N10.getOpcode() == ISD::FMUL)
7646         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7647                            DAG.getNode(ISD::FNEG, SL, VT,
7648                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7649                                                    N10.getOperand(0))),
7650                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7651                                        N10.getOperand(1)),
7652                            N0);
7653     }
7654
7655     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7656     //   -> (fneg (fma (fpext x), (fpext y), z))
7657     // Note: This could be removed with appropriate canonicalization of the
7658     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7659     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7660     // from implementing the canonicalization in visitFSUB.
7661     if (N0.getOpcode() == ISD::FP_EXTEND) {
7662       SDValue N00 = N0.getOperand(0);
7663       if (N00.getOpcode() == ISD::FNEG) {
7664         SDValue N000 = N00.getOperand(0);
7665         if (N000.getOpcode() == ISD::FMUL) {
7666           return DAG.getNode(ISD::FNEG, SL, VT,
7667                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7668                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7669                                                      N000.getOperand(0)),
7670                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7671                                                      N000.getOperand(1)),
7672                                          N1));
7673         }
7674       }
7675     }
7676
7677     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7678     //   -> (fneg (fma (fpext x)), (fpext y), z)
7679     // Note: This could be removed with appropriate canonicalization of the
7680     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7681     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7682     // from implementing the canonicalization in visitFSUB.
7683     if (N0.getOpcode() == ISD::FNEG) {
7684       SDValue N00 = N0.getOperand(0);
7685       if (N00.getOpcode() == ISD::FP_EXTEND) {
7686         SDValue N000 = N00.getOperand(0);
7687         if (N000.getOpcode() == ISD::FMUL) {
7688           return DAG.getNode(ISD::FNEG, SL, VT,
7689                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7690                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7691                                                      N000.getOperand(0)),
7692                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7693                                                      N000.getOperand(1)),
7694                                          N1));
7695         }
7696       }
7697     }
7698
7699   }
7700
7701   // More folding opportunities when target permits.
7702   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7703     // fold (fsub (fma x, y, (fmul u, v)), z)
7704     //   -> (fma x, y (fma u, v, (fneg z)))
7705     if (N0.getOpcode() == PreferredFusedOpcode &&
7706         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7707       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7708                          N0.getOperand(0), N0.getOperand(1),
7709                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7710                                      N0.getOperand(2).getOperand(0),
7711                                      N0.getOperand(2).getOperand(1),
7712                                      DAG.getNode(ISD::FNEG, SL, VT,
7713                                                  N1)));
7714     }
7715
7716     // fold (fsub x, (fma y, z, (fmul u, v)))
7717     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7718     if (N1.getOpcode() == PreferredFusedOpcode &&
7719         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7720       SDValue N20 = N1.getOperand(2).getOperand(0);
7721       SDValue N21 = N1.getOperand(2).getOperand(1);
7722       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7723                          DAG.getNode(ISD::FNEG, SL, VT,
7724                                      N1.getOperand(0)),
7725                          N1.getOperand(1),
7726                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7727                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7728
7729                                      N21, N0));
7730     }
7731
7732     if (UnsafeFPMath && LookThroughFPExt) {
7733       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7734       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7735       if (N0.getOpcode() == PreferredFusedOpcode) {
7736         SDValue N02 = N0.getOperand(2);
7737         if (N02.getOpcode() == ISD::FP_EXTEND) {
7738           SDValue N020 = N02.getOperand(0);
7739           if (N020.getOpcode() == ISD::FMUL)
7740             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7741                                N0.getOperand(0), N0.getOperand(1),
7742                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7743                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7744                                                        N020.getOperand(0)),
7745                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7746                                                        N020.getOperand(1)),
7747                                            DAG.getNode(ISD::FNEG, SL, VT,
7748                                                        N1)));
7749         }
7750       }
7751
7752       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7753       //   -> (fma (fpext x), (fpext y),
7754       //           (fma (fpext u), (fpext v), (fneg z)))
7755       // FIXME: This turns two single-precision and one double-precision
7756       // operation into two double-precision operations, which might not be
7757       // interesting for all targets, especially GPUs.
7758       if (N0.getOpcode() == ISD::FP_EXTEND) {
7759         SDValue N00 = N0.getOperand(0);
7760         if (N00.getOpcode() == PreferredFusedOpcode) {
7761           SDValue N002 = N00.getOperand(2);
7762           if (N002.getOpcode() == ISD::FMUL)
7763             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7764                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                            N00.getOperand(0)),
7766                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7767                                            N00.getOperand(1)),
7768                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7769                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7770                                                        N002.getOperand(0)),
7771                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772                                                        N002.getOperand(1)),
7773                                            DAG.getNode(ISD::FNEG, SL, VT,
7774                                                        N1)));
7775         }
7776       }
7777
7778       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7779       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7780       if (N1.getOpcode() == PreferredFusedOpcode &&
7781         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7782         SDValue N120 = N1.getOperand(2).getOperand(0);
7783         if (N120.getOpcode() == ISD::FMUL) {
7784           SDValue N1200 = N120.getOperand(0);
7785           SDValue N1201 = N120.getOperand(1);
7786           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7787                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7788                              N1.getOperand(1),
7789                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7790                                          DAG.getNode(ISD::FNEG, SL, VT,
7791                                              DAG.getNode(ISD::FP_EXTEND, SL,
7792                                                          VT, N1200)),
7793                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7794                                                      N1201),
7795                                          N0));
7796         }
7797       }
7798
7799       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7800       //   -> (fma (fneg (fpext y)), (fpext z),
7801       //           (fma (fneg (fpext u)), (fpext v), x))
7802       // FIXME: This turns two single-precision and one double-precision
7803       // operation into two double-precision operations, which might not be
7804       // interesting for all targets, especially GPUs.
7805       if (N1.getOpcode() == ISD::FP_EXTEND &&
7806         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7807         SDValue N100 = N1.getOperand(0).getOperand(0);
7808         SDValue N101 = N1.getOperand(0).getOperand(1);
7809         SDValue N102 = N1.getOperand(0).getOperand(2);
7810         if (N102.getOpcode() == ISD::FMUL) {
7811           SDValue N1020 = N102.getOperand(0);
7812           SDValue N1021 = N102.getOperand(1);
7813           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7814                              DAG.getNode(ISD::FNEG, SL, VT,
7815                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7816                                                      N100)),
7817                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7818                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7819                                          DAG.getNode(ISD::FNEG, SL, VT,
7820                                              DAG.getNode(ISD::FP_EXTEND, SL,
7821                                                          VT, N1020)),
7822                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7823                                                      N1021),
7824                                          N0));
7825         }
7826       }
7827     }
7828   }
7829
7830   return SDValue();
7831 }
7832
7833 SDValue DAGCombiner::visitFADD(SDNode *N) {
7834   SDValue N0 = N->getOperand(0);
7835   SDValue N1 = N->getOperand(1);
7836   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7837   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7838   EVT VT = N->getValueType(0);
7839   SDLoc DL(N);
7840   const TargetOptions &Options = DAG.getTarget().Options;
7841
7842   // fold vector ops
7843   if (VT.isVector())
7844     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7845       return FoldedVOp;
7846
7847   // fold (fadd c1, c2) -> c1 + c2
7848   if (N0CFP && N1CFP)
7849     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7850
7851   // canonicalize constant to RHS
7852   if (N0CFP && !N1CFP)
7853     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7854
7855   // fold (fadd A, (fneg B)) -> (fsub A, B)
7856   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7857       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7858     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7859                        GetNegatedExpression(N1, DAG, LegalOperations));
7860
7861   // fold (fadd (fneg A), B) -> (fsub B, A)
7862   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7863       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7864     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7865                        GetNegatedExpression(N0, DAG, LegalOperations));
7866
7867   // If 'unsafe math' is enabled, fold lots of things.
7868   if (Options.UnsafeFPMath) {
7869     // No FP constant should be created after legalization as Instruction
7870     // Selection pass has a hard time dealing with FP constants.
7871     bool AllowNewConst = (Level < AfterLegalizeDAG);
7872
7873     // fold (fadd A, 0) -> A
7874     if (N1CFP && N1CFP->isZero())
7875       return N0;
7876
7877     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7878     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7879         isa<ConstantFPSDNode>(N0.getOperand(1)))
7880       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7881                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7882
7883     // If allowed, fold (fadd (fneg x), x) -> 0.0
7884     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7885       return DAG.getConstantFP(0.0, DL, VT);
7886
7887     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7888     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7889       return DAG.getConstantFP(0.0, DL, VT);
7890
7891     // We can fold chains of FADD's of the same value into multiplications.
7892     // This transform is not safe in general because we are reducing the number
7893     // of rounding steps.
7894     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7895       if (N0.getOpcode() == ISD::FMUL) {
7896         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7897         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7898
7899         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7900         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7901           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7902                                        DAG.getConstantFP(1.0, DL, VT));
7903           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7904         }
7905
7906         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7907         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7908             N1.getOperand(0) == N1.getOperand(1) &&
7909             N0.getOperand(0) == N1.getOperand(0)) {
7910           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7911                                        DAG.getConstantFP(2.0, DL, VT));
7912           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7913         }
7914       }
7915
7916       if (N1.getOpcode() == ISD::FMUL) {
7917         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7918         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7919
7920         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7921         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7922           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7923                                        DAG.getConstantFP(1.0, DL, VT));
7924           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7925         }
7926
7927         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7928         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7929             N0.getOperand(0) == N0.getOperand(1) &&
7930             N1.getOperand(0) == N0.getOperand(0)) {
7931           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7932                                        DAG.getConstantFP(2.0, DL, VT));
7933           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7934         }
7935       }
7936
7937       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7938         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7939         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7940         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7941             (N0.getOperand(0) == N1)) {
7942           return DAG.getNode(ISD::FMUL, DL, VT,
7943                              N1, DAG.getConstantFP(3.0, DL, VT));
7944         }
7945       }
7946
7947       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7948         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7949         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7950         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7951             N1.getOperand(0) == N0) {
7952           return DAG.getNode(ISD::FMUL, DL, VT,
7953                              N0, DAG.getConstantFP(3.0, DL, VT));
7954         }
7955       }
7956
7957       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7958       if (AllowNewConst &&
7959           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7960           N0.getOperand(0) == N0.getOperand(1) &&
7961           N1.getOperand(0) == N1.getOperand(1) &&
7962           N0.getOperand(0) == N1.getOperand(0)) {
7963         return DAG.getNode(ISD::FMUL, DL, VT,
7964                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7965       }
7966     }
7967   } // enable-unsafe-fp-math
7968
7969   // FADD -> FMA combines:
7970   SDValue Fused = visitFADDForFMACombine(N);
7971   if (Fused) {
7972     AddToWorklist(Fused.getNode());
7973     return Fused;
7974   }
7975
7976   return SDValue();
7977 }
7978
7979 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7980   SDValue N0 = N->getOperand(0);
7981   SDValue N1 = N->getOperand(1);
7982   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7983   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7984   EVT VT = N->getValueType(0);
7985   SDLoc dl(N);
7986   const TargetOptions &Options = DAG.getTarget().Options;
7987
7988   // fold vector ops
7989   if (VT.isVector())
7990     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7991       return FoldedVOp;
7992
7993   // fold (fsub c1, c2) -> c1-c2
7994   if (N0CFP && N1CFP)
7995     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7996
7997   // fold (fsub A, (fneg B)) -> (fadd A, B)
7998   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7999     return DAG.getNode(ISD::FADD, dl, VT, N0,
8000                        GetNegatedExpression(N1, DAG, LegalOperations));
8001
8002   // If 'unsafe math' is enabled, fold lots of things.
8003   if (Options.UnsafeFPMath) {
8004     // (fsub A, 0) -> A
8005     if (N1CFP && N1CFP->isZero())
8006       return N0;
8007
8008     // (fsub 0, B) -> -B
8009     if (N0CFP && N0CFP->isZero()) {
8010       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8011         return GetNegatedExpression(N1, DAG, LegalOperations);
8012       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8013         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8014     }
8015
8016     // (fsub x, x) -> 0.0
8017     if (N0 == N1)
8018       return DAG.getConstantFP(0.0f, dl, VT);
8019
8020     // (fsub x, (fadd x, y)) -> (fneg y)
8021     // (fsub x, (fadd y, x)) -> (fneg y)
8022     if (N1.getOpcode() == ISD::FADD) {
8023       SDValue N10 = N1->getOperand(0);
8024       SDValue N11 = N1->getOperand(1);
8025
8026       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8027         return GetNegatedExpression(N11, DAG, LegalOperations);
8028
8029       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8030         return GetNegatedExpression(N10, DAG, LegalOperations);
8031     }
8032   }
8033
8034   // FSUB -> FMA combines:
8035   SDValue Fused = visitFSUBForFMACombine(N);
8036   if (Fused) {
8037     AddToWorklist(Fused.getNode());
8038     return Fused;
8039   }
8040
8041   return SDValue();
8042 }
8043
8044 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8045   SDValue N0 = N->getOperand(0);
8046   SDValue N1 = N->getOperand(1);
8047   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8048   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8049   EVT VT = N->getValueType(0);
8050   SDLoc DL(N);
8051   const TargetOptions &Options = DAG.getTarget().Options;
8052
8053   // fold vector ops
8054   if (VT.isVector()) {
8055     // This just handles C1 * C2 for vectors. Other vector folds are below.
8056     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8057       return FoldedVOp;
8058   }
8059
8060   // fold (fmul c1, c2) -> c1*c2
8061   if (N0CFP && N1CFP)
8062     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8063
8064   // canonicalize constant to RHS
8065   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8066      !isConstantFPBuildVectorOrConstantFP(N1))
8067     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8068
8069   // fold (fmul A, 1.0) -> A
8070   if (N1CFP && N1CFP->isExactlyValue(1.0))
8071     return N0;
8072
8073   if (Options.UnsafeFPMath) {
8074     // fold (fmul A, 0) -> 0
8075     if (N1CFP && N1CFP->isZero())
8076       return N1;
8077
8078     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8079     if (N0.getOpcode() == ISD::FMUL) {
8080       // Fold scalars or any vector constants (not just splats).
8081       // This fold is done in general by InstCombine, but extra fmul insts
8082       // may have been generated during lowering.
8083       SDValue N00 = N0.getOperand(0);
8084       SDValue N01 = N0.getOperand(1);
8085       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8086       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8087       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8088       
8089       // Check 1: Make sure that the first operand of the inner multiply is NOT
8090       // a constant. Otherwise, we may induce infinite looping.
8091       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8092         // Check 2: Make sure that the second operand of the inner multiply and
8093         // the second operand of the outer multiply are constants.
8094         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8095             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8096           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8097           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8098         }
8099       }
8100     }
8101
8102     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8103     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8104     // during an early run of DAGCombiner can prevent folding with fmuls
8105     // inserted during lowering.
8106     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8107       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8108       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8109       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8110     }
8111   }
8112
8113   // fold (fmul X, 2.0) -> (fadd X, X)
8114   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8115     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8116
8117   // fold (fmul X, -1.0) -> (fneg X)
8118   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8119     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8120       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8121
8122   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8123   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8124     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8125       // Both can be negated for free, check to see if at least one is cheaper
8126       // negated.
8127       if (LHSNeg == 2 || RHSNeg == 2)
8128         return DAG.getNode(ISD::FMUL, DL, VT,
8129                            GetNegatedExpression(N0, DAG, LegalOperations),
8130                            GetNegatedExpression(N1, DAG, LegalOperations));
8131     }
8132   }
8133
8134   return SDValue();
8135 }
8136
8137 SDValue DAGCombiner::visitFMA(SDNode *N) {
8138   SDValue N0 = N->getOperand(0);
8139   SDValue N1 = N->getOperand(1);
8140   SDValue N2 = N->getOperand(2);
8141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8142   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8143   EVT VT = N->getValueType(0);
8144   SDLoc dl(N);
8145   const TargetOptions &Options = DAG.getTarget().Options;
8146
8147   // Constant fold FMA.
8148   if (isa<ConstantFPSDNode>(N0) &&
8149       isa<ConstantFPSDNode>(N1) &&
8150       isa<ConstantFPSDNode>(N2)) {
8151     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8152   }
8153
8154   if (Options.UnsafeFPMath) {
8155     if (N0CFP && N0CFP->isZero())
8156       return N2;
8157     if (N1CFP && N1CFP->isZero())
8158       return N2;
8159   }
8160   if (N0CFP && N0CFP->isExactlyValue(1.0))
8161     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8162   if (N1CFP && N1CFP->isExactlyValue(1.0))
8163     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8164
8165   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8166   if (N0CFP && !N1CFP)
8167     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8168
8169   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8170   if (Options.UnsafeFPMath && N1CFP &&
8171       N2.getOpcode() == ISD::FMUL &&
8172       N0 == N2.getOperand(0) &&
8173       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8174     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8175                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8176   }
8177
8178
8179   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8180   if (Options.UnsafeFPMath &&
8181       N0.getOpcode() == ISD::FMUL && N1CFP &&
8182       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8183     return DAG.getNode(ISD::FMA, dl, VT,
8184                        N0.getOperand(0),
8185                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8186                        N2);
8187   }
8188
8189   // (fma x, 1, y) -> (fadd x, y)
8190   // (fma x, -1, y) -> (fadd (fneg x), y)
8191   if (N1CFP) {
8192     if (N1CFP->isExactlyValue(1.0))
8193       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8194
8195     if (N1CFP->isExactlyValue(-1.0) &&
8196         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8197       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8198       AddToWorklist(RHSNeg.getNode());
8199       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8200     }
8201   }
8202
8203   // (fma x, c, x) -> (fmul x, (c+1))
8204   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8205     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8206                        DAG.getNode(ISD::FADD, dl, VT,
8207                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8208
8209   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8210   if (Options.UnsafeFPMath && N1CFP &&
8211       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8212     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8213                        DAG.getNode(ISD::FADD, dl, VT,
8214                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8215
8216
8217   return SDValue();
8218 }
8219
8220 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8221   SDValue N0 = N->getOperand(0);
8222   SDValue N1 = N->getOperand(1);
8223   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8224   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8225   EVT VT = N->getValueType(0);
8226   SDLoc DL(N);
8227   const TargetOptions &Options = DAG.getTarget().Options;
8228
8229   // fold vector ops
8230   if (VT.isVector())
8231     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8232       return FoldedVOp;
8233
8234   // fold (fdiv c1, c2) -> c1/c2
8235   if (N0CFP && N1CFP)
8236     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8237
8238   if (Options.UnsafeFPMath) {
8239     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8240     if (N1CFP) {
8241       // Compute the reciprocal 1.0 / c2.
8242       APFloat N1APF = N1CFP->getValueAPF();
8243       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8244       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8245       // Only do the transform if the reciprocal is a legal fp immediate that
8246       // isn't too nasty (eg NaN, denormal, ...).
8247       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8248           (!LegalOperations ||
8249            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8250            // backend)... we should handle this gracefully after Legalize.
8251            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8252            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8253            TLI.isFPImmLegal(Recip, VT)))
8254         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8255                            DAG.getConstantFP(Recip, DL, VT));
8256     }
8257
8258     // If this FDIV is part of a reciprocal square root, it may be folded
8259     // into a target-specific square root estimate instruction.
8260     if (N1.getOpcode() == ISD::FSQRT) {
8261       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8262         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8263       }
8264     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8265                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8266       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8267         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8268         AddToWorklist(RV.getNode());
8269         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8270       }
8271     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8272                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8273       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8274         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8275         AddToWorklist(RV.getNode());
8276         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8277       }
8278     } else if (N1.getOpcode() == ISD::FMUL) {
8279       // Look through an FMUL. Even though this won't remove the FDIV directly,
8280       // it's still worthwhile to get rid of the FSQRT if possible.
8281       SDValue SqrtOp;
8282       SDValue OtherOp;
8283       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8284         SqrtOp = N1.getOperand(0);
8285         OtherOp = N1.getOperand(1);
8286       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8287         SqrtOp = N1.getOperand(1);
8288         OtherOp = N1.getOperand(0);
8289       }
8290       if (SqrtOp.getNode()) {
8291         // We found a FSQRT, so try to make this fold:
8292         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8293         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8294           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8295           AddToWorklist(RV.getNode());
8296           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8297         }
8298       }
8299     }
8300
8301     // Fold into a reciprocal estimate and multiply instead of a real divide.
8302     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8303       AddToWorklist(RV.getNode());
8304       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8305     }
8306   }
8307
8308   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8309   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8310     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8311       // Both can be negated for free, check to see if at least one is cheaper
8312       // negated.
8313       if (LHSNeg == 2 || RHSNeg == 2)
8314         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8315                            GetNegatedExpression(N0, DAG, LegalOperations),
8316                            GetNegatedExpression(N1, DAG, LegalOperations));
8317     }
8318   }
8319
8320   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8321   // reciprocal.
8322   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8323   // Notice that this is not always beneficial. One reason is different target
8324   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8325   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8326   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8327   if (Options.UnsafeFPMath) {
8328     // Skip if current node is a reciprocal.
8329     if (N0CFP && N0CFP->isExactlyValue(1.0))
8330       return SDValue();
8331
8332     SmallVector<SDNode *, 4> Users;
8333     // Find all FDIV users of the same divisor.
8334     for (auto *U : N1->uses()) {
8335       if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8336         Users.push_back(U);
8337     }
8338
8339     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8340       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8341       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8342
8343       // Dividend / Divisor -> Dividend * Reciprocal
8344       for (auto *U : Users) {
8345         SDValue Dividend = U->getOperand(0);
8346         if (Dividend != FPOne) {
8347           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8348                                         Reciprocal);
8349           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8350         }
8351       }
8352       return SDValue();
8353     }
8354   }
8355
8356   return SDValue();
8357 }
8358
8359 SDValue DAGCombiner::visitFREM(SDNode *N) {
8360   SDValue N0 = N->getOperand(0);
8361   SDValue N1 = N->getOperand(1);
8362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8363   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8364   EVT VT = N->getValueType(0);
8365
8366   // fold (frem c1, c2) -> fmod(c1,c2)
8367   if (N0CFP && N1CFP)
8368     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8369
8370   return SDValue();
8371 }
8372
8373 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8374   if (DAG.getTarget().Options.UnsafeFPMath &&
8375       !TLI.isFsqrtCheap()) {
8376     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8377     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8378       EVT VT = RV.getValueType();
8379       SDLoc DL(N);
8380       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8381       AddToWorklist(RV.getNode());
8382
8383       // Unfortunately, RV is now NaN if the input was exactly 0.
8384       // Select out this case and force the answer to 0.
8385       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8386       SDValue ZeroCmp =
8387         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8388                      N->getOperand(0), Zero, ISD::SETEQ);
8389       AddToWorklist(ZeroCmp.getNode());
8390       AddToWorklist(RV.getNode());
8391
8392       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8393                        DL, VT, ZeroCmp, Zero, RV);
8394       return RV;
8395     }
8396   }
8397   return SDValue();
8398 }
8399
8400 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8401   SDValue N0 = N->getOperand(0);
8402   SDValue N1 = N->getOperand(1);
8403   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8404   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8405   EVT VT = N->getValueType(0);
8406
8407   if (N0CFP && N1CFP)  // Constant fold
8408     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8409
8410   if (N1CFP) {
8411     const APFloat& V = N1CFP->getValueAPF();
8412     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8413     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8414     if (!V.isNegative()) {
8415       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8416         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8417     } else {
8418       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8419         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8420                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8421     }
8422   }
8423
8424   // copysign(fabs(x), y) -> copysign(x, y)
8425   // copysign(fneg(x), y) -> copysign(x, y)
8426   // copysign(copysign(x,z), y) -> copysign(x, y)
8427   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8428       N0.getOpcode() == ISD::FCOPYSIGN)
8429     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8430                        N0.getOperand(0), N1);
8431
8432   // copysign(x, abs(y)) -> abs(x)
8433   if (N1.getOpcode() == ISD::FABS)
8434     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8435
8436   // copysign(x, copysign(y,z)) -> copysign(x, z)
8437   if (N1.getOpcode() == ISD::FCOPYSIGN)
8438     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8439                        N0, N1.getOperand(1));
8440
8441   // copysign(x, fp_extend(y)) -> copysign(x, y)
8442   // copysign(x, fp_round(y)) -> copysign(x, y)
8443   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8444     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8445                        N0, N1.getOperand(0));
8446
8447   return SDValue();
8448 }
8449
8450 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8451   SDValue N0 = N->getOperand(0);
8452   EVT VT = N->getValueType(0);
8453   EVT OpVT = N0.getValueType();
8454
8455   // fold (sint_to_fp c1) -> c1fp
8456   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8457       // ...but only if the target supports immediate floating-point values
8458       (!LegalOperations ||
8459        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8460     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8461
8462   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8463   // but UINT_TO_FP is legal on this target, try to convert.
8464   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8465       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8466     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8467     if (DAG.SignBitIsZero(N0))
8468       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8469   }
8470
8471   // The next optimizations are desirable only if SELECT_CC can be lowered.
8472   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8473     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8474     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8475         !VT.isVector() &&
8476         (!LegalOperations ||
8477          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8478       SDLoc DL(N);
8479       SDValue Ops[] =
8480         { N0.getOperand(0), N0.getOperand(1),
8481           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8482           N0.getOperand(2) };
8483       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8484     }
8485
8486     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8487     //      (select_cc x, y, 1.0, 0.0,, cc)
8488     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8489         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8490         (!LegalOperations ||
8491          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8492       SDLoc DL(N);
8493       SDValue Ops[] =
8494         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8495           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8496           N0.getOperand(0).getOperand(2) };
8497       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8498     }
8499   }
8500
8501   return SDValue();
8502 }
8503
8504 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8505   SDValue N0 = N->getOperand(0);
8506   EVT VT = N->getValueType(0);
8507   EVT OpVT = N0.getValueType();
8508
8509   // fold (uint_to_fp c1) -> c1fp
8510   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8511       // ...but only if the target supports immediate floating-point values
8512       (!LegalOperations ||
8513        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8514     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8515
8516   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8517   // but SINT_TO_FP is legal on this target, try to convert.
8518   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8519       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8520     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8521     if (DAG.SignBitIsZero(N0))
8522       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8523   }
8524
8525   // The next optimizations are desirable only if SELECT_CC can be lowered.
8526   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8527     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8528
8529     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8530         (!LegalOperations ||
8531          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8532       SDLoc DL(N);
8533       SDValue Ops[] =
8534         { N0.getOperand(0), N0.getOperand(1),
8535           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8536           N0.getOperand(2) };
8537       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8538     }
8539   }
8540
8541   return SDValue();
8542 }
8543
8544 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8545 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8546   SDValue N0 = N->getOperand(0);
8547   EVT VT = N->getValueType(0);
8548
8549   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8550     return SDValue();
8551
8552   SDValue Src = N0.getOperand(0);
8553   EVT SrcVT = Src.getValueType();
8554   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8555   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8556
8557   // We can safely assume the conversion won't overflow the output range,
8558   // because (for example) (uint8_t)18293.f is undefined behavior.
8559
8560   // Since we can assume the conversion won't overflow, our decision as to
8561   // whether the input will fit in the float should depend on the minimum
8562   // of the input range and output range.
8563
8564   // This means this is also safe for a signed input and unsigned output, since
8565   // a negative input would lead to undefined behavior.
8566   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8567   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8568   unsigned ActualSize = std::min(InputSize, OutputSize);
8569   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8570
8571   // We can only fold away the float conversion if the input range can be
8572   // represented exactly in the float range.
8573   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8574     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8575       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8576                                                        : ISD::ZERO_EXTEND;
8577       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8578     }
8579     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8580       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8581     if (SrcVT == VT)
8582       return Src;
8583     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8584   }
8585   return SDValue();
8586 }
8587
8588 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8589   SDValue N0 = N->getOperand(0);
8590   EVT VT = N->getValueType(0);
8591
8592   // fold (fp_to_sint c1fp) -> c1
8593   if (isConstantFPBuildVectorOrConstantFP(N0))
8594     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8595
8596   return FoldIntToFPToInt(N, DAG);
8597 }
8598
8599 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8600   SDValue N0 = N->getOperand(0);
8601   EVT VT = N->getValueType(0);
8602
8603   // fold (fp_to_uint c1fp) -> c1
8604   if (isConstantFPBuildVectorOrConstantFP(N0))
8605     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8606
8607   return FoldIntToFPToInt(N, DAG);
8608 }
8609
8610 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8611   SDValue N0 = N->getOperand(0);
8612   SDValue N1 = N->getOperand(1);
8613   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8614   EVT VT = N->getValueType(0);
8615
8616   // fold (fp_round c1fp) -> c1fp
8617   if (N0CFP)
8618     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8619
8620   // fold (fp_round (fp_extend x)) -> x
8621   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8622     return N0.getOperand(0);
8623
8624   // fold (fp_round (fp_round x)) -> (fp_round x)
8625   if (N0.getOpcode() == ISD::FP_ROUND) {
8626     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8627     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8628     // If the first fp_round isn't a value preserving truncation, it might
8629     // introduce a tie in the second fp_round, that wouldn't occur in the
8630     // single-step fp_round we want to fold to.
8631     // In other words, double rounding isn't the same as rounding.
8632     // Also, this is a value preserving truncation iff both fp_round's are.
8633     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8634       SDLoc DL(N);
8635       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8636                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8637     }
8638   }
8639
8640   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8641   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8642     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8643                               N0.getOperand(0), N1);
8644     AddToWorklist(Tmp.getNode());
8645     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8646                        Tmp, N0.getOperand(1));
8647   }
8648
8649   return SDValue();
8650 }
8651
8652 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8653   SDValue N0 = N->getOperand(0);
8654   EVT VT = N->getValueType(0);
8655   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8656   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8657
8658   // fold (fp_round_inreg c1fp) -> c1fp
8659   if (N0CFP && isTypeLegal(EVT)) {
8660     SDLoc DL(N);
8661     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8662     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8663   }
8664
8665   return SDValue();
8666 }
8667
8668 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8669   SDValue N0 = N->getOperand(0);
8670   EVT VT = N->getValueType(0);
8671
8672   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8673   if (N->hasOneUse() &&
8674       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8675     return SDValue();
8676
8677   // fold (fp_extend c1fp) -> c1fp
8678   if (isConstantFPBuildVectorOrConstantFP(N0))
8679     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8680
8681   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8682   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8683       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8684     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8685
8686   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8687   // value of X.
8688   if (N0.getOpcode() == ISD::FP_ROUND
8689       && N0.getNode()->getConstantOperandVal(1) == 1) {
8690     SDValue In = N0.getOperand(0);
8691     if (In.getValueType() == VT) return In;
8692     if (VT.bitsLT(In.getValueType()))
8693       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8694                          In, N0.getOperand(1));
8695     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8696   }
8697
8698   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8699   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8700        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8701     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8702     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8703                                      LN0->getChain(),
8704                                      LN0->getBasePtr(), N0.getValueType(),
8705                                      LN0->getMemOperand());
8706     CombineTo(N, ExtLoad);
8707     CombineTo(N0.getNode(),
8708               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8709                           N0.getValueType(), ExtLoad,
8710                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8711               ExtLoad.getValue(1));
8712     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8713   }
8714
8715   return SDValue();
8716 }
8717
8718 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8719   SDValue N0 = N->getOperand(0);
8720   EVT VT = N->getValueType(0);
8721
8722   // fold (fceil c1) -> fceil(c1)
8723   if (isConstantFPBuildVectorOrConstantFP(N0))
8724     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8725
8726   return SDValue();
8727 }
8728
8729 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8730   SDValue N0 = N->getOperand(0);
8731   EVT VT = N->getValueType(0);
8732
8733   // fold (ftrunc c1) -> ftrunc(c1)
8734   if (isConstantFPBuildVectorOrConstantFP(N0))
8735     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8736
8737   return SDValue();
8738 }
8739
8740 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8741   SDValue N0 = N->getOperand(0);
8742   EVT VT = N->getValueType(0);
8743
8744   // fold (ffloor c1) -> ffloor(c1)
8745   if (isConstantFPBuildVectorOrConstantFP(N0))
8746     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8747
8748   return SDValue();
8749 }
8750
8751 // FIXME: FNEG and FABS have a lot in common; refactor.
8752 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8753   SDValue N0 = N->getOperand(0);
8754   EVT VT = N->getValueType(0);
8755
8756   // Constant fold FNEG.
8757   if (isConstantFPBuildVectorOrConstantFP(N0))
8758     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8759
8760   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8761                          &DAG.getTarget().Options))
8762     return GetNegatedExpression(N0, DAG, LegalOperations);
8763
8764   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8765   // constant pool values.
8766   if (!TLI.isFNegFree(VT) &&
8767       N0.getOpcode() == ISD::BITCAST &&
8768       N0.getNode()->hasOneUse()) {
8769     SDValue Int = N0.getOperand(0);
8770     EVT IntVT = Int.getValueType();
8771     if (IntVT.isInteger() && !IntVT.isVector()) {
8772       APInt SignMask;
8773       if (N0.getValueType().isVector()) {
8774         // For a vector, get a mask such as 0x80... per scalar element
8775         // and splat it.
8776         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8777         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8778       } else {
8779         // For a scalar, just generate 0x80...
8780         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8781       }
8782       SDLoc DL0(N0);
8783       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8784                         DAG.getConstant(SignMask, DL0, IntVT));
8785       AddToWorklist(Int.getNode());
8786       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8787     }
8788   }
8789
8790   // (fneg (fmul c, x)) -> (fmul -c, x)
8791   if (N0.getOpcode() == ISD::FMUL &&
8792       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8793     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8794     if (CFP1) {
8795       APFloat CVal = CFP1->getValueAPF();
8796       CVal.changeSign();
8797       if (Level >= AfterLegalizeDAG &&
8798           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8799            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8800         return DAG.getNode(
8801             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8802             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8803     }
8804   }
8805
8806   return SDValue();
8807 }
8808
8809 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8810   SDValue N0 = N->getOperand(0);
8811   SDValue N1 = N->getOperand(1);
8812   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8813   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8814
8815   if (N0CFP && N1CFP) {
8816     const APFloat &C0 = N0CFP->getValueAPF();
8817     const APFloat &C1 = N1CFP->getValueAPF();
8818     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8819   }
8820
8821   if (N0CFP) {
8822     EVT VT = N->getValueType(0);
8823     // Canonicalize to constant on RHS.
8824     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8825   }
8826
8827   return SDValue();
8828 }
8829
8830 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8831   SDValue N0 = N->getOperand(0);
8832   SDValue N1 = N->getOperand(1);
8833   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8834   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8835
8836   if (N0CFP && N1CFP) {
8837     const APFloat &C0 = N0CFP->getValueAPF();
8838     const APFloat &C1 = N1CFP->getValueAPF();
8839     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8840   }
8841
8842   if (N0CFP) {
8843     EVT VT = N->getValueType(0);
8844     // Canonicalize to constant on RHS.
8845     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8846   }
8847
8848   return SDValue();
8849 }
8850
8851 SDValue DAGCombiner::visitFABS(SDNode *N) {
8852   SDValue N0 = N->getOperand(0);
8853   EVT VT = N->getValueType(0);
8854
8855   // fold (fabs c1) -> fabs(c1)
8856   if (isConstantFPBuildVectorOrConstantFP(N0))
8857     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8858
8859   // fold (fabs (fabs x)) -> (fabs x)
8860   if (N0.getOpcode() == ISD::FABS)
8861     return N->getOperand(0);
8862
8863   // fold (fabs (fneg x)) -> (fabs x)
8864   // fold (fabs (fcopysign x, y)) -> (fabs x)
8865   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8866     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8867
8868   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8869   // constant pool values.
8870   if (!TLI.isFAbsFree(VT) &&
8871       N0.getOpcode() == ISD::BITCAST &&
8872       N0.getNode()->hasOneUse()) {
8873     SDValue Int = N0.getOperand(0);
8874     EVT IntVT = Int.getValueType();
8875     if (IntVT.isInteger() && !IntVT.isVector()) {
8876       APInt SignMask;
8877       if (N0.getValueType().isVector()) {
8878         // For a vector, get a mask such as 0x7f... per scalar element
8879         // and splat it.
8880         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8881         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8882       } else {
8883         // For a scalar, just generate 0x7f...
8884         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8885       }
8886       SDLoc DL(N0);
8887       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8888                         DAG.getConstant(SignMask, DL, IntVT));
8889       AddToWorklist(Int.getNode());
8890       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8891     }
8892   }
8893
8894   return SDValue();
8895 }
8896
8897 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8898   SDValue Chain = N->getOperand(0);
8899   SDValue N1 = N->getOperand(1);
8900   SDValue N2 = N->getOperand(2);
8901
8902   // If N is a constant we could fold this into a fallthrough or unconditional
8903   // branch. However that doesn't happen very often in normal code, because
8904   // Instcombine/SimplifyCFG should have handled the available opportunities.
8905   // If we did this folding here, it would be necessary to update the
8906   // MachineBasicBlock CFG, which is awkward.
8907
8908   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8909   // on the target.
8910   if (N1.getOpcode() == ISD::SETCC &&
8911       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8912                                    N1.getOperand(0).getValueType())) {
8913     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8914                        Chain, N1.getOperand(2),
8915                        N1.getOperand(0), N1.getOperand(1), N2);
8916   }
8917
8918   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8919       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8920        (N1.getOperand(0).hasOneUse() &&
8921         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8922     SDNode *Trunc = nullptr;
8923     if (N1.getOpcode() == ISD::TRUNCATE) {
8924       // Look pass the truncate.
8925       Trunc = N1.getNode();
8926       N1 = N1.getOperand(0);
8927     }
8928
8929     // Match this pattern so that we can generate simpler code:
8930     //
8931     //   %a = ...
8932     //   %b = and i32 %a, 2
8933     //   %c = srl i32 %b, 1
8934     //   brcond i32 %c ...
8935     //
8936     // into
8937     //
8938     //   %a = ...
8939     //   %b = and i32 %a, 2
8940     //   %c = setcc eq %b, 0
8941     //   brcond %c ...
8942     //
8943     // This applies only when the AND constant value has one bit set and the
8944     // SRL constant is equal to the log2 of the AND constant. The back-end is
8945     // smart enough to convert the result into a TEST/JMP sequence.
8946     SDValue Op0 = N1.getOperand(0);
8947     SDValue Op1 = N1.getOperand(1);
8948
8949     if (Op0.getOpcode() == ISD::AND &&
8950         Op1.getOpcode() == ISD::Constant) {
8951       SDValue AndOp1 = Op0.getOperand(1);
8952
8953       if (AndOp1.getOpcode() == ISD::Constant) {
8954         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8955
8956         if (AndConst.isPowerOf2() &&
8957             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8958           SDLoc DL(N);
8959           SDValue SetCC =
8960             DAG.getSetCC(DL,
8961                          getSetCCResultType(Op0.getValueType()),
8962                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8963                          ISD::SETNE);
8964
8965           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8966                                           MVT::Other, Chain, SetCC, N2);
8967           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8968           // will convert it back to (X & C1) >> C2.
8969           CombineTo(N, NewBRCond, false);
8970           // Truncate is dead.
8971           if (Trunc)
8972             deleteAndRecombine(Trunc);
8973           // Replace the uses of SRL with SETCC
8974           WorklistRemover DeadNodes(*this);
8975           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8976           deleteAndRecombine(N1.getNode());
8977           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8978         }
8979       }
8980     }
8981
8982     if (Trunc)
8983       // Restore N1 if the above transformation doesn't match.
8984       N1 = N->getOperand(1);
8985   }
8986
8987   // Transform br(xor(x, y)) -> br(x != y)
8988   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8989   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8990     SDNode *TheXor = N1.getNode();
8991     SDValue Op0 = TheXor->getOperand(0);
8992     SDValue Op1 = TheXor->getOperand(1);
8993     if (Op0.getOpcode() == Op1.getOpcode()) {
8994       // Avoid missing important xor optimizations.
8995       SDValue Tmp = visitXOR(TheXor);
8996       if (Tmp.getNode()) {
8997         if (Tmp.getNode() != TheXor) {
8998           DEBUG(dbgs() << "\nReplacing.8 ";
8999                 TheXor->dump(&DAG);
9000                 dbgs() << "\nWith: ";
9001                 Tmp.getNode()->dump(&DAG);
9002                 dbgs() << '\n');
9003           WorklistRemover DeadNodes(*this);
9004           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9005           deleteAndRecombine(TheXor);
9006           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9007                              MVT::Other, Chain, Tmp, N2);
9008         }
9009
9010         // visitXOR has changed XOR's operands or replaced the XOR completely,
9011         // bail out.
9012         return SDValue(N, 0);
9013       }
9014     }
9015
9016     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9017       bool Equal = false;
9018       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9019           Op0.getOpcode() == ISD::XOR) {
9020         TheXor = Op0.getNode();
9021         Equal = true;
9022       }
9023
9024       EVT SetCCVT = N1.getValueType();
9025       if (LegalTypes)
9026         SetCCVT = getSetCCResultType(SetCCVT);
9027       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9028                                    SetCCVT,
9029                                    Op0, Op1,
9030                                    Equal ? ISD::SETEQ : ISD::SETNE);
9031       // Replace the uses of XOR with SETCC
9032       WorklistRemover DeadNodes(*this);
9033       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9034       deleteAndRecombine(N1.getNode());
9035       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9036                          MVT::Other, Chain, SetCC, N2);
9037     }
9038   }
9039
9040   return SDValue();
9041 }
9042
9043 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9044 //
9045 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9046   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9047   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9048
9049   // If N is a constant we could fold this into a fallthrough or unconditional
9050   // branch. However that doesn't happen very often in normal code, because
9051   // Instcombine/SimplifyCFG should have handled the available opportunities.
9052   // If we did this folding here, it would be necessary to update the
9053   // MachineBasicBlock CFG, which is awkward.
9054
9055   // Use SimplifySetCC to simplify SETCC's.
9056   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9057                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9058                                false);
9059   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9060
9061   // fold to a simpler setcc
9062   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9063     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9064                        N->getOperand(0), Simp.getOperand(2),
9065                        Simp.getOperand(0), Simp.getOperand(1),
9066                        N->getOperand(4));
9067
9068   return SDValue();
9069 }
9070
9071 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9072 /// and that N may be folded in the load / store addressing mode.
9073 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9074                                     SelectionDAG &DAG,
9075                                     const TargetLowering &TLI) {
9076   EVT VT;
9077   unsigned AS;
9078
9079   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9080     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9081       return false;
9082     VT = LD->getMemoryVT();
9083     AS = LD->getAddressSpace();
9084   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9085     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9086       return false;
9087     VT = ST->getMemoryVT();
9088     AS = ST->getAddressSpace();
9089   } else
9090     return false;
9091
9092   TargetLowering::AddrMode AM;
9093   if (N->getOpcode() == ISD::ADD) {
9094     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9095     if (Offset)
9096       // [reg +/- imm]
9097       AM.BaseOffs = Offset->getSExtValue();
9098     else
9099       // [reg +/- reg]
9100       AM.Scale = 1;
9101   } else if (N->getOpcode() == ISD::SUB) {
9102     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9103     if (Offset)
9104       // [reg +/- imm]
9105       AM.BaseOffs = -Offset->getSExtValue();
9106     else
9107       // [reg +/- reg]
9108       AM.Scale = 1;
9109   } else
9110     return false;
9111
9112   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9113 }
9114
9115 /// Try turning a load/store into a pre-indexed load/store when the base
9116 /// pointer is an add or subtract and it has other uses besides the load/store.
9117 /// After the transformation, the new indexed load/store has effectively folded
9118 /// the add/subtract in and all of its other uses are redirected to the
9119 /// new load/store.
9120 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9121   if (Level < AfterLegalizeDAG)
9122     return false;
9123
9124   bool isLoad = true;
9125   SDValue Ptr;
9126   EVT VT;
9127   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9128     if (LD->isIndexed())
9129       return false;
9130     VT = LD->getMemoryVT();
9131     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9132         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9133       return false;
9134     Ptr = LD->getBasePtr();
9135   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9136     if (ST->isIndexed())
9137       return false;
9138     VT = ST->getMemoryVT();
9139     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9140         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9141       return false;
9142     Ptr = ST->getBasePtr();
9143     isLoad = false;
9144   } else {
9145     return false;
9146   }
9147
9148   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9149   // out.  There is no reason to make this a preinc/predec.
9150   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9151       Ptr.getNode()->hasOneUse())
9152     return false;
9153
9154   // Ask the target to do addressing mode selection.
9155   SDValue BasePtr;
9156   SDValue Offset;
9157   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9158   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9159     return false;
9160
9161   // Backends without true r+i pre-indexed forms may need to pass a
9162   // constant base with a variable offset so that constant coercion
9163   // will work with the patterns in canonical form.
9164   bool Swapped = false;
9165   if (isa<ConstantSDNode>(BasePtr)) {
9166     std::swap(BasePtr, Offset);
9167     Swapped = true;
9168   }
9169
9170   // Don't create a indexed load / store with zero offset.
9171   if (isNullConstant(Offset))
9172     return false;
9173
9174   // Try turning it into a pre-indexed load / store except when:
9175   // 1) The new base ptr is a frame index.
9176   // 2) If N is a store and the new base ptr is either the same as or is a
9177   //    predecessor of the value being stored.
9178   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9179   //    that would create a cycle.
9180   // 4) All uses are load / store ops that use it as old base ptr.
9181
9182   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9183   // (plus the implicit offset) to a register to preinc anyway.
9184   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9185     return false;
9186
9187   // Check #2.
9188   if (!isLoad) {
9189     SDValue Val = cast<StoreSDNode>(N)->getValue();
9190     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9191       return false;
9192   }
9193
9194   // If the offset is a constant, there may be other adds of constants that
9195   // can be folded with this one. We should do this to avoid having to keep
9196   // a copy of the original base pointer.
9197   SmallVector<SDNode *, 16> OtherUses;
9198   if (isa<ConstantSDNode>(Offset))
9199     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9200                               UE = BasePtr.getNode()->use_end();
9201          UI != UE; ++UI) {
9202       SDUse &Use = UI.getUse();
9203       // Skip the use that is Ptr and uses of other results from BasePtr's
9204       // node (important for nodes that return multiple results).
9205       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9206         continue;
9207
9208       if (Use.getUser()->isPredecessorOf(N))
9209         continue;
9210
9211       if (Use.getUser()->getOpcode() != ISD::ADD &&
9212           Use.getUser()->getOpcode() != ISD::SUB) {
9213         OtherUses.clear();
9214         break;
9215       }
9216
9217       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9218       if (!isa<ConstantSDNode>(Op1)) {
9219         OtherUses.clear();
9220         break;
9221       }
9222
9223       // FIXME: In some cases, we can be smarter about this.
9224       if (Op1.getValueType() != Offset.getValueType()) {
9225         OtherUses.clear();
9226         break;
9227       }
9228
9229       OtherUses.push_back(Use.getUser());
9230     }
9231
9232   if (Swapped)
9233     std::swap(BasePtr, Offset);
9234
9235   // Now check for #3 and #4.
9236   bool RealUse = false;
9237
9238   // Caches for hasPredecessorHelper
9239   SmallPtrSet<const SDNode *, 32> Visited;
9240   SmallVector<const SDNode *, 16> Worklist;
9241
9242   for (SDNode *Use : Ptr.getNode()->uses()) {
9243     if (Use == N)
9244       continue;
9245     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9246       return false;
9247
9248     // If Ptr may be folded in addressing mode of other use, then it's
9249     // not profitable to do this transformation.
9250     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9251       RealUse = true;
9252   }
9253
9254   if (!RealUse)
9255     return false;
9256
9257   SDValue Result;
9258   if (isLoad)
9259     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9260                                 BasePtr, Offset, AM);
9261   else
9262     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9263                                  BasePtr, Offset, AM);
9264   ++PreIndexedNodes;
9265   ++NodesCombined;
9266   DEBUG(dbgs() << "\nReplacing.4 ";
9267         N->dump(&DAG);
9268         dbgs() << "\nWith: ";
9269         Result.getNode()->dump(&DAG);
9270         dbgs() << '\n');
9271   WorklistRemover DeadNodes(*this);
9272   if (isLoad) {
9273     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9274     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9275   } else {
9276     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9277   }
9278
9279   // Finally, since the node is now dead, remove it from the graph.
9280   deleteAndRecombine(N);
9281
9282   if (Swapped)
9283     std::swap(BasePtr, Offset);
9284
9285   // Replace other uses of BasePtr that can be updated to use Ptr
9286   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9287     unsigned OffsetIdx = 1;
9288     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9289       OffsetIdx = 0;
9290     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9291            BasePtr.getNode() && "Expected BasePtr operand");
9292
9293     // We need to replace ptr0 in the following expression:
9294     //   x0 * offset0 + y0 * ptr0 = t0
9295     // knowing that
9296     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9297     //
9298     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9299     // indexed load/store and the expresion that needs to be re-written.
9300     //
9301     // Therefore, we have:
9302     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9303
9304     ConstantSDNode *CN =
9305       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9306     int X0, X1, Y0, Y1;
9307     APInt Offset0 = CN->getAPIntValue();
9308     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9309
9310     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9311     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9312     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9313     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9314
9315     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9316
9317     APInt CNV = Offset0;
9318     if (X0 < 0) CNV = -CNV;
9319     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9320     else CNV = CNV - Offset1;
9321
9322     SDLoc DL(OtherUses[i]);
9323
9324     // We can now generate the new expression.
9325     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9326     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9327
9328     SDValue NewUse = DAG.getNode(Opcode,
9329                                  DL,
9330                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9331     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9332     deleteAndRecombine(OtherUses[i]);
9333   }
9334
9335   // Replace the uses of Ptr with uses of the updated base value.
9336   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9337   deleteAndRecombine(Ptr.getNode());
9338
9339   return true;
9340 }
9341
9342 /// Try to combine a load/store with a add/sub of the base pointer node into a
9343 /// post-indexed load/store. The transformation folded the add/subtract into the
9344 /// new indexed load/store effectively and all of its uses are redirected to the
9345 /// new load/store.
9346 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9347   if (Level < AfterLegalizeDAG)
9348     return false;
9349
9350   bool isLoad = true;
9351   SDValue Ptr;
9352   EVT VT;
9353   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9354     if (LD->isIndexed())
9355       return false;
9356     VT = LD->getMemoryVT();
9357     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9358         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9359       return false;
9360     Ptr = LD->getBasePtr();
9361   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9362     if (ST->isIndexed())
9363       return false;
9364     VT = ST->getMemoryVT();
9365     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9366         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9367       return false;
9368     Ptr = ST->getBasePtr();
9369     isLoad = false;
9370   } else {
9371     return false;
9372   }
9373
9374   if (Ptr.getNode()->hasOneUse())
9375     return false;
9376
9377   for (SDNode *Op : Ptr.getNode()->uses()) {
9378     if (Op == N ||
9379         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9380       continue;
9381
9382     SDValue BasePtr;
9383     SDValue Offset;
9384     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9385     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9386       // Don't create a indexed load / store with zero offset.
9387       if (isNullConstant(Offset))
9388         continue;
9389
9390       // Try turning it into a post-indexed load / store except when
9391       // 1) All uses are load / store ops that use it as base ptr (and
9392       //    it may be folded as addressing mmode).
9393       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9394       //    nor a successor of N. Otherwise, if Op is folded that would
9395       //    create a cycle.
9396
9397       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9398         continue;
9399
9400       // Check for #1.
9401       bool TryNext = false;
9402       for (SDNode *Use : BasePtr.getNode()->uses()) {
9403         if (Use == Ptr.getNode())
9404           continue;
9405
9406         // If all the uses are load / store addresses, then don't do the
9407         // transformation.
9408         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9409           bool RealUse = false;
9410           for (SDNode *UseUse : Use->uses()) {
9411             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9412               RealUse = true;
9413           }
9414
9415           if (!RealUse) {
9416             TryNext = true;
9417             break;
9418           }
9419         }
9420       }
9421
9422       if (TryNext)
9423         continue;
9424
9425       // Check for #2
9426       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9427         SDValue Result = isLoad
9428           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9429                                BasePtr, Offset, AM)
9430           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9431                                 BasePtr, Offset, AM);
9432         ++PostIndexedNodes;
9433         ++NodesCombined;
9434         DEBUG(dbgs() << "\nReplacing.5 ";
9435               N->dump(&DAG);
9436               dbgs() << "\nWith: ";
9437               Result.getNode()->dump(&DAG);
9438               dbgs() << '\n');
9439         WorklistRemover DeadNodes(*this);
9440         if (isLoad) {
9441           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9442           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9443         } else {
9444           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9445         }
9446
9447         // Finally, since the node is now dead, remove it from the graph.
9448         deleteAndRecombine(N);
9449
9450         // Replace the uses of Use with uses of the updated base value.
9451         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9452                                       Result.getValue(isLoad ? 1 : 0));
9453         deleteAndRecombine(Op);
9454         return true;
9455       }
9456     }
9457   }
9458
9459   return false;
9460 }
9461
9462 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9463 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9464   ISD::MemIndexedMode AM = LD->getAddressingMode();
9465   assert(AM != ISD::UNINDEXED);
9466   SDValue BP = LD->getOperand(1);
9467   SDValue Inc = LD->getOperand(2);
9468
9469   // Some backends use TargetConstants for load offsets, but don't expect
9470   // TargetConstants in general ADD nodes. We can convert these constants into
9471   // regular Constants (if the constant is not opaque).
9472   assert((Inc.getOpcode() != ISD::TargetConstant ||
9473           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9474          "Cannot split out indexing using opaque target constants");
9475   if (Inc.getOpcode() == ISD::TargetConstant) {
9476     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9477     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9478                           ConstInc->getValueType(0));
9479   }
9480
9481   unsigned Opc =
9482       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9483   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9484 }
9485
9486 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9487   LoadSDNode *LD  = cast<LoadSDNode>(N);
9488   SDValue Chain = LD->getChain();
9489   SDValue Ptr   = LD->getBasePtr();
9490
9491   // If load is not volatile and there are no uses of the loaded value (and
9492   // the updated indexed value in case of indexed loads), change uses of the
9493   // chain value into uses of the chain input (i.e. delete the dead load).
9494   if (!LD->isVolatile()) {
9495     if (N->getValueType(1) == MVT::Other) {
9496       // Unindexed loads.
9497       if (!N->hasAnyUseOfValue(0)) {
9498         // It's not safe to use the two value CombineTo variant here. e.g.
9499         // v1, chain2 = load chain1, loc
9500         // v2, chain3 = load chain2, loc
9501         // v3         = add v2, c
9502         // Now we replace use of chain2 with chain1.  This makes the second load
9503         // isomorphic to the one we are deleting, and thus makes this load live.
9504         DEBUG(dbgs() << "\nReplacing.6 ";
9505               N->dump(&DAG);
9506               dbgs() << "\nWith chain: ";
9507               Chain.getNode()->dump(&DAG);
9508               dbgs() << "\n");
9509         WorklistRemover DeadNodes(*this);
9510         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9511
9512         if (N->use_empty())
9513           deleteAndRecombine(N);
9514
9515         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9516       }
9517     } else {
9518       // Indexed loads.
9519       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9520
9521       // If this load has an opaque TargetConstant offset, then we cannot split
9522       // the indexing into an add/sub directly (that TargetConstant may not be
9523       // valid for a different type of node, and we cannot convert an opaque
9524       // target constant into a regular constant).
9525       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9526                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9527
9528       if (!N->hasAnyUseOfValue(0) &&
9529           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9530         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9531         SDValue Index;
9532         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9533           Index = SplitIndexingFromLoad(LD);
9534           // Try to fold the base pointer arithmetic into subsequent loads and
9535           // stores.
9536           AddUsersToWorklist(N);
9537         } else
9538           Index = DAG.getUNDEF(N->getValueType(1));
9539         DEBUG(dbgs() << "\nReplacing.7 ";
9540               N->dump(&DAG);
9541               dbgs() << "\nWith: ";
9542               Undef.getNode()->dump(&DAG);
9543               dbgs() << " and 2 other values\n");
9544         WorklistRemover DeadNodes(*this);
9545         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9546         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9547         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9548         deleteAndRecombine(N);
9549         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9550       }
9551     }
9552   }
9553
9554   // If this load is directly stored, replace the load value with the stored
9555   // value.
9556   // TODO: Handle store large -> read small portion.
9557   // TODO: Handle TRUNCSTORE/LOADEXT
9558   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9559     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9560       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9561       if (PrevST->getBasePtr() == Ptr &&
9562           PrevST->getValue().getValueType() == N->getValueType(0))
9563       return CombineTo(N, Chain.getOperand(1), Chain);
9564     }
9565   }
9566
9567   // Try to infer better alignment information than the load already has.
9568   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9569     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9570       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9571         SDValue NewLoad =
9572                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9573                               LD->getValueType(0),
9574                               Chain, Ptr, LD->getPointerInfo(),
9575                               LD->getMemoryVT(),
9576                               LD->isVolatile(), LD->isNonTemporal(),
9577                               LD->isInvariant(), Align, LD->getAAInfo());
9578         if (NewLoad.getNode() != N)
9579           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9580       }
9581     }
9582   }
9583
9584   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9585                                                   : DAG.getSubtarget().useAA();
9586 #ifndef NDEBUG
9587   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9588       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9589     UseAA = false;
9590 #endif
9591   if (UseAA && LD->isUnindexed()) {
9592     // Walk up chain skipping non-aliasing memory nodes.
9593     SDValue BetterChain = FindBetterChain(N, Chain);
9594
9595     // If there is a better chain.
9596     if (Chain != BetterChain) {
9597       SDValue ReplLoad;
9598
9599       // Replace the chain to void dependency.
9600       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9601         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9602                                BetterChain, Ptr, LD->getMemOperand());
9603       } else {
9604         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9605                                   LD->getValueType(0),
9606                                   BetterChain, Ptr, LD->getMemoryVT(),
9607                                   LD->getMemOperand());
9608       }
9609
9610       // Create token factor to keep old chain connected.
9611       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9612                                   MVT::Other, Chain, ReplLoad.getValue(1));
9613
9614       // Make sure the new and old chains are cleaned up.
9615       AddToWorklist(Token.getNode());
9616
9617       // Replace uses with load result and token factor. Don't add users
9618       // to work list.
9619       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9620     }
9621   }
9622
9623   // Try transforming N to an indexed load.
9624   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9625     return SDValue(N, 0);
9626
9627   // Try to slice up N to more direct loads if the slices are mapped to
9628   // different register banks or pairing can take place.
9629   if (SliceUpLoad(N))
9630     return SDValue(N, 0);
9631
9632   return SDValue();
9633 }
9634
9635 namespace {
9636 /// \brief Helper structure used to slice a load in smaller loads.
9637 /// Basically a slice is obtained from the following sequence:
9638 /// Origin = load Ty1, Base
9639 /// Shift = srl Ty1 Origin, CstTy Amount
9640 /// Inst = trunc Shift to Ty2
9641 ///
9642 /// Then, it will be rewriten into:
9643 /// Slice = load SliceTy, Base + SliceOffset
9644 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9645 ///
9646 /// SliceTy is deduced from the number of bits that are actually used to
9647 /// build Inst.
9648 struct LoadedSlice {
9649   /// \brief Helper structure used to compute the cost of a slice.
9650   struct Cost {
9651     /// Are we optimizing for code size.
9652     bool ForCodeSize;
9653     /// Various cost.
9654     unsigned Loads;
9655     unsigned Truncates;
9656     unsigned CrossRegisterBanksCopies;
9657     unsigned ZExts;
9658     unsigned Shift;
9659
9660     Cost(bool ForCodeSize = false)
9661         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9662           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9663
9664     /// \brief Get the cost of one isolated slice.
9665     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9666         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9667           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9668       EVT TruncType = LS.Inst->getValueType(0);
9669       EVT LoadedType = LS.getLoadedType();
9670       if (TruncType != LoadedType &&
9671           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9672         ZExts = 1;
9673     }
9674
9675     /// \brief Account for slicing gain in the current cost.
9676     /// Slicing provide a few gains like removing a shift or a
9677     /// truncate. This method allows to grow the cost of the original
9678     /// load with the gain from this slice.
9679     void addSliceGain(const LoadedSlice &LS) {
9680       // Each slice saves a truncate.
9681       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9682       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9683                               LS.Inst->getOperand(0).getValueType()))
9684         ++Truncates;
9685       // If there is a shift amount, this slice gets rid of it.
9686       if (LS.Shift)
9687         ++Shift;
9688       // If this slice can merge a cross register bank copy, account for it.
9689       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9690         ++CrossRegisterBanksCopies;
9691     }
9692
9693     Cost &operator+=(const Cost &RHS) {
9694       Loads += RHS.Loads;
9695       Truncates += RHS.Truncates;
9696       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9697       ZExts += RHS.ZExts;
9698       Shift += RHS.Shift;
9699       return *this;
9700     }
9701
9702     bool operator==(const Cost &RHS) const {
9703       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9704              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9705              ZExts == RHS.ZExts && Shift == RHS.Shift;
9706     }
9707
9708     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9709
9710     bool operator<(const Cost &RHS) const {
9711       // Assume cross register banks copies are as expensive as loads.
9712       // FIXME: Do we want some more target hooks?
9713       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9714       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9715       // Unless we are optimizing for code size, consider the
9716       // expensive operation first.
9717       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9718         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9719       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9720              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9721     }
9722
9723     bool operator>(const Cost &RHS) const { return RHS < *this; }
9724
9725     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9726
9727     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9728   };
9729   // The last instruction that represent the slice. This should be a
9730   // truncate instruction.
9731   SDNode *Inst;
9732   // The original load instruction.
9733   LoadSDNode *Origin;
9734   // The right shift amount in bits from the original load.
9735   unsigned Shift;
9736   // The DAG from which Origin came from.
9737   // This is used to get some contextual information about legal types, etc.
9738   SelectionDAG *DAG;
9739
9740   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9741               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9742       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9743
9744   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9745   /// \return Result is \p BitWidth and has used bits set to 1 and
9746   ///         not used bits set to 0.
9747   APInt getUsedBits() const {
9748     // Reproduce the trunc(lshr) sequence:
9749     // - Start from the truncated value.
9750     // - Zero extend to the desired bit width.
9751     // - Shift left.
9752     assert(Origin && "No original load to compare against.");
9753     unsigned BitWidth = Origin->getValueSizeInBits(0);
9754     assert(Inst && "This slice is not bound to an instruction");
9755     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9756            "Extracted slice is bigger than the whole type!");
9757     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9758     UsedBits.setAllBits();
9759     UsedBits = UsedBits.zext(BitWidth);
9760     UsedBits <<= Shift;
9761     return UsedBits;
9762   }
9763
9764   /// \brief Get the size of the slice to be loaded in bytes.
9765   unsigned getLoadedSize() const {
9766     unsigned SliceSize = getUsedBits().countPopulation();
9767     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9768     return SliceSize / 8;
9769   }
9770
9771   /// \brief Get the type that will be loaded for this slice.
9772   /// Note: This may not be the final type for the slice.
9773   EVT getLoadedType() const {
9774     assert(DAG && "Missing context");
9775     LLVMContext &Ctxt = *DAG->getContext();
9776     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9777   }
9778
9779   /// \brief Get the alignment of the load used for this slice.
9780   unsigned getAlignment() const {
9781     unsigned Alignment = Origin->getAlignment();
9782     unsigned Offset = getOffsetFromBase();
9783     if (Offset != 0)
9784       Alignment = MinAlign(Alignment, Alignment + Offset);
9785     return Alignment;
9786   }
9787
9788   /// \brief Check if this slice can be rewritten with legal operations.
9789   bool isLegal() const {
9790     // An invalid slice is not legal.
9791     if (!Origin || !Inst || !DAG)
9792       return false;
9793
9794     // Offsets are for indexed load only, we do not handle that.
9795     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9796       return false;
9797
9798     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9799
9800     // Check that the type is legal.
9801     EVT SliceType = getLoadedType();
9802     if (!TLI.isTypeLegal(SliceType))
9803       return false;
9804
9805     // Check that the load is legal for this type.
9806     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9807       return false;
9808
9809     // Check that the offset can be computed.
9810     // 1. Check its type.
9811     EVT PtrType = Origin->getBasePtr().getValueType();
9812     if (PtrType == MVT::Untyped || PtrType.isExtended())
9813       return false;
9814
9815     // 2. Check that it fits in the immediate.
9816     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9817       return false;
9818
9819     // 3. Check that the computation is legal.
9820     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9821       return false;
9822
9823     // Check that the zext is legal if it needs one.
9824     EVT TruncateType = Inst->getValueType(0);
9825     if (TruncateType != SliceType &&
9826         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9827       return false;
9828
9829     return true;
9830   }
9831
9832   /// \brief Get the offset in bytes of this slice in the original chunk of
9833   /// bits.
9834   /// \pre DAG != nullptr.
9835   uint64_t getOffsetFromBase() const {
9836     assert(DAG && "Missing context.");
9837     bool IsBigEndian =
9838         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9839     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9840     uint64_t Offset = Shift / 8;
9841     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9842     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9843            "The size of the original loaded type is not a multiple of a"
9844            " byte.");
9845     // If Offset is bigger than TySizeInBytes, it means we are loading all
9846     // zeros. This should have been optimized before in the process.
9847     assert(TySizeInBytes > Offset &&
9848            "Invalid shift amount for given loaded size");
9849     if (IsBigEndian)
9850       Offset = TySizeInBytes - Offset - getLoadedSize();
9851     return Offset;
9852   }
9853
9854   /// \brief Generate the sequence of instructions to load the slice
9855   /// represented by this object and redirect the uses of this slice to
9856   /// this new sequence of instructions.
9857   /// \pre this->Inst && this->Origin are valid Instructions and this
9858   /// object passed the legal check: LoadedSlice::isLegal returned true.
9859   /// \return The last instruction of the sequence used to load the slice.
9860   SDValue loadSlice() const {
9861     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9862     const SDValue &OldBaseAddr = Origin->getBasePtr();
9863     SDValue BaseAddr = OldBaseAddr;
9864     // Get the offset in that chunk of bytes w.r.t. the endianess.
9865     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9866     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9867     if (Offset) {
9868       // BaseAddr = BaseAddr + Offset.
9869       EVT ArithType = BaseAddr.getValueType();
9870       SDLoc DL(Origin);
9871       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9872                               DAG->getConstant(Offset, DL, ArithType));
9873     }
9874
9875     // Create the type of the loaded slice according to its size.
9876     EVT SliceType = getLoadedType();
9877
9878     // Create the load for the slice.
9879     SDValue LastInst = DAG->getLoad(
9880         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9881         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9882         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9883     // If the final type is not the same as the loaded type, this means that
9884     // we have to pad with zero. Create a zero extend for that.
9885     EVT FinalType = Inst->getValueType(0);
9886     if (SliceType != FinalType)
9887       LastInst =
9888           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9889     return LastInst;
9890   }
9891
9892   /// \brief Check if this slice can be merged with an expensive cross register
9893   /// bank copy. E.g.,
9894   /// i = load i32
9895   /// f = bitcast i32 i to float
9896   bool canMergeExpensiveCrossRegisterBankCopy() const {
9897     if (!Inst || !Inst->hasOneUse())
9898       return false;
9899     SDNode *Use = *Inst->use_begin();
9900     if (Use->getOpcode() != ISD::BITCAST)
9901       return false;
9902     assert(DAG && "Missing context");
9903     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9904     EVT ResVT = Use->getValueType(0);
9905     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9906     const TargetRegisterClass *ArgRC =
9907         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9908     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9909       return false;
9910
9911     // At this point, we know that we perform a cross-register-bank copy.
9912     // Check if it is expensive.
9913     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9914     // Assume bitcasts are cheap, unless both register classes do not
9915     // explicitly share a common sub class.
9916     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9917       return false;
9918
9919     // Check if it will be merged with the load.
9920     // 1. Check the alignment constraint.
9921     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9922         ResVT.getTypeForEVT(*DAG->getContext()));
9923
9924     if (RequiredAlignment > getAlignment())
9925       return false;
9926
9927     // 2. Check that the load is a legal operation for that type.
9928     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9929       return false;
9930
9931     // 3. Check that we do not have a zext in the way.
9932     if (Inst->getValueType(0) != getLoadedType())
9933       return false;
9934
9935     return true;
9936   }
9937 };
9938 }
9939
9940 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9941 /// \p UsedBits looks like 0..0 1..1 0..0.
9942 static bool areUsedBitsDense(const APInt &UsedBits) {
9943   // If all the bits are one, this is dense!
9944   if (UsedBits.isAllOnesValue())
9945     return true;
9946
9947   // Get rid of the unused bits on the right.
9948   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9949   // Get rid of the unused bits on the left.
9950   if (NarrowedUsedBits.countLeadingZeros())
9951     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9952   // Check that the chunk of bits is completely used.
9953   return NarrowedUsedBits.isAllOnesValue();
9954 }
9955
9956 /// \brief Check whether or not \p First and \p Second are next to each other
9957 /// in memory. This means that there is no hole between the bits loaded
9958 /// by \p First and the bits loaded by \p Second.
9959 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9960                                      const LoadedSlice &Second) {
9961   assert(First.Origin == Second.Origin && First.Origin &&
9962          "Unable to match different memory origins.");
9963   APInt UsedBits = First.getUsedBits();
9964   assert((UsedBits & Second.getUsedBits()) == 0 &&
9965          "Slices are not supposed to overlap.");
9966   UsedBits |= Second.getUsedBits();
9967   return areUsedBitsDense(UsedBits);
9968 }
9969
9970 /// \brief Adjust the \p GlobalLSCost according to the target
9971 /// paring capabilities and the layout of the slices.
9972 /// \pre \p GlobalLSCost should account for at least as many loads as
9973 /// there is in the slices in \p LoadedSlices.
9974 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9975                                  LoadedSlice::Cost &GlobalLSCost) {
9976   unsigned NumberOfSlices = LoadedSlices.size();
9977   // If there is less than 2 elements, no pairing is possible.
9978   if (NumberOfSlices < 2)
9979     return;
9980
9981   // Sort the slices so that elements that are likely to be next to each
9982   // other in memory are next to each other in the list.
9983   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9984             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9985     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9986     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9987   });
9988   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9989   // First (resp. Second) is the first (resp. Second) potentially candidate
9990   // to be placed in a paired load.
9991   const LoadedSlice *First = nullptr;
9992   const LoadedSlice *Second = nullptr;
9993   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9994                 // Set the beginning of the pair.
9995                                                            First = Second) {
9996
9997     Second = &LoadedSlices[CurrSlice];
9998
9999     // If First is NULL, it means we start a new pair.
10000     // Get to the next slice.
10001     if (!First)
10002       continue;
10003
10004     EVT LoadedType = First->getLoadedType();
10005
10006     // If the types of the slices are different, we cannot pair them.
10007     if (LoadedType != Second->getLoadedType())
10008       continue;
10009
10010     // Check if the target supplies paired loads for this type.
10011     unsigned RequiredAlignment = 0;
10012     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10013       // move to the next pair, this type is hopeless.
10014       Second = nullptr;
10015       continue;
10016     }
10017     // Check if we meet the alignment requirement.
10018     if (RequiredAlignment > First->getAlignment())
10019       continue;
10020
10021     // Check that both loads are next to each other in memory.
10022     if (!areSlicesNextToEachOther(*First, *Second))
10023       continue;
10024
10025     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10026     --GlobalLSCost.Loads;
10027     // Move to the next pair.
10028     Second = nullptr;
10029   }
10030 }
10031
10032 /// \brief Check the profitability of all involved LoadedSlice.
10033 /// Currently, it is considered profitable if there is exactly two
10034 /// involved slices (1) which are (2) next to each other in memory, and
10035 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10036 ///
10037 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10038 /// the elements themselves.
10039 ///
10040 /// FIXME: When the cost model will be mature enough, we can relax
10041 /// constraints (1) and (2).
10042 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10043                                 const APInt &UsedBits, bool ForCodeSize) {
10044   unsigned NumberOfSlices = LoadedSlices.size();
10045   if (StressLoadSlicing)
10046     return NumberOfSlices > 1;
10047
10048   // Check (1).
10049   if (NumberOfSlices != 2)
10050     return false;
10051
10052   // Check (2).
10053   if (!areUsedBitsDense(UsedBits))
10054     return false;
10055
10056   // Check (3).
10057   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10058   // The original code has one big load.
10059   OrigCost.Loads = 1;
10060   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10061     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10062     // Accumulate the cost of all the slices.
10063     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10064     GlobalSlicingCost += SliceCost;
10065
10066     // Account as cost in the original configuration the gain obtained
10067     // with the current slices.
10068     OrigCost.addSliceGain(LS);
10069   }
10070
10071   // If the target supports paired load, adjust the cost accordingly.
10072   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10073   return OrigCost > GlobalSlicingCost;
10074 }
10075
10076 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10077 /// operations, split it in the various pieces being extracted.
10078 ///
10079 /// This sort of thing is introduced by SROA.
10080 /// This slicing takes care not to insert overlapping loads.
10081 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10082 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10083   if (Level < AfterLegalizeDAG)
10084     return false;
10085
10086   LoadSDNode *LD = cast<LoadSDNode>(N);
10087   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10088       !LD->getValueType(0).isInteger())
10089     return false;
10090
10091   // Keep track of already used bits to detect overlapping values.
10092   // In that case, we will just abort the transformation.
10093   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10094
10095   SmallVector<LoadedSlice, 4> LoadedSlices;
10096
10097   // Check if this load is used as several smaller chunks of bits.
10098   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10099   // of computation for each trunc.
10100   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10101        UI != UIEnd; ++UI) {
10102     // Skip the uses of the chain.
10103     if (UI.getUse().getResNo() != 0)
10104       continue;
10105
10106     SDNode *User = *UI;
10107     unsigned Shift = 0;
10108
10109     // Check if this is a trunc(lshr).
10110     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10111         isa<ConstantSDNode>(User->getOperand(1))) {
10112       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10113       User = *User->use_begin();
10114     }
10115
10116     // At this point, User is a Truncate, iff we encountered, trunc or
10117     // trunc(lshr).
10118     if (User->getOpcode() != ISD::TRUNCATE)
10119       return false;
10120
10121     // The width of the type must be a power of 2 and greater than 8-bits.
10122     // Otherwise the load cannot be represented in LLVM IR.
10123     // Moreover, if we shifted with a non-8-bits multiple, the slice
10124     // will be across several bytes. We do not support that.
10125     unsigned Width = User->getValueSizeInBits(0);
10126     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10127       return 0;
10128
10129     // Build the slice for this chain of computations.
10130     LoadedSlice LS(User, LD, Shift, &DAG);
10131     APInt CurrentUsedBits = LS.getUsedBits();
10132
10133     // Check if this slice overlaps with another.
10134     if ((CurrentUsedBits & UsedBits) != 0)
10135       return false;
10136     // Update the bits used globally.
10137     UsedBits |= CurrentUsedBits;
10138
10139     // Check if the new slice would be legal.
10140     if (!LS.isLegal())
10141       return false;
10142
10143     // Record the slice.
10144     LoadedSlices.push_back(LS);
10145   }
10146
10147   // Abort slicing if it does not seem to be profitable.
10148   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10149     return false;
10150
10151   ++SlicedLoads;
10152
10153   // Rewrite each chain to use an independent load.
10154   // By construction, each chain can be represented by a unique load.
10155
10156   // Prepare the argument for the new token factor for all the slices.
10157   SmallVector<SDValue, 8> ArgChains;
10158   for (SmallVectorImpl<LoadedSlice>::const_iterator
10159            LSIt = LoadedSlices.begin(),
10160            LSItEnd = LoadedSlices.end();
10161        LSIt != LSItEnd; ++LSIt) {
10162     SDValue SliceInst = LSIt->loadSlice();
10163     CombineTo(LSIt->Inst, SliceInst, true);
10164     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10165       SliceInst = SliceInst.getOperand(0);
10166     assert(SliceInst->getOpcode() == ISD::LOAD &&
10167            "It takes more than a zext to get to the loaded slice!!");
10168     ArgChains.push_back(SliceInst.getValue(1));
10169   }
10170
10171   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10172                               ArgChains);
10173   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10174   return true;
10175 }
10176
10177 /// Check to see if V is (and load (ptr), imm), where the load is having
10178 /// specific bytes cleared out.  If so, return the byte size being masked out
10179 /// and the shift amount.
10180 static std::pair<unsigned, unsigned>
10181 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10182   std::pair<unsigned, unsigned> Result(0, 0);
10183
10184   // Check for the structure we're looking for.
10185   if (V->getOpcode() != ISD::AND ||
10186       !isa<ConstantSDNode>(V->getOperand(1)) ||
10187       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10188     return Result;
10189
10190   // Check the chain and pointer.
10191   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10192   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10193
10194   // The store should be chained directly to the load or be an operand of a
10195   // tokenfactor.
10196   if (LD == Chain.getNode())
10197     ; // ok.
10198   else if (Chain->getOpcode() != ISD::TokenFactor)
10199     return Result; // Fail.
10200   else {
10201     bool isOk = false;
10202     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10203       if (Chain->getOperand(i).getNode() == LD) {
10204         isOk = true;
10205         break;
10206       }
10207     if (!isOk) return Result;
10208   }
10209
10210   // This only handles simple types.
10211   if (V.getValueType() != MVT::i16 &&
10212       V.getValueType() != MVT::i32 &&
10213       V.getValueType() != MVT::i64)
10214     return Result;
10215
10216   // Check the constant mask.  Invert it so that the bits being masked out are
10217   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10218   // follow the sign bit for uniformity.
10219   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10220   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10221   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10222   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10223   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10224   if (NotMaskLZ == 64) return Result;  // All zero mask.
10225
10226   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10227   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10228     return Result;
10229
10230   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10231   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10232     NotMaskLZ -= 64-V.getValueSizeInBits();
10233
10234   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10235   switch (MaskedBytes) {
10236   case 1:
10237   case 2:
10238   case 4: break;
10239   default: return Result; // All one mask, or 5-byte mask.
10240   }
10241
10242   // Verify that the first bit starts at a multiple of mask so that the access
10243   // is aligned the same as the access width.
10244   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10245
10246   Result.first = MaskedBytes;
10247   Result.second = NotMaskTZ/8;
10248   return Result;
10249 }
10250
10251
10252 /// Check to see if IVal is something that provides a value as specified by
10253 /// MaskInfo. If so, replace the specified store with a narrower store of
10254 /// truncated IVal.
10255 static SDNode *
10256 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10257                                 SDValue IVal, StoreSDNode *St,
10258                                 DAGCombiner *DC) {
10259   unsigned NumBytes = MaskInfo.first;
10260   unsigned ByteShift = MaskInfo.second;
10261   SelectionDAG &DAG = DC->getDAG();
10262
10263   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10264   // that uses this.  If not, this is not a replacement.
10265   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10266                                   ByteShift*8, (ByteShift+NumBytes)*8);
10267   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10268
10269   // Check that it is legal on the target to do this.  It is legal if the new
10270   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10271   // legalization.
10272   MVT VT = MVT::getIntegerVT(NumBytes*8);
10273   if (!DC->isTypeLegal(VT))
10274     return nullptr;
10275
10276   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10277   // shifted by ByteShift and truncated down to NumBytes.
10278   if (ByteShift) {
10279     SDLoc DL(IVal);
10280     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10281                        DAG.getConstant(ByteShift*8, DL,
10282                                     DC->getShiftAmountTy(IVal.getValueType())));
10283   }
10284
10285   // Figure out the offset for the store and the alignment of the access.
10286   unsigned StOffset;
10287   unsigned NewAlign = St->getAlignment();
10288
10289   if (DAG.getTargetLoweringInfo().isLittleEndian())
10290     StOffset = ByteShift;
10291   else
10292     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10293
10294   SDValue Ptr = St->getBasePtr();
10295   if (StOffset) {
10296     SDLoc DL(IVal);
10297     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10298                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10299     NewAlign = MinAlign(NewAlign, StOffset);
10300   }
10301
10302   // Truncate down to the new size.
10303   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10304
10305   ++OpsNarrowed;
10306   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10307                       St->getPointerInfo().getWithOffset(StOffset),
10308                       false, false, NewAlign).getNode();
10309 }
10310
10311
10312 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10313 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10314 /// narrowing the load and store if it would end up being a win for performance
10315 /// or code size.
10316 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10317   StoreSDNode *ST  = cast<StoreSDNode>(N);
10318   if (ST->isVolatile())
10319     return SDValue();
10320
10321   SDValue Chain = ST->getChain();
10322   SDValue Value = ST->getValue();
10323   SDValue Ptr   = ST->getBasePtr();
10324   EVT VT = Value.getValueType();
10325
10326   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10327     return SDValue();
10328
10329   unsigned Opc = Value.getOpcode();
10330
10331   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10332   // is a byte mask indicating a consecutive number of bytes, check to see if
10333   // Y is known to provide just those bytes.  If so, we try to replace the
10334   // load + replace + store sequence with a single (narrower) store, which makes
10335   // the load dead.
10336   if (Opc == ISD::OR) {
10337     std::pair<unsigned, unsigned> MaskedLoad;
10338     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10339     if (MaskedLoad.first)
10340       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10341                                                   Value.getOperand(1), ST,this))
10342         return SDValue(NewST, 0);
10343
10344     // Or is commutative, so try swapping X and Y.
10345     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10346     if (MaskedLoad.first)
10347       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10348                                                   Value.getOperand(0), ST,this))
10349         return SDValue(NewST, 0);
10350   }
10351
10352   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10353       Value.getOperand(1).getOpcode() != ISD::Constant)
10354     return SDValue();
10355
10356   SDValue N0 = Value.getOperand(0);
10357   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10358       Chain == SDValue(N0.getNode(), 1)) {
10359     LoadSDNode *LD = cast<LoadSDNode>(N0);
10360     if (LD->getBasePtr() != Ptr ||
10361         LD->getPointerInfo().getAddrSpace() !=
10362         ST->getPointerInfo().getAddrSpace())
10363       return SDValue();
10364
10365     // Find the type to narrow it the load / op / store to.
10366     SDValue N1 = Value.getOperand(1);
10367     unsigned BitWidth = N1.getValueSizeInBits();
10368     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10369     if (Opc == ISD::AND)
10370       Imm ^= APInt::getAllOnesValue(BitWidth);
10371     if (Imm == 0 || Imm.isAllOnesValue())
10372       return SDValue();
10373     unsigned ShAmt = Imm.countTrailingZeros();
10374     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10375     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10376     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10377     // The narrowing should be profitable, the load/store operation should be
10378     // legal (or custom) and the store size should be equal to the NewVT width.
10379     while (NewBW < BitWidth &&
10380            (NewVT.getStoreSizeInBits() != NewBW ||
10381             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10382             !TLI.isNarrowingProfitable(VT, NewVT))) {
10383       NewBW = NextPowerOf2(NewBW);
10384       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10385     }
10386     if (NewBW >= BitWidth)
10387       return SDValue();
10388
10389     // If the lsb changed does not start at the type bitwidth boundary,
10390     // start at the previous one.
10391     if (ShAmt % NewBW)
10392       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10393     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10394                                    std::min(BitWidth, ShAmt + NewBW));
10395     if ((Imm & Mask) == Imm) {
10396       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10397       if (Opc == ISD::AND)
10398         NewImm ^= APInt::getAllOnesValue(NewBW);
10399       uint64_t PtrOff = ShAmt / 8;
10400       // For big endian targets, we need to adjust the offset to the pointer to
10401       // load the correct bytes.
10402       if (TLI.isBigEndian())
10403         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10404
10405       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10406       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10407       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10408         return SDValue();
10409
10410       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10411                                    Ptr.getValueType(), Ptr,
10412                                    DAG.getConstant(PtrOff, SDLoc(LD),
10413                                                    Ptr.getValueType()));
10414       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10415                                   LD->getChain(), NewPtr,
10416                                   LD->getPointerInfo().getWithOffset(PtrOff),
10417                                   LD->isVolatile(), LD->isNonTemporal(),
10418                                   LD->isInvariant(), NewAlign,
10419                                   LD->getAAInfo());
10420       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10421                                    DAG.getConstant(NewImm, SDLoc(Value),
10422                                                    NewVT));
10423       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10424                                    NewVal, NewPtr,
10425                                    ST->getPointerInfo().getWithOffset(PtrOff),
10426                                    false, false, NewAlign);
10427
10428       AddToWorklist(NewPtr.getNode());
10429       AddToWorklist(NewLD.getNode());
10430       AddToWorklist(NewVal.getNode());
10431       WorklistRemover DeadNodes(*this);
10432       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10433       ++OpsNarrowed;
10434       return NewST;
10435     }
10436   }
10437
10438   return SDValue();
10439 }
10440
10441 /// For a given floating point load / store pair, if the load value isn't used
10442 /// by any other operations, then consider transforming the pair to integer
10443 /// load / store operations if the target deems the transformation profitable.
10444 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10445   StoreSDNode *ST  = cast<StoreSDNode>(N);
10446   SDValue Chain = ST->getChain();
10447   SDValue Value = ST->getValue();
10448   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10449       Value.hasOneUse() &&
10450       Chain == SDValue(Value.getNode(), 1)) {
10451     LoadSDNode *LD = cast<LoadSDNode>(Value);
10452     EVT VT = LD->getMemoryVT();
10453     if (!VT.isFloatingPoint() ||
10454         VT != ST->getMemoryVT() ||
10455         LD->isNonTemporal() ||
10456         ST->isNonTemporal() ||
10457         LD->getPointerInfo().getAddrSpace() != 0 ||
10458         ST->getPointerInfo().getAddrSpace() != 0)
10459       return SDValue();
10460
10461     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10462     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10463         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10464         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10465         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10466       return SDValue();
10467
10468     unsigned LDAlign = LD->getAlignment();
10469     unsigned STAlign = ST->getAlignment();
10470     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10471     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10472     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10473       return SDValue();
10474
10475     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10476                                 LD->getChain(), LD->getBasePtr(),
10477                                 LD->getPointerInfo(),
10478                                 false, false, false, LDAlign);
10479
10480     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10481                                  NewLD, ST->getBasePtr(),
10482                                  ST->getPointerInfo(),
10483                                  false, false, STAlign);
10484
10485     AddToWorklist(NewLD.getNode());
10486     AddToWorklist(NewST.getNode());
10487     WorklistRemover DeadNodes(*this);
10488     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10489     ++LdStFP2Int;
10490     return NewST;
10491   }
10492
10493   return SDValue();
10494 }
10495
10496 namespace {
10497 /// Helper struct to parse and store a memory address as base + index + offset.
10498 /// We ignore sign extensions when it is safe to do so.
10499 /// The following two expressions are not equivalent. To differentiate we need
10500 /// to store whether there was a sign extension involved in the index
10501 /// computation.
10502 ///  (load (i64 add (i64 copyfromreg %c)
10503 ///                 (i64 signextend (add (i8 load %index)
10504 ///                                      (i8 1))))
10505 /// vs
10506 ///
10507 /// (load (i64 add (i64 copyfromreg %c)
10508 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10509 ///                                         (i32 1)))))
10510 struct BaseIndexOffset {
10511   SDValue Base;
10512   SDValue Index;
10513   int64_t Offset;
10514   bool IsIndexSignExt;
10515
10516   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10517
10518   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10519                   bool IsIndexSignExt) :
10520     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10521
10522   bool equalBaseIndex(const BaseIndexOffset &Other) {
10523     return Other.Base == Base && Other.Index == Index &&
10524       Other.IsIndexSignExt == IsIndexSignExt;
10525   }
10526
10527   /// Parses tree in Ptr for base, index, offset addresses.
10528   static BaseIndexOffset match(SDValue Ptr) {
10529     bool IsIndexSignExt = false;
10530
10531     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10532     // instruction, then it could be just the BASE or everything else we don't
10533     // know how to handle. Just use Ptr as BASE and give up.
10534     if (Ptr->getOpcode() != ISD::ADD)
10535       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10536
10537     // We know that we have at least an ADD instruction. Try to pattern match
10538     // the simple case of BASE + OFFSET.
10539     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10540       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10541       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10542                               IsIndexSignExt);
10543     }
10544
10545     // Inside a loop the current BASE pointer is calculated using an ADD and a
10546     // MUL instruction. In this case Ptr is the actual BASE pointer.
10547     // (i64 add (i64 %array_ptr)
10548     //          (i64 mul (i64 %induction_var)
10549     //                   (i64 %element_size)))
10550     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10551       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10552
10553     // Look at Base + Index + Offset cases.
10554     SDValue Base = Ptr->getOperand(0);
10555     SDValue IndexOffset = Ptr->getOperand(1);
10556
10557     // Skip signextends.
10558     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10559       IndexOffset = IndexOffset->getOperand(0);
10560       IsIndexSignExt = true;
10561     }
10562
10563     // Either the case of Base + Index (no offset) or something else.
10564     if (IndexOffset->getOpcode() != ISD::ADD)
10565       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10566
10567     // Now we have the case of Base + Index + offset.
10568     SDValue Index = IndexOffset->getOperand(0);
10569     SDValue Offset = IndexOffset->getOperand(1);
10570
10571     if (!isa<ConstantSDNode>(Offset))
10572       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10573
10574     // Ignore signextends.
10575     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10576       Index = Index->getOperand(0);
10577       IsIndexSignExt = true;
10578     } else IsIndexSignExt = false;
10579
10580     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10581     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10582   }
10583 };
10584 } // namespace
10585
10586 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10587                                                   SDLoc SL,
10588                                                   ArrayRef<MemOpLink> Stores,
10589                                                   EVT Ty) const {
10590   SmallVector<SDValue, 8> BuildVector;
10591
10592   for (const MemOpLink &Store : Stores)
10593     BuildVector.push_back(cast<StoreSDNode>(Store.MemNode)->getValue());
10594   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10595 }
10596
10597 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10598                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10599                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10600   // Make sure we have something to merge.
10601   if (NumElem < 2)
10602     return false;
10603
10604   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10605   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10606   unsigned LatestNodeUsed = 0;
10607
10608   for (unsigned i=0; i < NumElem; ++i) {
10609     // Find a chain for the new wide-store operand. Notice that some
10610     // of the store nodes that we found may not be selected for inclusion
10611     // in the wide store. The chain we use needs to be the chain of the
10612     // latest store node which is *used* and replaced by the wide store.
10613     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10614       LatestNodeUsed = i;
10615   }
10616
10617   // The latest Node in the DAG.
10618   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10619   SDLoc DL(StoreNodes[0].MemNode);
10620
10621   SDValue StoredVal;
10622   if (UseVector) {
10623     // Find a legal type for the vector store.
10624     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10625     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10626     if (IsConstantSrc) {
10627       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10628     } else {
10629       SmallVector<SDValue, 8> Ops;
10630       for (unsigned i = 0; i < NumElem ; ++i) {
10631         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10632         SDValue Val = St->getValue();
10633         // All of the operands of a BUILD_VECTOR must have the same type.
10634         if (Val.getValueType() != MemVT)
10635           return false;
10636         Ops.push_back(Val);
10637       }
10638
10639       // Build the extracted vector elements back into a vector.
10640       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10641     }
10642   } else {
10643     // We should always use a vector store when merging extracted vector
10644     // elements, so this path implies a store of constants.
10645     assert(IsConstantSrc && "Merged vector elements should use vector store");
10646
10647     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10648     APInt StoreInt(StoreBW, 0);
10649
10650     // Construct a single integer constant which is made of the smaller
10651     // constant inputs.
10652     bool IsLE = TLI.isLittleEndian();
10653     for (unsigned i = 0; i < NumElem ; ++i) {
10654       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10655       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10656       SDValue Val = St->getValue();
10657       StoreInt <<= ElementSizeBytes*8;
10658       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10659         StoreInt |= C->getAPIntValue().zext(StoreBW);
10660       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10661         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10662       } else {
10663         llvm_unreachable("Invalid constant element type");
10664       }
10665     }
10666
10667     // Create the new Load and Store operations.
10668     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10669     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10670   }
10671
10672   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10673                                   FirstInChain->getBasePtr(),
10674                                   FirstInChain->getPointerInfo(),
10675                                   false, false,
10676                                   FirstInChain->getAlignment());
10677
10678   // Replace the last store with the new store
10679   CombineTo(LatestOp, NewStore);
10680   // Erase all other stores.
10681   for (unsigned i = 0; i < NumElem ; ++i) {
10682     if (StoreNodes[i].MemNode == LatestOp)
10683       continue;
10684     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10685     // ReplaceAllUsesWith will replace all uses that existed when it was
10686     // called, but graph optimizations may cause new ones to appear. For
10687     // example, the case in pr14333 looks like
10688     //
10689     //  St's chain -> St -> another store -> X
10690     //
10691     // And the only difference from St to the other store is the chain.
10692     // When we change it's chain to be St's chain they become identical,
10693     // get CSEed and the net result is that X is now a use of St.
10694     // Since we know that St is redundant, just iterate.
10695     while (!St->use_empty())
10696       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10697     deleteAndRecombine(St);
10698   }
10699
10700   return true;
10701 }
10702
10703 static bool allowableAlignment(const SelectionDAG &DAG,
10704                                const TargetLowering &TLI, EVT EVTTy,
10705                                unsigned AS, unsigned Align) {
10706   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10707     return true;
10708
10709   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10710   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10711   return (Align >= ABIAlignment);
10712 }
10713
10714 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10715   if (OptLevel == CodeGenOpt::None)
10716     return false;
10717
10718   EVT MemVT = St->getMemoryVT();
10719   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10720   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10721       Attribute::NoImplicitFloat);
10722
10723   // This function cannot currently deal with non-byte-sized memory sizes.
10724   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10725     return false;
10726
10727   // Don't merge vectors into wider inputs.
10728   if (MemVT.isVector() || !MemVT.isSimple())
10729     return false;
10730
10731   // Perform an early exit check. Do not bother looking at stored values that
10732   // are not constants, loads, or extracted vector elements.
10733   SDValue StoredVal = St->getValue();
10734   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10735   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10736                        isa<ConstantFPSDNode>(StoredVal);
10737   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10738
10739   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10740     return false;
10741
10742   // Only look at ends of store sequences.
10743   SDValue Chain = SDValue(St, 0);
10744   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10745     return false;
10746
10747   // This holds the base pointer, index, and the offset in bytes from the base
10748   // pointer.
10749   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10750
10751   // We must have a base and an offset.
10752   if (!BasePtr.Base.getNode())
10753     return false;
10754
10755   // Do not handle stores to undef base pointers.
10756   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10757     return false;
10758
10759   // Save the LoadSDNodes that we find in the chain.
10760   // We need to make sure that these nodes do not interfere with
10761   // any of the store nodes.
10762   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10763
10764   // Save the StoreSDNodes that we find in the chain.
10765   SmallVector<MemOpLink, 8> StoreNodes;
10766
10767   // Walk up the chain and look for nodes with offsets from the same
10768   // base pointer. Stop when reaching an instruction with a different kind
10769   // or instruction which has a different base pointer.
10770   unsigned Seq = 0;
10771   StoreSDNode *Index = St;
10772   while (Index) {
10773     // If the chain has more than one use, then we can't reorder the mem ops.
10774     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10775       break;
10776
10777     // Find the base pointer and offset for this memory node.
10778     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10779
10780     // Check that the base pointer is the same as the original one.
10781     if (!Ptr.equalBaseIndex(BasePtr))
10782       break;
10783
10784     // The memory operands must not be volatile.
10785     if (Index->isVolatile() || Index->isIndexed())
10786       break;
10787
10788     // No truncation.
10789     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10790       if (St->isTruncatingStore())
10791         break;
10792
10793     // The stored memory type must be the same.
10794     if (Index->getMemoryVT() != MemVT)
10795       break;
10796
10797     // We found a potential memory operand to merge.
10798     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10799
10800     // Find the next memory operand in the chain. If the next operand in the
10801     // chain is a store then move up and continue the scan with the next
10802     // memory operand. If the next operand is a load save it and use alias
10803     // information to check if it interferes with anything.
10804     SDNode *NextInChain = Index->getChain().getNode();
10805     while (1) {
10806       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10807         // We found a store node. Use it for the next iteration.
10808         Index = STn;
10809         break;
10810       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10811         if (Ldn->isVolatile()) {
10812           Index = nullptr;
10813           break;
10814         }
10815
10816         // Save the load node for later. Continue the scan.
10817         AliasLoadNodes.push_back(Ldn);
10818         NextInChain = Ldn->getChain().getNode();
10819         continue;
10820       } else {
10821         Index = nullptr;
10822         break;
10823       }
10824     }
10825   }
10826
10827   // Check if there is anything to merge.
10828   if (StoreNodes.size() < 2)
10829     return false;
10830
10831   // Sort the memory operands according to their distance from the base pointer.
10832   std::sort(StoreNodes.begin(), StoreNodes.end(),
10833             [](MemOpLink LHS, MemOpLink RHS) {
10834     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10835            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10836             LHS.SequenceNum > RHS.SequenceNum);
10837   });
10838
10839   // Scan the memory operations on the chain and find the first non-consecutive
10840   // store memory address.
10841   unsigned LastConsecutiveStore = 0;
10842   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10843   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10844
10845     // Check that the addresses are consecutive starting from the second
10846     // element in the list of stores.
10847     if (i > 0) {
10848       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10849       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10850         break;
10851     }
10852
10853     bool Alias = false;
10854     // Check if this store interferes with any of the loads that we found.
10855     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10856       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10857         Alias = true;
10858         break;
10859       }
10860     // We found a load that alias with this store. Stop the sequence.
10861     if (Alias)
10862       break;
10863
10864     // Mark this node as useful.
10865     LastConsecutiveStore = i;
10866   }
10867
10868   // The node with the lowest store address.
10869   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10870   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10871   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10872
10873   // Store the constants into memory as one consecutive store.
10874   if (IsConstantSrc) {
10875     unsigned LastLegalType = 0;
10876     unsigned LastLegalVectorType = 0;
10877     bool NonZero = false;
10878     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10879       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10880       SDValue StoredVal = St->getValue();
10881
10882       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10883         NonZero |= !C->isNullValue();
10884       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10885         NonZero |= !C->getConstantFPValue()->isNullValue();
10886       } else {
10887         // Non-constant.
10888         break;
10889       }
10890
10891       // Find a legal type for the constant store.
10892       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10893       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10894       if (TLI.isTypeLegal(StoreTy) &&
10895           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10896                              FirstStoreAlign)) {
10897         LastLegalType = i+1;
10898       // Or check whether a truncstore is legal.
10899       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10900                  TargetLowering::TypePromoteInteger) {
10901         EVT LegalizedStoredValueTy =
10902           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10903         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10904             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10905                                FirstStoreAlign)) {
10906           LastLegalType = i + 1;
10907         }
10908       }
10909
10910       // Find a legal type for the vector store.
10911       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10912       if (TLI.isTypeLegal(Ty) &&
10913           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10914         LastLegalVectorType = i + 1;
10915       }
10916     }
10917
10918
10919     // We only use vectors if the constant is known to be zero or the target
10920     // allows it and the function is not marked with the noimplicitfloat
10921     // attribute.
10922     if (NoVectors) {
10923       LastLegalVectorType = 0;
10924     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10925                                                             LastLegalVectorType,
10926                                                             FirstStoreAS)) {
10927       LastLegalVectorType = 0;
10928     }
10929
10930     // Check if we found a legal integer type to store.
10931     if (LastLegalType == 0 && LastLegalVectorType == 0)
10932       return false;
10933
10934     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10935     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10936
10937     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10938                                            true, UseVector);
10939   }
10940
10941   // When extracting multiple vector elements, try to store them
10942   // in one vector store rather than a sequence of scalar stores.
10943   if (IsExtractVecEltSrc) {
10944     unsigned NumElem = 0;
10945     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10946       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10947       SDValue StoredVal = St->getValue();
10948       // This restriction could be loosened.
10949       // Bail out if any stored values are not elements extracted from a vector.
10950       // It should be possible to handle mixed sources, but load sources need
10951       // more careful handling (see the block of code below that handles
10952       // consecutive loads).
10953       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10954         return false;
10955
10956       // Find a legal type for the vector store.
10957       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10958       if (TLI.isTypeLegal(Ty) &&
10959           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10960         NumElem = i + 1;
10961     }
10962
10963     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10964                                            false, true);
10965   }
10966
10967   // Below we handle the case of multiple consecutive stores that
10968   // come from multiple consecutive loads. We merge them into a single
10969   // wide load and a single wide store.
10970
10971   // Look for load nodes which are used by the stored values.
10972   SmallVector<MemOpLink, 8> LoadNodes;
10973
10974   // Find acceptable loads. Loads need to have the same chain (token factor),
10975   // must not be zext, volatile, indexed, and they must be consecutive.
10976   BaseIndexOffset LdBasePtr;
10977   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10978     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10979     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10980     if (!Ld) break;
10981
10982     // Loads must only have one use.
10983     if (!Ld->hasNUsesOfValue(1, 0))
10984       break;
10985
10986     // The memory operands must not be volatile.
10987     if (Ld->isVolatile() || Ld->isIndexed())
10988       break;
10989
10990     // We do not accept ext loads.
10991     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10992       break;
10993
10994     // The stored memory type must be the same.
10995     if (Ld->getMemoryVT() != MemVT)
10996       break;
10997
10998     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10999     // If this is not the first ptr that we check.
11000     if (LdBasePtr.Base.getNode()) {
11001       // The base ptr must be the same.
11002       if (!LdPtr.equalBaseIndex(LdBasePtr))
11003         break;
11004     } else {
11005       // Check that all other base pointers are the same as this one.
11006       LdBasePtr = LdPtr;
11007     }
11008
11009     // We found a potential memory operand to merge.
11010     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11011   }
11012
11013   if (LoadNodes.size() < 2)
11014     return false;
11015
11016   // If we have load/store pair instructions and we only have two values,
11017   // don't bother.
11018   unsigned RequiredAlignment;
11019   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11020       St->getAlignment() >= RequiredAlignment)
11021     return false;
11022
11023   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11024   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11025   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11026
11027   // Scan the memory operations on the chain and find the first non-consecutive
11028   // load memory address. These variables hold the index in the store node
11029   // array.
11030   unsigned LastConsecutiveLoad = 0;
11031   // This variable refers to the size and not index in the array.
11032   unsigned LastLegalVectorType = 0;
11033   unsigned LastLegalIntegerType = 0;
11034   StartAddress = LoadNodes[0].OffsetFromBase;
11035   SDValue FirstChain = FirstLoad->getChain();
11036   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11037     // All loads much share the same chain.
11038     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11039       break;
11040
11041     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11042     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11043       break;
11044     LastConsecutiveLoad = i;
11045
11046     // Find a legal type for the vector store.
11047     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11048     if (TLI.isTypeLegal(StoreTy) &&
11049         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11050         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11051       LastLegalVectorType = i + 1;
11052     }
11053
11054     // Find a legal type for the integer store.
11055     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11056     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11057     if (TLI.isTypeLegal(StoreTy) &&
11058         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11059         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11060       LastLegalIntegerType = i + 1;
11061     // Or check whether a truncstore and extload is legal.
11062     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11063              TargetLowering::TypePromoteInteger) {
11064       EVT LegalizedStoredValueTy =
11065         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11066       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11067           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11068           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11069           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11070           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11071                              FirstStoreAlign) &&
11072           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11073                              FirstLoadAlign))
11074         LastLegalIntegerType = i+1;
11075     }
11076   }
11077
11078   // Only use vector types if the vector type is larger than the integer type.
11079   // If they are the same, use integers.
11080   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11081   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11082
11083   // We add +1 here because the LastXXX variables refer to location while
11084   // the NumElem refers to array/index size.
11085   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11086   NumElem = std::min(LastLegalType, NumElem);
11087
11088   if (NumElem < 2)
11089     return false;
11090
11091   // The latest Node in the DAG.
11092   unsigned LatestNodeUsed = 0;
11093   for (unsigned i=1; i<NumElem; ++i) {
11094     // Find a chain for the new wide-store operand. Notice that some
11095     // of the store nodes that we found may not be selected for inclusion
11096     // in the wide store. The chain we use needs to be the chain of the
11097     // latest store node which is *used* and replaced by the wide store.
11098     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11099       LatestNodeUsed = i;
11100   }
11101
11102   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11103
11104   // Find if it is better to use vectors or integers to load and store
11105   // to memory.
11106   EVT JointMemOpVT;
11107   if (UseVectorTy) {
11108     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11109   } else {
11110     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11111     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11112   }
11113
11114   SDLoc LoadDL(LoadNodes[0].MemNode);
11115   SDLoc StoreDL(StoreNodes[0].MemNode);
11116
11117   SDValue NewLoad = DAG.getLoad(
11118       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11119       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11120
11121   SDValue NewStore = DAG.getStore(
11122       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11123       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11124
11125   // Replace one of the loads with the new load.
11126   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11127   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11128                                 SDValue(NewLoad.getNode(), 1));
11129
11130   // Remove the rest of the load chains.
11131   for (unsigned i = 1; i < NumElem ; ++i) {
11132     // Replace all chain users of the old load nodes with the chain of the new
11133     // load node.
11134     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11135     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11136   }
11137
11138   // Replace the last store with the new store.
11139   CombineTo(LatestOp, NewStore);
11140   // Erase all other stores.
11141   for (unsigned i = 0; i < NumElem ; ++i) {
11142     // Remove all Store nodes.
11143     if (StoreNodes[i].MemNode == LatestOp)
11144       continue;
11145     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11146     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11147     deleteAndRecombine(St);
11148   }
11149
11150   return true;
11151 }
11152
11153 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11154   StoreSDNode *ST  = cast<StoreSDNode>(N);
11155   SDValue Chain = ST->getChain();
11156   SDValue Value = ST->getValue();
11157   SDValue Ptr   = ST->getBasePtr();
11158
11159   // If this is a store of a bit convert, store the input value if the
11160   // resultant store does not need a higher alignment than the original.
11161   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11162       ST->isUnindexed()) {
11163     unsigned OrigAlign = ST->getAlignment();
11164     EVT SVT = Value.getOperand(0).getValueType();
11165     unsigned Align = TLI.getDataLayout()->
11166       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11167     if (Align <= OrigAlign &&
11168         ((!LegalOperations && !ST->isVolatile()) ||
11169          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11170       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11171                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11172                           ST->isNonTemporal(), OrigAlign,
11173                           ST->getAAInfo());
11174   }
11175
11176   // Turn 'store undef, Ptr' -> nothing.
11177   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11178     return Chain;
11179
11180   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11181   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11182     // NOTE: If the original store is volatile, this transform must not increase
11183     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11184     // processor operation but an i64 (which is not legal) requires two.  So the
11185     // transform should not be done in this case.
11186     if (Value.getOpcode() != ISD::TargetConstantFP) {
11187       SDValue Tmp;
11188       switch (CFP->getSimpleValueType(0).SimpleTy) {
11189       default: llvm_unreachable("Unknown FP type");
11190       case MVT::f16:    // We don't do this for these yet.
11191       case MVT::f80:
11192       case MVT::f128:
11193       case MVT::ppcf128:
11194         break;
11195       case MVT::f32:
11196         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11197             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11198           ;
11199           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11200                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11201                               MVT::i32);
11202           return DAG.getStore(Chain, SDLoc(N), Tmp,
11203                               Ptr, ST->getMemOperand());
11204         }
11205         break;
11206       case MVT::f64:
11207         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11208              !ST->isVolatile()) ||
11209             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11210           ;
11211           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11212                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11213           return DAG.getStore(Chain, SDLoc(N), Tmp,
11214                               Ptr, ST->getMemOperand());
11215         }
11216
11217         if (!ST->isVolatile() &&
11218             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11219           // Many FP stores are not made apparent until after legalize, e.g. for
11220           // argument passing.  Since this is so common, custom legalize the
11221           // 64-bit integer store into two 32-bit stores.
11222           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11223           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11224           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11225           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11226
11227           unsigned Alignment = ST->getAlignment();
11228           bool isVolatile = ST->isVolatile();
11229           bool isNonTemporal = ST->isNonTemporal();
11230           AAMDNodes AAInfo = ST->getAAInfo();
11231
11232           SDLoc DL(N);
11233
11234           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11235                                      Ptr, ST->getPointerInfo(),
11236                                      isVolatile, isNonTemporal,
11237                                      ST->getAlignment(), AAInfo);
11238           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11239                             DAG.getConstant(4, DL, Ptr.getValueType()));
11240           Alignment = MinAlign(Alignment, 4U);
11241           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11242                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11243                                      isVolatile, isNonTemporal,
11244                                      Alignment, AAInfo);
11245           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11246                              St0, St1);
11247         }
11248
11249         break;
11250       }
11251     }
11252   }
11253
11254   // Try to infer better alignment information than the store already has.
11255   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11256     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11257       if (Align > ST->getAlignment()) {
11258         SDValue NewStore =
11259                DAG.getTruncStore(Chain, SDLoc(N), Value,
11260                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11261                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11262                                  ST->getAAInfo());
11263         if (NewStore.getNode() != N)
11264           return CombineTo(ST, NewStore, true);
11265       }
11266     }
11267   }
11268
11269   // Try transforming a pair floating point load / store ops to integer
11270   // load / store ops.
11271   SDValue NewST = TransformFPLoadStorePair(N);
11272   if (NewST.getNode())
11273     return NewST;
11274
11275   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11276                                                   : DAG.getSubtarget().useAA();
11277 #ifndef NDEBUG
11278   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11279       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11280     UseAA = false;
11281 #endif
11282   if (UseAA && ST->isUnindexed()) {
11283     // Walk up chain skipping non-aliasing memory nodes.
11284     SDValue BetterChain = FindBetterChain(N, Chain);
11285
11286     // If there is a better chain.
11287     if (Chain != BetterChain) {
11288       SDValue ReplStore;
11289
11290       // Replace the chain to avoid dependency.
11291       if (ST->isTruncatingStore()) {
11292         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11293                                       ST->getMemoryVT(), ST->getMemOperand());
11294       } else {
11295         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11296                                  ST->getMemOperand());
11297       }
11298
11299       // Create token to keep both nodes around.
11300       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11301                                   MVT::Other, Chain, ReplStore);
11302
11303       // Make sure the new and old chains are cleaned up.
11304       AddToWorklist(Token.getNode());
11305
11306       // Don't add users to work list.
11307       return CombineTo(N, Token, false);
11308     }
11309   }
11310
11311   // Try transforming N to an indexed store.
11312   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11313     return SDValue(N, 0);
11314
11315   // FIXME: is there such a thing as a truncating indexed store?
11316   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11317       Value.getValueType().isInteger()) {
11318     // See if we can simplify the input to this truncstore with knowledge that
11319     // only the low bits are being used.  For example:
11320     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11321     SDValue Shorter =
11322       GetDemandedBits(Value,
11323                       APInt::getLowBitsSet(
11324                         Value.getValueType().getScalarType().getSizeInBits(),
11325                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11326     AddToWorklist(Value.getNode());
11327     if (Shorter.getNode())
11328       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11329                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11330
11331     // Otherwise, see if we can simplify the operation with
11332     // SimplifyDemandedBits, which only works if the value has a single use.
11333     if (SimplifyDemandedBits(Value,
11334                         APInt::getLowBitsSet(
11335                           Value.getValueType().getScalarType().getSizeInBits(),
11336                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11337       return SDValue(N, 0);
11338   }
11339
11340   // If this is a load followed by a store to the same location, then the store
11341   // is dead/noop.
11342   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11343     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11344         ST->isUnindexed() && !ST->isVolatile() &&
11345         // There can't be any side effects between the load and store, such as
11346         // a call or store.
11347         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11348       // The store is dead, remove it.
11349       return Chain;
11350     }
11351   }
11352
11353   // If this is a store followed by a store with the same value to the same
11354   // location, then the store is dead/noop.
11355   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11356     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11357         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11358         ST1->isUnindexed() && !ST1->isVolatile()) {
11359       // The store is dead, remove it.
11360       return Chain;
11361     }
11362   }
11363
11364   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11365   // truncating store.  We can do this even if this is already a truncstore.
11366   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11367       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11368       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11369                             ST->getMemoryVT())) {
11370     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11371                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11372   }
11373
11374   // Only perform this optimization before the types are legal, because we
11375   // don't want to perform this optimization on every DAGCombine invocation.
11376   if (!LegalTypes) {
11377     bool EverChanged = false;
11378
11379     do {
11380       // There can be multiple store sequences on the same chain.
11381       // Keep trying to merge store sequences until we are unable to do so
11382       // or until we merge the last store on the chain.
11383       bool Changed = MergeConsecutiveStores(ST);
11384       EverChanged |= Changed;
11385       if (!Changed) break;
11386     } while (ST->getOpcode() != ISD::DELETED_NODE);
11387
11388     if (EverChanged)
11389       return SDValue(N, 0);
11390   }
11391
11392   return ReduceLoadOpStoreWidth(N);
11393 }
11394
11395 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11396   SDValue InVec = N->getOperand(0);
11397   SDValue InVal = N->getOperand(1);
11398   SDValue EltNo = N->getOperand(2);
11399   SDLoc dl(N);
11400
11401   // If the inserted element is an UNDEF, just use the input vector.
11402   if (InVal.getOpcode() == ISD::UNDEF)
11403     return InVec;
11404
11405   EVT VT = InVec.getValueType();
11406
11407   // If we can't generate a legal BUILD_VECTOR, exit
11408   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11409     return SDValue();
11410
11411   // Check that we know which element is being inserted
11412   if (!isa<ConstantSDNode>(EltNo))
11413     return SDValue();
11414   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11415
11416   // Canonicalize insert_vector_elt dag nodes.
11417   // Example:
11418   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11419   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11420   //
11421   // Do this only if the child insert_vector node has one use; also
11422   // do this only if indices are both constants and Idx1 < Idx0.
11423   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11424       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11425     unsigned OtherElt =
11426       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11427     if (Elt < OtherElt) {
11428       // Swap nodes.
11429       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11430                                   InVec.getOperand(0), InVal, EltNo);
11431       AddToWorklist(NewOp.getNode());
11432       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11433                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11434     }
11435   }
11436
11437   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11438   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11439   // vector elements.
11440   SmallVector<SDValue, 8> Ops;
11441   // Do not combine these two vectors if the output vector will not replace
11442   // the input vector.
11443   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11444     Ops.append(InVec.getNode()->op_begin(),
11445                InVec.getNode()->op_end());
11446   } else if (InVec.getOpcode() == ISD::UNDEF) {
11447     unsigned NElts = VT.getVectorNumElements();
11448     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11449   } else {
11450     return SDValue();
11451   }
11452
11453   // Insert the element
11454   if (Elt < Ops.size()) {
11455     // All the operands of BUILD_VECTOR must have the same type;
11456     // we enforce that here.
11457     EVT OpVT = Ops[0].getValueType();
11458     if (InVal.getValueType() != OpVT)
11459       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11460                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11461                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11462     Ops[Elt] = InVal;
11463   }
11464
11465   // Return the new vector
11466   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11467 }
11468
11469 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11470     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11471   EVT ResultVT = EVE->getValueType(0);
11472   EVT VecEltVT = InVecVT.getVectorElementType();
11473   unsigned Align = OriginalLoad->getAlignment();
11474   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11475       VecEltVT.getTypeForEVT(*DAG.getContext()));
11476
11477   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11478     return SDValue();
11479
11480   Align = NewAlign;
11481
11482   SDValue NewPtr = OriginalLoad->getBasePtr();
11483   SDValue Offset;
11484   EVT PtrType = NewPtr.getValueType();
11485   MachinePointerInfo MPI;
11486   SDLoc DL(EVE);
11487   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11488     int Elt = ConstEltNo->getZExtValue();
11489     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11490     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11491     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11492   } else {
11493     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11494     Offset = DAG.getNode(
11495         ISD::MUL, DL, PtrType, Offset,
11496         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11497     MPI = OriginalLoad->getPointerInfo();
11498   }
11499   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11500
11501   // The replacement we need to do here is a little tricky: we need to
11502   // replace an extractelement of a load with a load.
11503   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11504   // Note that this replacement assumes that the extractvalue is the only
11505   // use of the load; that's okay because we don't want to perform this
11506   // transformation in other cases anyway.
11507   SDValue Load;
11508   SDValue Chain;
11509   if (ResultVT.bitsGT(VecEltVT)) {
11510     // If the result type of vextract is wider than the load, then issue an
11511     // extending load instead.
11512     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11513                                                   VecEltVT)
11514                                    ? ISD::ZEXTLOAD
11515                                    : ISD::EXTLOAD;
11516     Load = DAG.getExtLoad(
11517         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11518         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11519         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11520     Chain = Load.getValue(1);
11521   } else {
11522     Load = DAG.getLoad(
11523         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11524         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11525         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11526     Chain = Load.getValue(1);
11527     if (ResultVT.bitsLT(VecEltVT))
11528       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11529     else
11530       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11531   }
11532   WorklistRemover DeadNodes(*this);
11533   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11534   SDValue To[] = { Load, Chain };
11535   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11536   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11537   // worklist explicitly as well.
11538   AddToWorklist(Load.getNode());
11539   AddUsersToWorklist(Load.getNode()); // Add users too
11540   // Make sure to revisit this node to clean it up; it will usually be dead.
11541   AddToWorklist(EVE);
11542   ++OpsNarrowed;
11543   return SDValue(EVE, 0);
11544 }
11545
11546 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11547   // (vextract (scalar_to_vector val, 0) -> val
11548   SDValue InVec = N->getOperand(0);
11549   EVT VT = InVec.getValueType();
11550   EVT NVT = N->getValueType(0);
11551
11552   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11553     // Check if the result type doesn't match the inserted element type. A
11554     // SCALAR_TO_VECTOR may truncate the inserted element and the
11555     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11556     SDValue InOp = InVec.getOperand(0);
11557     if (InOp.getValueType() != NVT) {
11558       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11559       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11560     }
11561     return InOp;
11562   }
11563
11564   SDValue EltNo = N->getOperand(1);
11565   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11566
11567   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11568   // We only perform this optimization before the op legalization phase because
11569   // we may introduce new vector instructions which are not backed by TD
11570   // patterns. For example on AVX, extracting elements from a wide vector
11571   // without using extract_subvector. However, if we can find an underlying
11572   // scalar value, then we can always use that.
11573   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11574       && ConstEltNo) {
11575     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11576     int NumElem = VT.getVectorNumElements();
11577     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11578     // Find the new index to extract from.
11579     int OrigElt = SVOp->getMaskElt(Elt);
11580
11581     // Extracting an undef index is undef.
11582     if (OrigElt == -1)
11583       return DAG.getUNDEF(NVT);
11584
11585     // Select the right vector half to extract from.
11586     SDValue SVInVec;
11587     if (OrigElt < NumElem) {
11588       SVInVec = InVec->getOperand(0);
11589     } else {
11590       SVInVec = InVec->getOperand(1);
11591       OrigElt -= NumElem;
11592     }
11593
11594     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11595       SDValue InOp = SVInVec.getOperand(OrigElt);
11596       if (InOp.getValueType() != NVT) {
11597         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11598         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11599       }
11600
11601       return InOp;
11602     }
11603
11604     // FIXME: We should handle recursing on other vector shuffles and
11605     // scalar_to_vector here as well.
11606
11607     if (!LegalOperations) {
11608       EVT IndexTy = TLI.getVectorIdxTy();
11609       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11610                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11611     }
11612   }
11613
11614   bool BCNumEltsChanged = false;
11615   EVT ExtVT = VT.getVectorElementType();
11616   EVT LVT = ExtVT;
11617
11618   // If the result of load has to be truncated, then it's not necessarily
11619   // profitable.
11620   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11621     return SDValue();
11622
11623   if (InVec.getOpcode() == ISD::BITCAST) {
11624     // Don't duplicate a load with other uses.
11625     if (!InVec.hasOneUse())
11626       return SDValue();
11627
11628     EVT BCVT = InVec.getOperand(0).getValueType();
11629     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11630       return SDValue();
11631     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11632       BCNumEltsChanged = true;
11633     InVec = InVec.getOperand(0);
11634     ExtVT = BCVT.getVectorElementType();
11635   }
11636
11637   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11638   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11639       ISD::isNormalLoad(InVec.getNode()) &&
11640       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11641     SDValue Index = N->getOperand(1);
11642     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11643       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11644                                                            OrigLoad);
11645   }
11646
11647   // Perform only after legalization to ensure build_vector / vector_shuffle
11648   // optimizations have already been done.
11649   if (!LegalOperations) return SDValue();
11650
11651   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11652   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11653   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11654
11655   if (ConstEltNo) {
11656     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11657
11658     LoadSDNode *LN0 = nullptr;
11659     const ShuffleVectorSDNode *SVN = nullptr;
11660     if (ISD::isNormalLoad(InVec.getNode())) {
11661       LN0 = cast<LoadSDNode>(InVec);
11662     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11663                InVec.getOperand(0).getValueType() == ExtVT &&
11664                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11665       // Don't duplicate a load with other uses.
11666       if (!InVec.hasOneUse())
11667         return SDValue();
11668
11669       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11670     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11671       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11672       // =>
11673       // (load $addr+1*size)
11674
11675       // Don't duplicate a load with other uses.
11676       if (!InVec.hasOneUse())
11677         return SDValue();
11678
11679       // If the bit convert changed the number of elements, it is unsafe
11680       // to examine the mask.
11681       if (BCNumEltsChanged)
11682         return SDValue();
11683
11684       // Select the input vector, guarding against out of range extract vector.
11685       unsigned NumElems = VT.getVectorNumElements();
11686       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11687       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11688
11689       if (InVec.getOpcode() == ISD::BITCAST) {
11690         // Don't duplicate a load with other uses.
11691         if (!InVec.hasOneUse())
11692           return SDValue();
11693
11694         InVec = InVec.getOperand(0);
11695       }
11696       if (ISD::isNormalLoad(InVec.getNode())) {
11697         LN0 = cast<LoadSDNode>(InVec);
11698         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11699         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11700       }
11701     }
11702
11703     // Make sure we found a non-volatile load and the extractelement is
11704     // the only use.
11705     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11706       return SDValue();
11707
11708     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11709     if (Elt == -1)
11710       return DAG.getUNDEF(LVT);
11711
11712     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11713   }
11714
11715   return SDValue();
11716 }
11717
11718 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11719 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11720   // We perform this optimization post type-legalization because
11721   // the type-legalizer often scalarizes integer-promoted vectors.
11722   // Performing this optimization before may create bit-casts which
11723   // will be type-legalized to complex code sequences.
11724   // We perform this optimization only before the operation legalizer because we
11725   // may introduce illegal operations.
11726   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11727     return SDValue();
11728
11729   unsigned NumInScalars = N->getNumOperands();
11730   SDLoc dl(N);
11731   EVT VT = N->getValueType(0);
11732
11733   // Check to see if this is a BUILD_VECTOR of a bunch of values
11734   // which come from any_extend or zero_extend nodes. If so, we can create
11735   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11736   // optimizations. We do not handle sign-extend because we can't fill the sign
11737   // using shuffles.
11738   EVT SourceType = MVT::Other;
11739   bool AllAnyExt = true;
11740
11741   for (unsigned i = 0; i != NumInScalars; ++i) {
11742     SDValue In = N->getOperand(i);
11743     // Ignore undef inputs.
11744     if (In.getOpcode() == ISD::UNDEF) continue;
11745
11746     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11747     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11748
11749     // Abort if the element is not an extension.
11750     if (!ZeroExt && !AnyExt) {
11751       SourceType = MVT::Other;
11752       break;
11753     }
11754
11755     // The input is a ZeroExt or AnyExt. Check the original type.
11756     EVT InTy = In.getOperand(0).getValueType();
11757
11758     // Check that all of the widened source types are the same.
11759     if (SourceType == MVT::Other)
11760       // First time.
11761       SourceType = InTy;
11762     else if (InTy != SourceType) {
11763       // Multiple income types. Abort.
11764       SourceType = MVT::Other;
11765       break;
11766     }
11767
11768     // Check if all of the extends are ANY_EXTENDs.
11769     AllAnyExt &= AnyExt;
11770   }
11771
11772   // In order to have valid types, all of the inputs must be extended from the
11773   // same source type and all of the inputs must be any or zero extend.
11774   // Scalar sizes must be a power of two.
11775   EVT OutScalarTy = VT.getScalarType();
11776   bool ValidTypes = SourceType != MVT::Other &&
11777                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11778                  isPowerOf2_32(SourceType.getSizeInBits());
11779
11780   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11781   // turn into a single shuffle instruction.
11782   if (!ValidTypes)
11783     return SDValue();
11784
11785   bool isLE = TLI.isLittleEndian();
11786   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11787   assert(ElemRatio > 1 && "Invalid element size ratio");
11788   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11789                                DAG.getConstant(0, SDLoc(N), SourceType);
11790
11791   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11792   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11793
11794   // Populate the new build_vector
11795   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11796     SDValue Cast = N->getOperand(i);
11797     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11798             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11799             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11800     SDValue In;
11801     if (Cast.getOpcode() == ISD::UNDEF)
11802       In = DAG.getUNDEF(SourceType);
11803     else
11804       In = Cast->getOperand(0);
11805     unsigned Index = isLE ? (i * ElemRatio) :
11806                             (i * ElemRatio + (ElemRatio - 1));
11807
11808     assert(Index < Ops.size() && "Invalid index");
11809     Ops[Index] = In;
11810   }
11811
11812   // The type of the new BUILD_VECTOR node.
11813   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11814   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11815          "Invalid vector size");
11816   // Check if the new vector type is legal.
11817   if (!isTypeLegal(VecVT)) return SDValue();
11818
11819   // Make the new BUILD_VECTOR.
11820   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11821
11822   // The new BUILD_VECTOR node has the potential to be further optimized.
11823   AddToWorklist(BV.getNode());
11824   // Bitcast to the desired type.
11825   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11826 }
11827
11828 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11829   EVT VT = N->getValueType(0);
11830
11831   unsigned NumInScalars = N->getNumOperands();
11832   SDLoc dl(N);
11833
11834   EVT SrcVT = MVT::Other;
11835   unsigned Opcode = ISD::DELETED_NODE;
11836   unsigned NumDefs = 0;
11837
11838   for (unsigned i = 0; i != NumInScalars; ++i) {
11839     SDValue In = N->getOperand(i);
11840     unsigned Opc = In.getOpcode();
11841
11842     if (Opc == ISD::UNDEF)
11843       continue;
11844
11845     // If all scalar values are floats and converted from integers.
11846     if (Opcode == ISD::DELETED_NODE &&
11847         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11848       Opcode = Opc;
11849     }
11850
11851     if (Opc != Opcode)
11852       return SDValue();
11853
11854     EVT InVT = In.getOperand(0).getValueType();
11855
11856     // If all scalar values are typed differently, bail out. It's chosen to
11857     // simplify BUILD_VECTOR of integer types.
11858     if (SrcVT == MVT::Other)
11859       SrcVT = InVT;
11860     if (SrcVT != InVT)
11861       return SDValue();
11862     NumDefs++;
11863   }
11864
11865   // If the vector has just one element defined, it's not worth to fold it into
11866   // a vectorized one.
11867   if (NumDefs < 2)
11868     return SDValue();
11869
11870   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11871          && "Should only handle conversion from integer to float.");
11872   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11873
11874   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11875
11876   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11877     return SDValue();
11878
11879   // Just because the floating-point vector type is legal does not necessarily
11880   // mean that the corresponding integer vector type is.
11881   if (!isTypeLegal(NVT))
11882     return SDValue();
11883
11884   SmallVector<SDValue, 8> Opnds;
11885   for (unsigned i = 0; i != NumInScalars; ++i) {
11886     SDValue In = N->getOperand(i);
11887
11888     if (In.getOpcode() == ISD::UNDEF)
11889       Opnds.push_back(DAG.getUNDEF(SrcVT));
11890     else
11891       Opnds.push_back(In.getOperand(0));
11892   }
11893   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11894   AddToWorklist(BV.getNode());
11895
11896   return DAG.getNode(Opcode, dl, VT, BV);
11897 }
11898
11899 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11900   unsigned NumInScalars = N->getNumOperands();
11901   SDLoc dl(N);
11902   EVT VT = N->getValueType(0);
11903
11904   // A vector built entirely of undefs is undef.
11905   if (ISD::allOperandsUndef(N))
11906     return DAG.getUNDEF(VT);
11907
11908   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11909     return V;
11910
11911   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11912     return V;
11913
11914   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11915   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11916   // at most two distinct vectors, turn this into a shuffle node.
11917
11918   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11919   if (!isTypeLegal(VT))
11920     return SDValue();
11921
11922   // May only combine to shuffle after legalize if shuffle is legal.
11923   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11924     return SDValue();
11925
11926   SDValue VecIn1, VecIn2;
11927   bool UsesZeroVector = false;
11928   for (unsigned i = 0; i != NumInScalars; ++i) {
11929     SDValue Op = N->getOperand(i);
11930     // Ignore undef inputs.
11931     if (Op.getOpcode() == ISD::UNDEF) continue;
11932
11933     // See if we can combine this build_vector into a blend with a zero vector.
11934     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11935       UsesZeroVector = true;
11936       continue;
11937     }
11938
11939     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11940     // constant index, bail out.
11941     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11942         !isa<ConstantSDNode>(Op.getOperand(1))) {
11943       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11944       break;
11945     }
11946
11947     // We allow up to two distinct input vectors.
11948     SDValue ExtractedFromVec = Op.getOperand(0);
11949     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11950       continue;
11951
11952     if (!VecIn1.getNode()) {
11953       VecIn1 = ExtractedFromVec;
11954     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11955       VecIn2 = ExtractedFromVec;
11956     } else {
11957       // Too many inputs.
11958       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11959       break;
11960     }
11961   }
11962
11963   // If everything is good, we can make a shuffle operation.
11964   if (VecIn1.getNode()) {
11965     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11966     SmallVector<int, 8> Mask;
11967     for (unsigned i = 0; i != NumInScalars; ++i) {
11968       unsigned Opcode = N->getOperand(i).getOpcode();
11969       if (Opcode == ISD::UNDEF) {
11970         Mask.push_back(-1);
11971         continue;
11972       }
11973
11974       // Operands can also be zero.
11975       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11976         assert(UsesZeroVector &&
11977                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11978                "Unexpected node found!");
11979         Mask.push_back(NumInScalars+i);
11980         continue;
11981       }
11982
11983       // If extracting from the first vector, just use the index directly.
11984       SDValue Extract = N->getOperand(i);
11985       SDValue ExtVal = Extract.getOperand(1);
11986       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11987       if (Extract.getOperand(0) == VecIn1) {
11988         Mask.push_back(ExtIndex);
11989         continue;
11990       }
11991
11992       // Otherwise, use InIdx + InputVecSize
11993       Mask.push_back(InNumElements + ExtIndex);
11994     }
11995
11996     // Avoid introducing illegal shuffles with zero.
11997     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11998       return SDValue();
11999
12000     // We can't generate a shuffle node with mismatched input and output types.
12001     // Attempt to transform a single input vector to the correct type.
12002     if ((VT != VecIn1.getValueType())) {
12003       // If the input vector type has a different base type to the output
12004       // vector type, bail out.
12005       EVT VTElemType = VT.getVectorElementType();
12006       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12007           (VecIn2.getNode() &&
12008            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12009         return SDValue();
12010
12011       // If the input vector is too small, widen it.
12012       // We only support widening of vectors which are half the size of the
12013       // output registers. For example XMM->YMM widening on X86 with AVX.
12014       EVT VecInT = VecIn1.getValueType();
12015       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12016         // If we only have one small input, widen it by adding undef values.
12017         if (!VecIn2.getNode())
12018           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12019                                DAG.getUNDEF(VecIn1.getValueType()));
12020         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12021           // If we have two small inputs of the same type, try to concat them.
12022           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12023           VecIn2 = SDValue(nullptr, 0);
12024         } else
12025           return SDValue();
12026       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12027         // If the input vector is too large, try to split it.
12028         // We don't support having two input vectors that are too large.
12029         // If the zero vector was used, we can not split the vector,
12030         // since we'd need 3 inputs.
12031         if (UsesZeroVector || VecIn2.getNode())
12032           return SDValue();
12033
12034         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12035           return SDValue();
12036
12037         // Try to replace VecIn1 with two extract_subvectors
12038         // No need to update the masks, they should still be correct.
12039         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12040           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12041         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12042           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12043       } else
12044         return SDValue();
12045     }
12046
12047     if (UsesZeroVector)
12048       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12049                                 DAG.getConstantFP(0.0, dl, VT);
12050     else
12051       // If VecIn2 is unused then change it to undef.
12052       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12053
12054     // Check that we were able to transform all incoming values to the same
12055     // type.
12056     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12057         VecIn1.getValueType() != VT)
12058           return SDValue();
12059
12060     // Return the new VECTOR_SHUFFLE node.
12061     SDValue Ops[2];
12062     Ops[0] = VecIn1;
12063     Ops[1] = VecIn2;
12064     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12065   }
12066
12067   return SDValue();
12068 }
12069
12070 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12072   EVT OpVT = N->getOperand(0).getValueType();
12073
12074   // If the operands are legal vectors, leave them alone.
12075   if (TLI.isTypeLegal(OpVT))
12076     return SDValue();
12077
12078   SDLoc DL(N);
12079   EVT VT = N->getValueType(0);
12080   SmallVector<SDValue, 8> Ops;
12081
12082   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12083   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12084
12085   // Keep track of what we encounter.
12086   bool AnyInteger = false;
12087   bool AnyFP = false;
12088   for (const SDValue &Op : N->ops()) {
12089     if (ISD::BITCAST == Op.getOpcode() &&
12090         !Op.getOperand(0).getValueType().isVector())
12091       Ops.push_back(Op.getOperand(0));
12092     else if (ISD::UNDEF == Op.getOpcode())
12093       Ops.push_back(ScalarUndef);
12094     else
12095       return SDValue();
12096
12097     // Note whether we encounter an integer or floating point scalar.
12098     // If it's neither, bail out, it could be something weird like x86mmx.
12099     EVT LastOpVT = Ops.back().getValueType();
12100     if (LastOpVT.isFloatingPoint())
12101       AnyFP = true;
12102     else if (LastOpVT.isInteger())
12103       AnyInteger = true;
12104     else
12105       return SDValue();
12106   }
12107
12108   // If any of the operands is a floating point scalar bitcast to a vector,
12109   // use floating point types throughout, and bitcast everything.  
12110   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12111   if (AnyFP) {
12112     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12113     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12114     if (AnyInteger) {
12115       for (SDValue &Op : Ops) {
12116         if (Op.getValueType() == SVT)
12117           continue;
12118         if (Op.getOpcode() == ISD::UNDEF)
12119           Op = ScalarUndef;
12120         else
12121           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12122       }
12123     }
12124   }
12125
12126   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12127                                VT.getSizeInBits() / SVT.getSizeInBits());
12128   return DAG.getNode(ISD::BITCAST, DL, VT,
12129                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12130 }
12131
12132 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12133   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12134   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12135   // inputs come from at most two distinct vectors, turn this into a shuffle
12136   // node.
12137
12138   // If we only have one input vector, we don't need to do any concatenation.
12139   if (N->getNumOperands() == 1)
12140     return N->getOperand(0);
12141
12142   // Check if all of the operands are undefs.
12143   EVT VT = N->getValueType(0);
12144   if (ISD::allOperandsUndef(N))
12145     return DAG.getUNDEF(VT);
12146
12147   // Optimize concat_vectors where all but the first of the vectors are undef.
12148   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12149         return Op.getOpcode() == ISD::UNDEF;
12150       })) {
12151     SDValue In = N->getOperand(0);
12152     assert(In.getValueType().isVector() && "Must concat vectors");
12153
12154     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12155     if (In->getOpcode() == ISD::BITCAST &&
12156         !In->getOperand(0)->getValueType(0).isVector()) {
12157       SDValue Scalar = In->getOperand(0);
12158
12159       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12160       // look through the trunc so we can still do the transform:
12161       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12162       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12163           !TLI.isTypeLegal(Scalar.getValueType()) &&
12164           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12165         Scalar = Scalar->getOperand(0);
12166
12167       EVT SclTy = Scalar->getValueType(0);
12168
12169       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12170         return SDValue();
12171
12172       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12173                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12174       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12175         return SDValue();
12176
12177       SDLoc dl = SDLoc(N);
12178       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12179       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12180     }
12181   }
12182
12183   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12184   // We have already tested above for an UNDEF only concatenation.
12185   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12186   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12187   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12188     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12189   };
12190   bool AllBuildVectorsOrUndefs =
12191       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12192   if (AllBuildVectorsOrUndefs) {
12193     SmallVector<SDValue, 8> Opnds;
12194     EVT SVT = VT.getScalarType();
12195
12196     EVT MinVT = SVT;
12197     if (!SVT.isFloatingPoint()) {
12198       // If BUILD_VECTOR are from built from integer, they may have different
12199       // operand types. Get the smallest type and truncate all operands to it.
12200       bool FoundMinVT = false;
12201       for (const SDValue &Op : N->ops())
12202         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12203           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12204           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12205           FoundMinVT = true;
12206         }
12207       assert(FoundMinVT && "Concat vector type mismatch");
12208     }
12209
12210     for (const SDValue &Op : N->ops()) {
12211       EVT OpVT = Op.getValueType();
12212       unsigned NumElts = OpVT.getVectorNumElements();
12213
12214       if (ISD::UNDEF == Op.getOpcode())
12215         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12216
12217       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12218         if (SVT.isFloatingPoint()) {
12219           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12220           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12221         } else {
12222           for (unsigned i = 0; i != NumElts; ++i)
12223             Opnds.push_back(
12224                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12225         }
12226       }
12227     }
12228
12229     assert(VT.getVectorNumElements() == Opnds.size() &&
12230            "Concat vector type mismatch");
12231     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12232   }
12233
12234   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12235   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12236     return V;
12237
12238   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12239   // nodes often generate nop CONCAT_VECTOR nodes.
12240   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12241   // place the incoming vectors at the exact same location.
12242   SDValue SingleSource = SDValue();
12243   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12244
12245   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12246     SDValue Op = N->getOperand(i);
12247
12248     if (Op.getOpcode() == ISD::UNDEF)
12249       continue;
12250
12251     // Check if this is the identity extract:
12252     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12253       return SDValue();
12254
12255     // Find the single incoming vector for the extract_subvector.
12256     if (SingleSource.getNode()) {
12257       if (Op.getOperand(0) != SingleSource)
12258         return SDValue();
12259     } else {
12260       SingleSource = Op.getOperand(0);
12261
12262       // Check the source type is the same as the type of the result.
12263       // If not, this concat may extend the vector, so we can not
12264       // optimize it away.
12265       if (SingleSource.getValueType() != N->getValueType(0))
12266         return SDValue();
12267     }
12268
12269     unsigned IdentityIndex = i * PartNumElem;
12270     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12271     // The extract index must be constant.
12272     if (!CS)
12273       return SDValue();
12274
12275     // Check that we are reading from the identity index.
12276     if (CS->getZExtValue() != IdentityIndex)
12277       return SDValue();
12278   }
12279
12280   if (SingleSource.getNode())
12281     return SingleSource;
12282
12283   return SDValue();
12284 }
12285
12286 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12287   EVT NVT = N->getValueType(0);
12288   SDValue V = N->getOperand(0);
12289
12290   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12291     // Combine:
12292     //    (extract_subvec (concat V1, V2, ...), i)
12293     // Into:
12294     //    Vi if possible
12295     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12296     // type.
12297     if (V->getOperand(0).getValueType() != NVT)
12298       return SDValue();
12299     unsigned Idx = N->getConstantOperandVal(1);
12300     unsigned NumElems = NVT.getVectorNumElements();
12301     assert((Idx % NumElems) == 0 &&
12302            "IDX in concat is not a multiple of the result vector length.");
12303     return V->getOperand(Idx / NumElems);
12304   }
12305
12306   // Skip bitcasting
12307   if (V->getOpcode() == ISD::BITCAST)
12308     V = V.getOperand(0);
12309
12310   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12311     SDLoc dl(N);
12312     // Handle only simple case where vector being inserted and vector
12313     // being extracted are of same type, and are half size of larger vectors.
12314     EVT BigVT = V->getOperand(0).getValueType();
12315     EVT SmallVT = V->getOperand(1).getValueType();
12316     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12317       return SDValue();
12318
12319     // Only handle cases where both indexes are constants with the same type.
12320     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12321     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12322
12323     if (InsIdx && ExtIdx &&
12324         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12325         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12326       // Combine:
12327       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12328       // Into:
12329       //    indices are equal or bit offsets are equal => V1
12330       //    otherwise => (extract_subvec V1, ExtIdx)
12331       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12332           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12333         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12334       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12335                          DAG.getNode(ISD::BITCAST, dl,
12336                                      N->getOperand(0).getValueType(),
12337                                      V->getOperand(0)), N->getOperand(1));
12338     }
12339   }
12340
12341   return SDValue();
12342 }
12343
12344 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12345                                                  SDValue V, SelectionDAG &DAG) {
12346   SDLoc DL(V);
12347   EVT VT = V.getValueType();
12348
12349   switch (V.getOpcode()) {
12350   default:
12351     return V;
12352
12353   case ISD::CONCAT_VECTORS: {
12354     EVT OpVT = V->getOperand(0).getValueType();
12355     int OpSize = OpVT.getVectorNumElements();
12356     SmallBitVector OpUsedElements(OpSize, false);
12357     bool FoundSimplification = false;
12358     SmallVector<SDValue, 4> NewOps;
12359     NewOps.reserve(V->getNumOperands());
12360     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12361       SDValue Op = V->getOperand(i);
12362       bool OpUsed = false;
12363       for (int j = 0; j < OpSize; ++j)
12364         if (UsedElements[i * OpSize + j]) {
12365           OpUsedElements[j] = true;
12366           OpUsed = true;
12367         }
12368       NewOps.push_back(
12369           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12370                  : DAG.getUNDEF(OpVT));
12371       FoundSimplification |= Op == NewOps.back();
12372       OpUsedElements.reset();
12373     }
12374     if (FoundSimplification)
12375       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12376     return V;
12377   }
12378
12379   case ISD::INSERT_SUBVECTOR: {
12380     SDValue BaseV = V->getOperand(0);
12381     SDValue SubV = V->getOperand(1);
12382     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12383     if (!IdxN)
12384       return V;
12385
12386     int SubSize = SubV.getValueType().getVectorNumElements();
12387     int Idx = IdxN->getZExtValue();
12388     bool SubVectorUsed = false;
12389     SmallBitVector SubUsedElements(SubSize, false);
12390     for (int i = 0; i < SubSize; ++i)
12391       if (UsedElements[i + Idx]) {
12392         SubVectorUsed = true;
12393         SubUsedElements[i] = true;
12394         UsedElements[i + Idx] = false;
12395       }
12396
12397     // Now recurse on both the base and sub vectors.
12398     SDValue SimplifiedSubV =
12399         SubVectorUsed
12400             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12401             : DAG.getUNDEF(SubV.getValueType());
12402     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12403     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12404       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12405                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12406     return V;
12407   }
12408   }
12409 }
12410
12411 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12412                                        SDValue N1, SelectionDAG &DAG) {
12413   EVT VT = SVN->getValueType(0);
12414   int NumElts = VT.getVectorNumElements();
12415   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12416   for (int M : SVN->getMask())
12417     if (M >= 0 && M < NumElts)
12418       N0UsedElements[M] = true;
12419     else if (M >= NumElts)
12420       N1UsedElements[M - NumElts] = true;
12421
12422   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12423   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12424   if (S0 == N0 && S1 == N1)
12425     return SDValue();
12426
12427   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12428 }
12429
12430 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12431 // or turn a shuffle of a single concat into simpler shuffle then concat.
12432 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12433   EVT VT = N->getValueType(0);
12434   unsigned NumElts = VT.getVectorNumElements();
12435
12436   SDValue N0 = N->getOperand(0);
12437   SDValue N1 = N->getOperand(1);
12438   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12439
12440   SmallVector<SDValue, 4> Ops;
12441   EVT ConcatVT = N0.getOperand(0).getValueType();
12442   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12443   unsigned NumConcats = NumElts / NumElemsPerConcat;
12444
12445   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12446   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12447   // half vector elements.
12448   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12449       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12450                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12451     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12452                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12453     N1 = DAG.getUNDEF(ConcatVT);
12454     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12455   }
12456
12457   // Look at every vector that's inserted. We're looking for exact
12458   // subvector-sized copies from a concatenated vector
12459   for (unsigned I = 0; I != NumConcats; ++I) {
12460     // Make sure we're dealing with a copy.
12461     unsigned Begin = I * NumElemsPerConcat;
12462     bool AllUndef = true, NoUndef = true;
12463     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12464       if (SVN->getMaskElt(J) >= 0)
12465         AllUndef = false;
12466       else
12467         NoUndef = false;
12468     }
12469
12470     if (NoUndef) {
12471       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12472         return SDValue();
12473
12474       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12475         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12476           return SDValue();
12477
12478       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12479       if (FirstElt < N0.getNumOperands())
12480         Ops.push_back(N0.getOperand(FirstElt));
12481       else
12482         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12483
12484     } else if (AllUndef) {
12485       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12486     } else { // Mixed with general masks and undefs, can't do optimization.
12487       return SDValue();
12488     }
12489   }
12490
12491   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12492 }
12493
12494 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12495   EVT VT = N->getValueType(0);
12496   unsigned NumElts = VT.getVectorNumElements();
12497
12498   SDValue N0 = N->getOperand(0);
12499   SDValue N1 = N->getOperand(1);
12500
12501   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12502
12503   // Canonicalize shuffle undef, undef -> undef
12504   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12505     return DAG.getUNDEF(VT);
12506
12507   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12508
12509   // Canonicalize shuffle v, v -> v, undef
12510   if (N0 == N1) {
12511     SmallVector<int, 8> NewMask;
12512     for (unsigned i = 0; i != NumElts; ++i) {
12513       int Idx = SVN->getMaskElt(i);
12514       if (Idx >= (int)NumElts) Idx -= NumElts;
12515       NewMask.push_back(Idx);
12516     }
12517     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12518                                 &NewMask[0]);
12519   }
12520
12521   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12522   if (N0.getOpcode() == ISD::UNDEF) {
12523     SmallVector<int, 8> NewMask;
12524     for (unsigned i = 0; i != NumElts; ++i) {
12525       int Idx = SVN->getMaskElt(i);
12526       if (Idx >= 0) {
12527         if (Idx >= (int)NumElts)
12528           Idx -= NumElts;
12529         else
12530           Idx = -1; // remove reference to lhs
12531       }
12532       NewMask.push_back(Idx);
12533     }
12534     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12535                                 &NewMask[0]);
12536   }
12537
12538   // Remove references to rhs if it is undef
12539   if (N1.getOpcode() == ISD::UNDEF) {
12540     bool Changed = false;
12541     SmallVector<int, 8> NewMask;
12542     for (unsigned i = 0; i != NumElts; ++i) {
12543       int Idx = SVN->getMaskElt(i);
12544       if (Idx >= (int)NumElts) {
12545         Idx = -1;
12546         Changed = true;
12547       }
12548       NewMask.push_back(Idx);
12549     }
12550     if (Changed)
12551       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12552   }
12553
12554   // If it is a splat, check if the argument vector is another splat or a
12555   // build_vector.
12556   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12557     SDNode *V = N0.getNode();
12558
12559     // If this is a bit convert that changes the element type of the vector but
12560     // not the number of vector elements, look through it.  Be careful not to
12561     // look though conversions that change things like v4f32 to v2f64.
12562     if (V->getOpcode() == ISD::BITCAST) {
12563       SDValue ConvInput = V->getOperand(0);
12564       if (ConvInput.getValueType().isVector() &&
12565           ConvInput.getValueType().getVectorNumElements() == NumElts)
12566         V = ConvInput.getNode();
12567     }
12568
12569     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12570       assert(V->getNumOperands() == NumElts &&
12571              "BUILD_VECTOR has wrong number of operands");
12572       SDValue Base;
12573       bool AllSame = true;
12574       for (unsigned i = 0; i != NumElts; ++i) {
12575         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12576           Base = V->getOperand(i);
12577           break;
12578         }
12579       }
12580       // Splat of <u, u, u, u>, return <u, u, u, u>
12581       if (!Base.getNode())
12582         return N0;
12583       for (unsigned i = 0; i != NumElts; ++i) {
12584         if (V->getOperand(i) != Base) {
12585           AllSame = false;
12586           break;
12587         }
12588       }
12589       // Splat of <x, x, x, x>, return <x, x, x, x>
12590       if (AllSame)
12591         return N0;
12592
12593       // Canonicalize any other splat as a build_vector.
12594       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12595       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12596       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12597                                   V->getValueType(0), Ops);
12598
12599       // We may have jumped through bitcasts, so the type of the
12600       // BUILD_VECTOR may not match the type of the shuffle.
12601       if (V->getValueType(0) != VT)
12602         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12603       return NewBV;
12604     }
12605   }
12606
12607   // There are various patterns used to build up a vector from smaller vectors,
12608   // subvectors, or elements. Scan chains of these and replace unused insertions
12609   // or components with undef.
12610   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12611     return S;
12612
12613   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12614       Level < AfterLegalizeVectorOps &&
12615       (N1.getOpcode() == ISD::UNDEF ||
12616       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12617        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12618     SDValue V = partitionShuffleOfConcats(N, DAG);
12619
12620     if (V.getNode())
12621       return V;
12622   }
12623
12624   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12625   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12626   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12627     SmallVector<SDValue, 8> Ops;
12628     for (int M : SVN->getMask()) {
12629       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12630       if (M >= 0) {
12631         int Idx = M % NumElts;
12632         SDValue &S = (M < (int)NumElts ? N0 : N1);
12633         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12634           Op = S.getOperand(Idx);
12635         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12636           if (Idx == 0)
12637             Op = S.getOperand(0);
12638         } else {
12639           // Operand can't be combined - bail out.
12640           break;
12641         }
12642       }
12643       Ops.push_back(Op);
12644     }
12645     if (Ops.size() == VT.getVectorNumElements()) {
12646       // BUILD_VECTOR requires all inputs to be of the same type, find the
12647       // maximum type and extend them all.
12648       EVT SVT = VT.getScalarType();
12649       if (SVT.isInteger())
12650         for (SDValue &Op : Ops)
12651           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12652       if (SVT != VT.getScalarType())
12653         for (SDValue &Op : Ops)
12654           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12655                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12656                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12657       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12658     }
12659   }
12660
12661   // If this shuffle only has a single input that is a bitcasted shuffle,
12662   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12663   // back to their original types.
12664   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12665       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12666       TLI.isTypeLegal(VT)) {
12667
12668     // Peek through the bitcast only if there is one user.
12669     SDValue BC0 = N0;
12670     while (BC0.getOpcode() == ISD::BITCAST) {
12671       if (!BC0.hasOneUse())
12672         break;
12673       BC0 = BC0.getOperand(0);
12674     }
12675
12676     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12677       if (Scale == 1)
12678         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12679
12680       SmallVector<int, 8> NewMask;
12681       for (int M : Mask)
12682         for (int s = 0; s != Scale; ++s)
12683           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12684       return NewMask;
12685     };
12686
12687     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12688       EVT SVT = VT.getScalarType();
12689       EVT InnerVT = BC0->getValueType(0);
12690       EVT InnerSVT = InnerVT.getScalarType();
12691
12692       // Determine which shuffle works with the smaller scalar type.
12693       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12694       EVT ScaleSVT = ScaleVT.getScalarType();
12695
12696       if (TLI.isTypeLegal(ScaleVT) &&
12697           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12698           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12699
12700         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12701         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12702
12703         // Scale the shuffle masks to the smaller scalar type.
12704         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12705         SmallVector<int, 8> InnerMask =
12706             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12707         SmallVector<int, 8> OuterMask =
12708             ScaleShuffleMask(SVN->getMask(), OuterScale);
12709
12710         // Merge the shuffle masks.
12711         SmallVector<int, 8> NewMask;
12712         for (int M : OuterMask)
12713           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12714
12715         // Test for shuffle mask legality over both commutations.
12716         SDValue SV0 = BC0->getOperand(0);
12717         SDValue SV1 = BC0->getOperand(1);
12718         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12719         if (!LegalMask) {
12720           std::swap(SV0, SV1);
12721           ShuffleVectorSDNode::commuteMask(NewMask);
12722           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12723         }
12724
12725         if (LegalMask) {
12726           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12727           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12728           return DAG.getNode(
12729               ISD::BITCAST, SDLoc(N), VT,
12730               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12731         }
12732       }
12733     }
12734   }
12735
12736   // Canonicalize shuffles according to rules:
12737   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12738   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12739   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12740   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12741       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12742       TLI.isTypeLegal(VT)) {
12743     // The incoming shuffle must be of the same type as the result of the
12744     // current shuffle.
12745     assert(N1->getOperand(0).getValueType() == VT &&
12746            "Shuffle types don't match");
12747
12748     SDValue SV0 = N1->getOperand(0);
12749     SDValue SV1 = N1->getOperand(1);
12750     bool HasSameOp0 = N0 == SV0;
12751     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12752     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12753       // Commute the operands of this shuffle so that next rule
12754       // will trigger.
12755       return DAG.getCommutedVectorShuffle(*SVN);
12756   }
12757
12758   // Try to fold according to rules:
12759   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12760   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12761   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12762   // Don't try to fold shuffles with illegal type.
12763   // Only fold if this shuffle is the only user of the other shuffle.
12764   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12765       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12766     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12767
12768     // The incoming shuffle must be of the same type as the result of the
12769     // current shuffle.
12770     assert(OtherSV->getOperand(0).getValueType() == VT &&
12771            "Shuffle types don't match");
12772
12773     SDValue SV0, SV1;
12774     SmallVector<int, 4> Mask;
12775     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12776     // operand, and SV1 as the second operand.
12777     for (unsigned i = 0; i != NumElts; ++i) {
12778       int Idx = SVN->getMaskElt(i);
12779       if (Idx < 0) {
12780         // Propagate Undef.
12781         Mask.push_back(Idx);
12782         continue;
12783       }
12784
12785       SDValue CurrentVec;
12786       if (Idx < (int)NumElts) {
12787         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12788         // shuffle mask to identify which vector is actually referenced.
12789         Idx = OtherSV->getMaskElt(Idx);
12790         if (Idx < 0) {
12791           // Propagate Undef.
12792           Mask.push_back(Idx);
12793           continue;
12794         }
12795
12796         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12797                                            : OtherSV->getOperand(1);
12798       } else {
12799         // This shuffle index references an element within N1.
12800         CurrentVec = N1;
12801       }
12802
12803       // Simple case where 'CurrentVec' is UNDEF.
12804       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12805         Mask.push_back(-1);
12806         continue;
12807       }
12808
12809       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12810       // will be the first or second operand of the combined shuffle.
12811       Idx = Idx % NumElts;
12812       if (!SV0.getNode() || SV0 == CurrentVec) {
12813         // Ok. CurrentVec is the left hand side.
12814         // Update the mask accordingly.
12815         SV0 = CurrentVec;
12816         Mask.push_back(Idx);
12817         continue;
12818       }
12819
12820       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12821       if (SV1.getNode() && SV1 != CurrentVec)
12822         return SDValue();
12823
12824       // Ok. CurrentVec is the right hand side.
12825       // Update the mask accordingly.
12826       SV1 = CurrentVec;
12827       Mask.push_back(Idx + NumElts);
12828     }
12829
12830     // Check if all indices in Mask are Undef. In case, propagate Undef.
12831     bool isUndefMask = true;
12832     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12833       isUndefMask &= Mask[i] < 0;
12834
12835     if (isUndefMask)
12836       return DAG.getUNDEF(VT);
12837
12838     if (!SV0.getNode())
12839       SV0 = DAG.getUNDEF(VT);
12840     if (!SV1.getNode())
12841       SV1 = DAG.getUNDEF(VT);
12842
12843     // Avoid introducing shuffles with illegal mask.
12844     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12845       ShuffleVectorSDNode::commuteMask(Mask);
12846
12847       if (!TLI.isShuffleMaskLegal(Mask, VT))
12848         return SDValue();
12849
12850       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12851       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12852       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12853       std::swap(SV0, SV1);
12854     }
12855
12856     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12857     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12858     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12859     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12860   }
12861
12862   return SDValue();
12863 }
12864
12865 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12866   SDValue InVal = N->getOperand(0);
12867   EVT VT = N->getValueType(0);
12868
12869   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12870   // with a VECTOR_SHUFFLE.
12871   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12872     SDValue InVec = InVal->getOperand(0);
12873     SDValue EltNo = InVal->getOperand(1);
12874
12875     // FIXME: We could support implicit truncation if the shuffle can be
12876     // scaled to a smaller vector scalar type.
12877     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12878     if (C0 && VT == InVec.getValueType() &&
12879         VT.getScalarType() == InVal.getValueType()) {
12880       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12881       int Elt = C0->getZExtValue();
12882       NewMask[0] = Elt;
12883
12884       if (TLI.isShuffleMaskLegal(NewMask, VT))
12885         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12886                                     NewMask);
12887     }
12888   }
12889
12890   return SDValue();
12891 }
12892
12893 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12894   SDValue N0 = N->getOperand(0);
12895   SDValue N2 = N->getOperand(2);
12896
12897   // If the input vector is a concatenation, and the insert replaces
12898   // one of the halves, we can optimize into a single concat_vectors.
12899   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12900       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12901     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12902     EVT VT = N->getValueType(0);
12903
12904     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12905     // (concat_vectors Z, Y)
12906     if (InsIdx == 0)
12907       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12908                          N->getOperand(1), N0.getOperand(1));
12909
12910     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12911     // (concat_vectors X, Z)
12912     if (InsIdx == VT.getVectorNumElements()/2)
12913       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12914                          N0.getOperand(0), N->getOperand(1));
12915   }
12916
12917   return SDValue();
12918 }
12919
12920 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12921   SDValue N0 = N->getOperand(0);
12922
12923   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12924   if (N0->getOpcode() == ISD::FP16_TO_FP)
12925     return N0->getOperand(0);
12926
12927   return SDValue();
12928 }
12929
12930 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12931 /// with the destination vector and a zero vector.
12932 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12933 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12934 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12935   EVT VT = N->getValueType(0);
12936   SDValue LHS = N->getOperand(0);
12937   SDValue RHS = N->getOperand(1);
12938   SDLoc dl(N);
12939
12940   // Make sure we're not running after operation legalization where it 
12941   // may have custom lowered the vector shuffles.
12942   if (LegalOperations)
12943     return SDValue();
12944
12945   if (N->getOpcode() != ISD::AND)
12946     return SDValue();
12947
12948   if (RHS.getOpcode() == ISD::BITCAST)
12949     RHS = RHS.getOperand(0);
12950
12951   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12952     SmallVector<int, 8> Indices;
12953     unsigned NumElts = RHS.getNumOperands();
12954
12955     for (unsigned i = 0; i != NumElts; ++i) {
12956       SDValue Elt = RHS.getOperand(i);
12957       if (isAllOnesConstant(Elt))
12958         Indices.push_back(i);
12959       else if (isNullConstant(Elt))
12960         Indices.push_back(NumElts+i);
12961       else
12962         return SDValue();
12963     }
12964
12965     // Let's see if the target supports this vector_shuffle.
12966     EVT RVT = RHS.getValueType();
12967     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12968       return SDValue();
12969
12970     // Return the new VECTOR_SHUFFLE node.
12971     EVT EltVT = RVT.getVectorElementType();
12972     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12973                                    DAG.getConstant(0, dl, EltVT));
12974     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12975     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12976     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12977     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12978   }
12979
12980   return SDValue();
12981 }
12982
12983 /// Visit a binary vector operation, like ADD.
12984 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12985   assert(N->getValueType(0).isVector() &&
12986          "SimplifyVBinOp only works on vectors!");
12987
12988   SDValue LHS = N->getOperand(0);
12989   SDValue RHS = N->getOperand(1);
12990
12991   if (SDValue Shuffle = XformToShuffleWithZero(N))
12992     return Shuffle;
12993
12994   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12995   // this operation.
12996   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12997       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12998     // Check if both vectors are constants. If not bail out.
12999     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13000           cast<BuildVectorSDNode>(RHS)->isConstant()))
13001       return SDValue();
13002
13003     SmallVector<SDValue, 8> Ops;
13004     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13005       SDValue LHSOp = LHS.getOperand(i);
13006       SDValue RHSOp = RHS.getOperand(i);
13007
13008       // Can't fold divide by zero.
13009       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13010           N->getOpcode() == ISD::FDIV) {
13011         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13012              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13013           break;
13014       }
13015
13016       EVT VT = LHSOp.getValueType();
13017       EVT RVT = RHSOp.getValueType();
13018       if (RVT != VT) {
13019         // Integer BUILD_VECTOR operands may have types larger than the element
13020         // size (e.g., when the element type is not legal).  Prior to type
13021         // legalization, the types may not match between the two BUILD_VECTORS.
13022         // Truncate one of the operands to make them match.
13023         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13024           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13025         } else {
13026           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13027           VT = RVT;
13028         }
13029       }
13030       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13031                                    LHSOp, RHSOp);
13032       if (FoldOp.getOpcode() != ISD::UNDEF &&
13033           FoldOp.getOpcode() != ISD::Constant &&
13034           FoldOp.getOpcode() != ISD::ConstantFP)
13035         break;
13036       Ops.push_back(FoldOp);
13037       AddToWorklist(FoldOp.getNode());
13038     }
13039
13040     if (Ops.size() == LHS.getNumOperands())
13041       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13042   }
13043
13044   // Type legalization might introduce new shuffles in the DAG.
13045   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13046   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13047   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13048       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13049       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13050       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13051     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13052     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13053
13054     if (SVN0->getMask().equals(SVN1->getMask())) {
13055       EVT VT = N->getValueType(0);
13056       SDValue UndefVector = LHS.getOperand(1);
13057       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13058                                      LHS.getOperand(0), RHS.getOperand(0));
13059       AddUsersToWorklist(N);
13060       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13061                                   &SVN0->getMask()[0]);
13062     }
13063   }
13064
13065   return SDValue();
13066 }
13067
13068 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13069                                     SDValue N1, SDValue N2){
13070   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13071
13072   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13073                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13074
13075   // If we got a simplified select_cc node back from SimplifySelectCC, then
13076   // break it down into a new SETCC node, and a new SELECT node, and then return
13077   // the SELECT node, since we were called with a SELECT node.
13078   if (SCC.getNode()) {
13079     // Check to see if we got a select_cc back (to turn into setcc/select).
13080     // Otherwise, just return whatever node we got back, like fabs.
13081     if (SCC.getOpcode() == ISD::SELECT_CC) {
13082       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13083                                   N0.getValueType(),
13084                                   SCC.getOperand(0), SCC.getOperand(1),
13085                                   SCC.getOperand(4));
13086       AddToWorklist(SETCC.getNode());
13087       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13088                            SCC.getOperand(2), SCC.getOperand(3));
13089     }
13090
13091     return SCC;
13092   }
13093   return SDValue();
13094 }
13095
13096 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13097 /// being selected between, see if we can simplify the select.  Callers of this
13098 /// should assume that TheSelect is deleted if this returns true.  As such, they
13099 /// should return the appropriate thing (e.g. the node) back to the top-level of
13100 /// the DAG combiner loop to avoid it being looked at.
13101 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13102                                     SDValue RHS) {
13103
13104   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13105   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13106   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13107     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13108       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13109       SDValue Sqrt = RHS;
13110       ISD::CondCode CC;
13111       SDValue CmpLHS;
13112       const ConstantFPSDNode *NegZero = nullptr;
13113
13114       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13115         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13116         CmpLHS = TheSelect->getOperand(0);
13117         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13118       } else {
13119         // SELECT or VSELECT
13120         SDValue Cmp = TheSelect->getOperand(0);
13121         if (Cmp.getOpcode() == ISD::SETCC) {
13122           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13123           CmpLHS = Cmp.getOperand(0);
13124           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13125         }
13126       }
13127       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13128           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13129           CC == ISD::SETULT || CC == ISD::SETLT)) {
13130         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13131         CombineTo(TheSelect, Sqrt);
13132         return true;
13133       }
13134     }
13135   }
13136   // Cannot simplify select with vector condition
13137   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13138
13139   // If this is a select from two identical things, try to pull the operation
13140   // through the select.
13141   if (LHS.getOpcode() != RHS.getOpcode() ||
13142       !LHS.hasOneUse() || !RHS.hasOneUse())
13143     return false;
13144
13145   // If this is a load and the token chain is identical, replace the select
13146   // of two loads with a load through a select of the address to load from.
13147   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13148   // constants have been dropped into the constant pool.
13149   if (LHS.getOpcode() == ISD::LOAD) {
13150     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13151     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13152
13153     // Token chains must be identical.
13154     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13155         // Do not let this transformation reduce the number of volatile loads.
13156         LLD->isVolatile() || RLD->isVolatile() ||
13157         // FIXME: If either is a pre/post inc/dec load,
13158         // we'd need to split out the address adjustment.
13159         LLD->isIndexed() || RLD->isIndexed() ||
13160         // If this is an EXTLOAD, the VT's must match.
13161         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13162         // If this is an EXTLOAD, the kind of extension must match.
13163         (LLD->getExtensionType() != RLD->getExtensionType() &&
13164          // The only exception is if one of the extensions is anyext.
13165          LLD->getExtensionType() != ISD::EXTLOAD &&
13166          RLD->getExtensionType() != ISD::EXTLOAD) ||
13167         // FIXME: this discards src value information.  This is
13168         // over-conservative. It would be beneficial to be able to remember
13169         // both potential memory locations.  Since we are discarding
13170         // src value info, don't do the transformation if the memory
13171         // locations are not in the default address space.
13172         LLD->getPointerInfo().getAddrSpace() != 0 ||
13173         RLD->getPointerInfo().getAddrSpace() != 0 ||
13174         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13175                                       LLD->getBasePtr().getValueType()))
13176       return false;
13177
13178     // Check that the select condition doesn't reach either load.  If so,
13179     // folding this will induce a cycle into the DAG.  If not, this is safe to
13180     // xform, so create a select of the addresses.
13181     SDValue Addr;
13182     if (TheSelect->getOpcode() == ISD::SELECT) {
13183       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13184       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13185           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13186         return false;
13187       // The loads must not depend on one another.
13188       if (LLD->isPredecessorOf(RLD) ||
13189           RLD->isPredecessorOf(LLD))
13190         return false;
13191       Addr = DAG.getSelect(SDLoc(TheSelect),
13192                            LLD->getBasePtr().getValueType(),
13193                            TheSelect->getOperand(0), LLD->getBasePtr(),
13194                            RLD->getBasePtr());
13195     } else {  // Otherwise SELECT_CC
13196       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13197       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13198
13199       if ((LLD->hasAnyUseOfValue(1) &&
13200            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13201           (RLD->hasAnyUseOfValue(1) &&
13202            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13203         return false;
13204
13205       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13206                          LLD->getBasePtr().getValueType(),
13207                          TheSelect->getOperand(0),
13208                          TheSelect->getOperand(1),
13209                          LLD->getBasePtr(), RLD->getBasePtr(),
13210                          TheSelect->getOperand(4));
13211     }
13212
13213     SDValue Load;
13214     // It is safe to replace the two loads if they have different alignments,
13215     // but the new load must be the minimum (most restrictive) alignment of the
13216     // inputs.
13217     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13218     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13219     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13220       Load = DAG.getLoad(TheSelect->getValueType(0),
13221                          SDLoc(TheSelect),
13222                          // FIXME: Discards pointer and AA info.
13223                          LLD->getChain(), Addr, MachinePointerInfo(),
13224                          LLD->isVolatile(), LLD->isNonTemporal(),
13225                          isInvariant, Alignment);
13226     } else {
13227       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13228                             RLD->getExtensionType() : LLD->getExtensionType(),
13229                             SDLoc(TheSelect),
13230                             TheSelect->getValueType(0),
13231                             // FIXME: Discards pointer and AA info.
13232                             LLD->getChain(), Addr, MachinePointerInfo(),
13233                             LLD->getMemoryVT(), LLD->isVolatile(),
13234                             LLD->isNonTemporal(), isInvariant, Alignment);
13235     }
13236
13237     // Users of the select now use the result of the load.
13238     CombineTo(TheSelect, Load);
13239
13240     // Users of the old loads now use the new load's chain.  We know the
13241     // old-load value is dead now.
13242     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13243     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13244     return true;
13245   }
13246
13247   return false;
13248 }
13249
13250 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13251 /// where 'cond' is the comparison specified by CC.
13252 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13253                                       SDValue N2, SDValue N3,
13254                                       ISD::CondCode CC, bool NotExtCompare) {
13255   // (x ? y : y) -> y.
13256   if (N2 == N3) return N2;
13257
13258   EVT VT = N2.getValueType();
13259   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13260   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13261
13262   // Determine if the condition we're dealing with is constant
13263   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13264                               N0, N1, CC, DL, false);
13265   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13266
13267   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13268     // fold select_cc true, x, y -> x
13269     // fold select_cc false, x, y -> y
13270     return !SCCC->isNullValue() ? N2 : N3;
13271   }
13272
13273   // Check to see if we can simplify the select into an fabs node
13274   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13275     // Allow either -0.0 or 0.0
13276     if (CFP->isZero()) {
13277       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13278       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13279           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13280           N2 == N3.getOperand(0))
13281         return DAG.getNode(ISD::FABS, DL, VT, N0);
13282
13283       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13284       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13285           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13286           N2.getOperand(0) == N3)
13287         return DAG.getNode(ISD::FABS, DL, VT, N3);
13288     }
13289   }
13290
13291   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13292   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13293   // in it.  This is a win when the constant is not otherwise available because
13294   // it replaces two constant pool loads with one.  We only do this if the FP
13295   // type is known to be legal, because if it isn't, then we are before legalize
13296   // types an we want the other legalization to happen first (e.g. to avoid
13297   // messing with soft float) and if the ConstantFP is not legal, because if
13298   // it is legal, we may not need to store the FP constant in a constant pool.
13299   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13300     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13301       if (TLI.isTypeLegal(N2.getValueType()) &&
13302           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13303                TargetLowering::Legal &&
13304            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13305            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13306           // If both constants have multiple uses, then we won't need to do an
13307           // extra load, they are likely around in registers for other users.
13308           (TV->hasOneUse() || FV->hasOneUse())) {
13309         Constant *Elts[] = {
13310           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13311           const_cast<ConstantFP*>(TV->getConstantFPValue())
13312         };
13313         Type *FPTy = Elts[0]->getType();
13314         const DataLayout &TD = *TLI.getDataLayout();
13315
13316         // Create a ConstantArray of the two constants.
13317         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13318         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13319                                             TD.getPrefTypeAlignment(FPTy));
13320         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13321
13322         // Get the offsets to the 0 and 1 element of the array so that we can
13323         // select between them.
13324         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13325         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13326         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13327
13328         SDValue Cond = DAG.getSetCC(DL,
13329                                     getSetCCResultType(N0.getValueType()),
13330                                     N0, N1, CC);
13331         AddToWorklist(Cond.getNode());
13332         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13333                                           Cond, One, Zero);
13334         AddToWorklist(CstOffset.getNode());
13335         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13336                             CstOffset);
13337         AddToWorklist(CPIdx.getNode());
13338         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13339                            MachinePointerInfo::getConstantPool(), false,
13340                            false, false, Alignment);
13341       }
13342     }
13343
13344   // Check to see if we can perform the "gzip trick", transforming
13345   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13346   if (isNullConstant(N3) && CC == ISD::SETLT &&
13347       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13348        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13349     EVT XType = N0.getValueType();
13350     EVT AType = N2.getValueType();
13351     if (XType.bitsGE(AType)) {
13352       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13353       // single-bit constant.
13354       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13355         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13356         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13357         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13358                                        getShiftAmountTy(N0.getValueType()));
13359         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13360                                     XType, N0, ShCt);
13361         AddToWorklist(Shift.getNode());
13362
13363         if (XType.bitsGT(AType)) {
13364           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13365           AddToWorklist(Shift.getNode());
13366         }
13367
13368         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13369       }
13370
13371       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13372                                   XType, N0,
13373                                   DAG.getConstant(XType.getSizeInBits() - 1,
13374                                                   SDLoc(N0),
13375                                          getShiftAmountTy(N0.getValueType())));
13376       AddToWorklist(Shift.getNode());
13377
13378       if (XType.bitsGT(AType)) {
13379         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13380         AddToWorklist(Shift.getNode());
13381       }
13382
13383       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13384     }
13385   }
13386
13387   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13388   // where y is has a single bit set.
13389   // A plaintext description would be, we can turn the SELECT_CC into an AND
13390   // when the condition can be materialized as an all-ones register.  Any
13391   // single bit-test can be materialized as an all-ones register with
13392   // shift-left and shift-right-arith.
13393   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13394       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13395     SDValue AndLHS = N0->getOperand(0);
13396     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13397     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13398       // Shift the tested bit over the sign bit.
13399       APInt AndMask = ConstAndRHS->getAPIntValue();
13400       SDValue ShlAmt =
13401         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13402                         getShiftAmountTy(AndLHS.getValueType()));
13403       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13404
13405       // Now arithmetic right shift it all the way over, so the result is either
13406       // all-ones, or zero.
13407       SDValue ShrAmt =
13408         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13409                         getShiftAmountTy(Shl.getValueType()));
13410       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13411
13412       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13413     }
13414   }
13415
13416   // fold select C, 16, 0 -> shl C, 4
13417   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13418       TLI.getBooleanContents(N0.getValueType()) ==
13419           TargetLowering::ZeroOrOneBooleanContent) {
13420
13421     // If the caller doesn't want us to simplify this into a zext of a compare,
13422     // don't do it.
13423     if (NotExtCompare && N2C->isOne())
13424       return SDValue();
13425
13426     // Get a SetCC of the condition
13427     // NOTE: Don't create a SETCC if it's not legal on this target.
13428     if (!LegalOperations ||
13429         TLI.isOperationLegal(ISD::SETCC,
13430           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13431       SDValue Temp, SCC;
13432       // cast from setcc result type to select result type
13433       if (LegalTypes) {
13434         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13435                             N0, N1, CC);
13436         if (N2.getValueType().bitsLT(SCC.getValueType()))
13437           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13438                                         N2.getValueType());
13439         else
13440           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13441                              N2.getValueType(), SCC);
13442       } else {
13443         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13444         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13445                            N2.getValueType(), SCC);
13446       }
13447
13448       AddToWorklist(SCC.getNode());
13449       AddToWorklist(Temp.getNode());
13450
13451       if (N2C->isOne())
13452         return Temp;
13453
13454       // shl setcc result by log2 n2c
13455       return DAG.getNode(
13456           ISD::SHL, DL, N2.getValueType(), Temp,
13457           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13458                           getShiftAmountTy(Temp.getValueType())));
13459     }
13460   }
13461
13462   // Check to see if this is the equivalent of setcc
13463   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13464   // otherwise, go ahead with the folds.
13465   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13466     EVT XType = N0.getValueType();
13467     if (!LegalOperations ||
13468         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13469       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13470       if (Res.getValueType() != VT)
13471         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13472       return Res;
13473     }
13474
13475     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13476     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13477         (!LegalOperations ||
13478          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13479       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13480       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13481                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13482                                          SDLoc(Ctlz),
13483                                        getShiftAmountTy(Ctlz.getValueType())));
13484     }
13485     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13486     if (isNullConstant(N1) && CC == ISD::SETGT) {
13487       SDLoc DL(N0);
13488       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13489                                   XType, DAG.getConstant(0, DL, XType), N0);
13490       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13491       return DAG.getNode(ISD::SRL, DL, XType,
13492                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13493                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13494                                          getShiftAmountTy(XType)));
13495     }
13496     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13497     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13498       SDLoc DL(N0);
13499       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13500                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13501                                          getShiftAmountTy(N0.getValueType())));
13502       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13503                                                                     XType));
13504     }
13505   }
13506
13507   // Check to see if this is an integer abs.
13508   // select_cc setg[te] X,  0,  X, -X ->
13509   // select_cc setgt    X, -1,  X, -X ->
13510   // select_cc setl[te] X,  0, -X,  X ->
13511   // select_cc setlt    X,  1, -X,  X ->
13512   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13513   if (N1C) {
13514     ConstantSDNode *SubC = nullptr;
13515     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13516          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13517         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13518       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13519     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13520               (N1C->isOne() && CC == ISD::SETLT)) &&
13521              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13522       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13523
13524     EVT XType = N0.getValueType();
13525     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13526       SDLoc DL(N0);
13527       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13528                                   N0,
13529                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13530                                          getShiftAmountTy(N0.getValueType())));
13531       SDValue Add = DAG.getNode(ISD::ADD, DL,
13532                                 XType, N0, Shift);
13533       AddToWorklist(Shift.getNode());
13534       AddToWorklist(Add.getNode());
13535       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13536     }
13537   }
13538
13539   return SDValue();
13540 }
13541
13542 /// This is a stub for TargetLowering::SimplifySetCC.
13543 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13544                                    SDValue N1, ISD::CondCode Cond,
13545                                    SDLoc DL, bool foldBooleans) {
13546   TargetLowering::DAGCombinerInfo
13547     DagCombineInfo(DAG, Level, false, this);
13548   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13549 }
13550
13551 /// Given an ISD::SDIV node expressing a divide by constant, return
13552 /// a DAG expression to select that will generate the same value by multiplying
13553 /// by a magic number.
13554 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13555 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13556   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13557   if (!C)
13558     return SDValue();
13559
13560   // Avoid division by zero.
13561   if (C->isNullValue())
13562     return SDValue();
13563
13564   std::vector<SDNode*> Built;
13565   SDValue S =
13566       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13567
13568   for (SDNode *N : Built)
13569     AddToWorklist(N);
13570   return S;
13571 }
13572
13573 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13574 /// DAG expression that will generate the same value by right shifting.
13575 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13576   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13577   if (!C)
13578     return SDValue();
13579
13580   // Avoid division by zero.
13581   if (C->isNullValue())
13582     return SDValue();
13583
13584   std::vector<SDNode *> Built;
13585   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13586
13587   for (SDNode *N : Built)
13588     AddToWorklist(N);
13589   return S;
13590 }
13591
13592 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13593 /// expression that will generate the same value by multiplying by a magic
13594 /// number.
13595 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13596 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13597   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13598   if (!C)
13599     return SDValue();
13600
13601   // Avoid division by zero.
13602   if (C->isNullValue())
13603     return SDValue();
13604
13605   std::vector<SDNode*> Built;
13606   SDValue S =
13607       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13608
13609   for (SDNode *N : Built)
13610     AddToWorklist(N);
13611   return S;
13612 }
13613
13614 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13615   if (Level >= AfterLegalizeDAG)
13616     return SDValue();
13617
13618   // Expose the DAG combiner to the target combiner implementations.
13619   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13620
13621   unsigned Iterations = 0;
13622   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13623     if (Iterations) {
13624       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13625       // For the reciprocal, we need to find the zero of the function:
13626       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13627       //     =>
13628       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13629       //     does not require additional intermediate precision]
13630       EVT VT = Op.getValueType();
13631       SDLoc DL(Op);
13632       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13633
13634       AddToWorklist(Est.getNode());
13635
13636       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13637       for (unsigned i = 0; i < Iterations; ++i) {
13638         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13639         AddToWorklist(NewEst.getNode());
13640
13641         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13642         AddToWorklist(NewEst.getNode());
13643
13644         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13645         AddToWorklist(NewEst.getNode());
13646
13647         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13648         AddToWorklist(Est.getNode());
13649       }
13650     }
13651     return Est;
13652   }
13653
13654   return SDValue();
13655 }
13656
13657 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13658 /// For the reciprocal sqrt, we need to find the zero of the function:
13659 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13660 ///     =>
13661 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13662 /// As a result, we precompute A/2 prior to the iteration loop.
13663 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13664                                           unsigned Iterations) {
13665   EVT VT = Arg.getValueType();
13666   SDLoc DL(Arg);
13667   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13668
13669   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13670   // this entire sequence requires only one FP constant.
13671   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13672   AddToWorklist(HalfArg.getNode());
13673
13674   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13675   AddToWorklist(HalfArg.getNode());
13676
13677   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13678   for (unsigned i = 0; i < Iterations; ++i) {
13679     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13680     AddToWorklist(NewEst.getNode());
13681
13682     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13683     AddToWorklist(NewEst.getNode());
13684
13685     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13686     AddToWorklist(NewEst.getNode());
13687
13688     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13689     AddToWorklist(Est.getNode());
13690   }
13691   return Est;
13692 }
13693
13694 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13695 /// For the reciprocal sqrt, we need to find the zero of the function:
13696 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13697 ///     =>
13698 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13699 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13700                                           unsigned Iterations) {
13701   EVT VT = Arg.getValueType();
13702   SDLoc DL(Arg);
13703   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13704   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13705
13706   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13707   for (unsigned i = 0; i < Iterations; ++i) {
13708     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13709     AddToWorklist(HalfEst.getNode());
13710
13711     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13712     AddToWorklist(Est.getNode());
13713
13714     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13715     AddToWorklist(Est.getNode());
13716
13717     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13718     AddToWorklist(Est.getNode());
13719
13720     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13721     AddToWorklist(Est.getNode());
13722   }
13723   return Est;
13724 }
13725
13726 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13727   if (Level >= AfterLegalizeDAG)
13728     return SDValue();
13729
13730   // Expose the DAG combiner to the target combiner implementations.
13731   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13732   unsigned Iterations = 0;
13733   bool UseOneConstNR = false;
13734   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13735     AddToWorklist(Est.getNode());
13736     if (Iterations) {
13737       Est = UseOneConstNR ?
13738         BuildRsqrtNROneConst(Op, Est, Iterations) :
13739         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13740     }
13741     return Est;
13742   }
13743
13744   return SDValue();
13745 }
13746
13747 /// Return true if base is a frame index, which is known not to alias with
13748 /// anything but itself.  Provides base object and offset as results.
13749 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13750                            const GlobalValue *&GV, const void *&CV) {
13751   // Assume it is a primitive operation.
13752   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13753
13754   // If it's an adding a simple constant then integrate the offset.
13755   if (Base.getOpcode() == ISD::ADD) {
13756     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13757       Base = Base.getOperand(0);
13758       Offset += C->getZExtValue();
13759     }
13760   }
13761
13762   // Return the underlying GlobalValue, and update the Offset.  Return false
13763   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13764   // by multiple nodes with different offsets.
13765   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13766     GV = G->getGlobal();
13767     Offset += G->getOffset();
13768     return false;
13769   }
13770
13771   // Return the underlying Constant value, and update the Offset.  Return false
13772   // for ConstantSDNodes since the same constant pool entry may be represented
13773   // by multiple nodes with different offsets.
13774   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13775     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13776                                          : (const void *)C->getConstVal();
13777     Offset += C->getOffset();
13778     return false;
13779   }
13780   // If it's any of the following then it can't alias with anything but itself.
13781   return isa<FrameIndexSDNode>(Base);
13782 }
13783
13784 /// Return true if there is any possibility that the two addresses overlap.
13785 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13786   // If they are the same then they must be aliases.
13787   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13788
13789   // If they are both volatile then they cannot be reordered.
13790   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13791
13792   // Gather base node and offset information.
13793   SDValue Base1, Base2;
13794   int64_t Offset1, Offset2;
13795   const GlobalValue *GV1, *GV2;
13796   const void *CV1, *CV2;
13797   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13798                                       Base1, Offset1, GV1, CV1);
13799   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13800                                       Base2, Offset2, GV2, CV2);
13801
13802   // If they have a same base address then check to see if they overlap.
13803   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13804     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13805              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13806
13807   // It is possible for different frame indices to alias each other, mostly
13808   // when tail call optimization reuses return address slots for arguments.
13809   // To catch this case, look up the actual index of frame indices to compute
13810   // the real alias relationship.
13811   if (isFrameIndex1 && isFrameIndex2) {
13812     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13813     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13814     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13815     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13816              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13817   }
13818
13819   // Otherwise, if we know what the bases are, and they aren't identical, then
13820   // we know they cannot alias.
13821   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13822     return false;
13823
13824   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13825   // compared to the size and offset of the access, we may be able to prove they
13826   // do not alias.  This check is conservative for now to catch cases created by
13827   // splitting vector types.
13828   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13829       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13830       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13831        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13832       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13833     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13834     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13835
13836     // There is no overlap between these relatively aligned accesses of similar
13837     // size, return no alias.
13838     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13839         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13840       return false;
13841   }
13842
13843   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13844                    ? CombinerGlobalAA
13845                    : DAG.getSubtarget().useAA();
13846 #ifndef NDEBUG
13847   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13848       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13849     UseAA = false;
13850 #endif
13851   if (UseAA &&
13852       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13853     // Use alias analysis information.
13854     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13855                                  Op1->getSrcValueOffset());
13856     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13857         Op0->getSrcValueOffset() - MinOffset;
13858     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13859         Op1->getSrcValueOffset() - MinOffset;
13860     AliasAnalysis::AliasResult AAResult =
13861         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13862                                          Overlap1,
13863                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13864                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13865                                          Overlap2,
13866                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13867     if (AAResult == AliasAnalysis::NoAlias)
13868       return false;
13869   }
13870
13871   // Otherwise we have to assume they alias.
13872   return true;
13873 }
13874
13875 /// Walk up chain skipping non-aliasing memory nodes,
13876 /// looking for aliasing nodes and adding them to the Aliases vector.
13877 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13878                                    SmallVectorImpl<SDValue> &Aliases) {
13879   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13880   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13881
13882   // Get alias information for node.
13883   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13884
13885   // Starting off.
13886   Chains.push_back(OriginalChain);
13887   unsigned Depth = 0;
13888
13889   // Look at each chain and determine if it is an alias.  If so, add it to the
13890   // aliases list.  If not, then continue up the chain looking for the next
13891   // candidate.
13892   while (!Chains.empty()) {
13893     SDValue Chain = Chains.back();
13894     Chains.pop_back();
13895
13896     // For TokenFactor nodes, look at each operand and only continue up the
13897     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13898     // find more and revert to original chain since the xform is unlikely to be
13899     // profitable.
13900     //
13901     // FIXME: The depth check could be made to return the last non-aliasing
13902     // chain we found before we hit a tokenfactor rather than the original
13903     // chain.
13904     if (Depth > 6 || Aliases.size() == 2) {
13905       Aliases.clear();
13906       Aliases.push_back(OriginalChain);
13907       return;
13908     }
13909
13910     // Don't bother if we've been before.
13911     if (!Visited.insert(Chain.getNode()).second)
13912       continue;
13913
13914     switch (Chain.getOpcode()) {
13915     case ISD::EntryToken:
13916       // Entry token is ideal chain operand, but handled in FindBetterChain.
13917       break;
13918
13919     case ISD::LOAD:
13920     case ISD::STORE: {
13921       // Get alias information for Chain.
13922       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13923           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13924
13925       // If chain is alias then stop here.
13926       if (!(IsLoad && IsOpLoad) &&
13927           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13928         Aliases.push_back(Chain);
13929       } else {
13930         // Look further up the chain.
13931         Chains.push_back(Chain.getOperand(0));
13932         ++Depth;
13933       }
13934       break;
13935     }
13936
13937     case ISD::TokenFactor:
13938       // We have to check each of the operands of the token factor for "small"
13939       // token factors, so we queue them up.  Adding the operands to the queue
13940       // (stack) in reverse order maintains the original order and increases the
13941       // likelihood that getNode will find a matching token factor (CSE.)
13942       if (Chain.getNumOperands() > 16) {
13943         Aliases.push_back(Chain);
13944         break;
13945       }
13946       for (unsigned n = Chain.getNumOperands(); n;)
13947         Chains.push_back(Chain.getOperand(--n));
13948       ++Depth;
13949       break;
13950
13951     default:
13952       // For all other instructions we will just have to take what we can get.
13953       Aliases.push_back(Chain);
13954       break;
13955     }
13956   }
13957
13958   // We need to be careful here to also search for aliases through the
13959   // value operand of a store, etc. Consider the following situation:
13960   //   Token1 = ...
13961   //   L1 = load Token1, %52
13962   //   S1 = store Token1, L1, %51
13963   //   L2 = load Token1, %52+8
13964   //   S2 = store Token1, L2, %51+8
13965   //   Token2 = Token(S1, S2)
13966   //   L3 = load Token2, %53
13967   //   S3 = store Token2, L3, %52
13968   //   L4 = load Token2, %53+8
13969   //   S4 = store Token2, L4, %52+8
13970   // If we search for aliases of S3 (which loads address %52), and we look
13971   // only through the chain, then we'll miss the trivial dependence on L1
13972   // (which also loads from %52). We then might change all loads and
13973   // stores to use Token1 as their chain operand, which could result in
13974   // copying %53 into %52 before copying %52 into %51 (which should
13975   // happen first).
13976   //
13977   // The problem is, however, that searching for such data dependencies
13978   // can become expensive, and the cost is not directly related to the
13979   // chain depth. Instead, we'll rule out such configurations here by
13980   // insisting that we've visited all chain users (except for users
13981   // of the original chain, which is not necessary). When doing this,
13982   // we need to look through nodes we don't care about (otherwise, things
13983   // like register copies will interfere with trivial cases).
13984
13985   SmallVector<const SDNode *, 16> Worklist;
13986   for (const SDNode *N : Visited)
13987     if (N != OriginalChain.getNode())
13988       Worklist.push_back(N);
13989
13990   while (!Worklist.empty()) {
13991     const SDNode *M = Worklist.pop_back_val();
13992
13993     // We have already visited M, and want to make sure we've visited any uses
13994     // of M that we care about. For uses that we've not visisted, and don't
13995     // care about, queue them to the worklist.
13996
13997     for (SDNode::use_iterator UI = M->use_begin(),
13998          UIE = M->use_end(); UI != UIE; ++UI)
13999       if (UI.getUse().getValueType() == MVT::Other &&
14000           Visited.insert(*UI).second) {
14001         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
14002           // We've not visited this use, and we care about it (it could have an
14003           // ordering dependency with the original node).
14004           Aliases.clear();
14005           Aliases.push_back(OriginalChain);
14006           return;
14007         }
14008
14009         // We've not visited this use, but we don't care about it. Mark it as
14010         // visited and enqueue it to the worklist.
14011         Worklist.push_back(*UI);
14012       }
14013   }
14014 }
14015
14016 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14017 /// (aliasing node.)
14018 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14019   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14020
14021   // Accumulate all the aliases to this node.
14022   GatherAllAliases(N, OldChain, Aliases);
14023
14024   // If no operands then chain to entry token.
14025   if (Aliases.size() == 0)
14026     return DAG.getEntryNode();
14027
14028   // If a single operand then chain to it.  We don't need to revisit it.
14029   if (Aliases.size() == 1)
14030     return Aliases[0];
14031
14032   // Construct a custom tailored token factor.
14033   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14034 }
14035
14036 /// This is the entry point for the file.
14037 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14038                            CodeGenOpt::Level OptLevel) {
14039   /// This is the main entry point to this class.
14040   DAGCombiner(*this, AA, OptLevel).Run(Level);
14041 }