Masked gather and scatter - added DAGCombine visitors
[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 visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitMGATHER(SDNode *N);
311     SDValue visitMSCATTER(SDNode *N);
312     SDValue visitFP_TO_FP16(SDNode *N);
313
314     SDValue visitFADDForFMACombine(SDNode *N);
315     SDValue visitFSUBForFMACombine(SDNode *N);
316
317     SDValue XformToShuffleWithZero(SDNode *N);
318     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
319
320     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
321
322     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326                              SDValue N3, ISD::CondCode CC,
327                              bool NotExtCompare = false);
328     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329                           SDLoc DL, bool foldBooleans = true);
330
331     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332                            SDValue &CC) const;
333     bool isOneUseSetCC(SDValue N) const;
334
335     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
336                                          unsigned HiOp);
337     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338     SDValue CombineExtLoad(SDNode *N);
339     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340     SDValue BuildSDIV(SDNode *N);
341     SDValue BuildSDIVPow2(SDNode *N);
342     SDValue BuildUDIV(SDNode *N);
343     SDValue BuildReciprocalEstimate(SDValue Op);
344     SDValue BuildRsqrtEstimate(SDValue Op);
345     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348                                bool DemandHighBits = true);
349     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351                               SDValue InnerPos, SDValue InnerNeg,
352                               unsigned PosOpcode, unsigned NegOpcode,
353                               SDLoc DL);
354     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355     SDValue ReduceLoadWidth(SDNode *N);
356     SDValue ReduceLoadOpStoreWidth(SDNode *N);
357     SDValue TransformFPLoadStorePair(SDNode *N);
358     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
360
361     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
362
363     /// Walk up chain skipping non-aliasing memory nodes,
364     /// looking for aliasing nodes and adding them to the Aliases vector.
365     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366                           SmallVectorImpl<SDValue> &Aliases);
367
368     /// Return true if there is any possibility that the two addresses overlap.
369     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
370
371     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372     /// chain (aliasing node.)
373     SDValue FindBetterChain(SDNode *N, SDValue Chain);
374
375     /// Holds a pointer to an LSBaseSDNode as well as information on where it
376     /// is located in a sequence of memory operations connected by a chain.
377     struct MemOpLink {
378       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380       // Ptr to the mem node.
381       LSBaseSDNode *MemNode;
382       // Offset from the base ptr.
383       int64_t OffsetFromBase;
384       // What is the sequence number of this mem node.
385       // Lowest mem operand in the DAG starts at zero.
386       unsigned SequenceNum;
387     };
388
389     /// This is a helper function for MergeConsecutiveStores. When the source
390     /// elements of the consecutive stores are all constants or all extracted
391     /// vector elements, try to merge them into one larger store.
392     /// \return True if a merged store was created.
393     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394                                          EVT MemVT, unsigned NumElem,
395                                          bool IsConstantSrc, bool UseVector);
396
397     /// Merge consecutive store operations into a wide store.
398     /// This optimization uses wide integers or vectors when possible.
399     /// \return True if some memory operations were changed.
400     bool MergeConsecutiveStores(StoreSDNode *N);
401
402     /// \brief Try to transform a truncation where C is a constant:
403     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
404     ///
405     /// \p N needs to be a truncation and its first operand an AND. Other
406     /// requirements are checked by the function (e.g. that trunc is
407     /// single-use) and if missed an empty SDValue is returned.
408     SDValue distributeTruncateThroughAnd(SDNode *N);
409
410   public:
411     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414       auto *F = DAG.getMachineFunction().getFunction();
415       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416                     F->hasFnAttribute(Attribute::MinSize);
417     }
418
419     /// Runs the dag combiner on all nodes in the work list
420     void Run(CombineLevel AtLevel);
421
422     SelectionDAG &getDAG() const { return DAG; }
423
424     /// Returns a type large enough to hold any valid shift amount - before type
425     /// legalization these can be huge.
426     EVT getShiftAmountTy(EVT LHSTy) {
427       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428       if (LHSTy.isVector())
429         return LHSTy;
430       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431                         : TLI.getPointerTy();
432     }
433
434     /// This method returns true if we are running before type legalization or
435     /// if the specified VT is legal.
436     bool isTypeLegal(const EVT &VT) {
437       if (!LegalTypes) return true;
438       return TLI.isTypeLegal(VT);
439     }
440
441     /// Convenience wrapper around TargetLowering::getSetCCResultType
442     EVT getSetCCResultType(EVT VT) const {
443       return TLI.getSetCCResultType(*DAG.getContext(), VT);
444     }
445   };
446 }
447
448
449 namespace {
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453   DAGCombiner &DC;
454 public:
455   explicit WorklistRemover(DAGCombiner &dc)
456     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
457
458   void NodeDeleted(SDNode *N, SDNode *E) override {
459     DC.removeFromWorklist(N);
460   }
461 };
462 }
463
464 //===----------------------------------------------------------------------===//
465 //  TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
467
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469   ((DAGCombiner*)DC)->AddToWorklist(N);
470 }
471
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473   ((DAGCombiner*)DC)->removeFromWorklist(N);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 }
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
484 }
485
486
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 }
491
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 }
496
497 //===----------------------------------------------------------------------===//
498 // Helper Functions
499 //===----------------------------------------------------------------------===//
500
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502   removeFromWorklist(N);
503
504   // If the operands of this node are only used by the node, they will now be
505   // dead. Make sure to re-visit them and recursively delete dead nodes.
506   for (const SDValue &Op : N->ops())
507     // For an operand generating multiple values, one of the values may
508     // become dead allowing further simplification (e.g. split index
509     // arithmetic from an indexed load).
510     if (Op->hasOneUse() || Op->getNumValues() > 1)
511       AddToWorklist(Op.getNode());
512
513   DAG.DeleteNode(N);
514 }
515
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520                                const TargetLowering &TLI,
521                                const TargetOptions *Options,
522                                unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return 2;
525
526   // Don't allow anything with multiple uses.
527   if (!Op.hasOneUse()) return 0;
528
529   // Don't recurse exponentially.
530   if (Depth > 6) return 0;
531
532   switch (Op.getOpcode()) {
533   default: return false;
534   case ISD::ConstantFP:
535     // Don't invert constant FP values after legalize.  The negated constant
536     // isn't necessarily legal.
537     return LegalOperations ? 0 : 1;
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     if (!Options->UnsafeFPMath) return 0;
541
542     // After operation legalization, it might not be legal to create new FSUBs.
543     if (LegalOperations &&
544         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
545       return 0;
546
547     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549                                     Options, Depth + 1))
550       return V;
551     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553                               Depth + 1);
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // fold (fneg (fsub A, B)) -> (fsub B, A)
559     return 1;
560
561   case ISD::FMUL:
562   case ISD::FDIV:
563     if (Options->HonorSignDependentRoundingFPMath()) return 0;
564
565     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572
573   case ISD::FP_EXTEND:
574   case ISD::FP_ROUND:
575   case ISD::FSIN:
576     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
577                               Depth + 1);
578   }
579 }
580
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583                                     bool LegalOperations, unsigned Depth = 0) {
584   const TargetOptions &Options = DAG.getTarget().Options;
585   // fneg is removable even if it has multiple uses.
586   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
587
588   // Don't allow anything with multiple uses.
589   assert(Op.hasOneUse() && "Unknown reuse!");
590
591   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592   switch (Op.getOpcode()) {
593   default: llvm_unreachable("Unknown code");
594   case ISD::ConstantFP: {
595     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596     V.changeSign();
597     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598   }
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     assert(Options.UnsafeFPMath);
602
603     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
606       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                          GetNegatedExpression(Op.getOperand(0), DAG,
608                                               LegalOperations, Depth+1),
609                          Op.getOperand(1));
610     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(1), DAG,
613                                             LegalOperations, Depth+1),
614                        Op.getOperand(0));
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fsub 0, B)) -> B
620     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621       if (N0CFP->getValueAPF().isZero())
622         return Op.getOperand(1);
623
624     // fold (fneg (fsub A, B)) -> (fsub B, A)
625     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626                        Op.getOperand(1), Op.getOperand(0));
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     assert(!Options.HonorSignDependentRoundingFPMath());
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
635       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                          GetNegatedExpression(Op.getOperand(0), DAG,
637                                               LegalOperations, Depth+1),
638                          Op.getOperand(1));
639
640     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(0),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1));
645
646   case ISD::FP_EXTEND:
647   case ISD::FSIN:
648     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649                        GetNegatedExpression(Op.getOperand(0), DAG,
650                                             LegalOperations, Depth+1));
651   case ISD::FP_ROUND:
652       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653                          GetNegatedExpression(Op.getOperand(0), DAG,
654                                               LegalOperations, Depth+1),
655                          Op.getOperand(1));
656   }
657 }
658
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665                                     SDValue &CC) const {
666   if (N.getOpcode() == ISD::SETCC) {
667     LHS = N.getOperand(0);
668     RHS = N.getOperand(1);
669     CC  = N.getOperand(2);
670     return true;
671   }
672
673   if (N.getOpcode() != ISD::SELECT_CC ||
674       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676     return false;
677
678   if (TLI.getBooleanContents(N.getValueType()) ==
679       TargetLowering::UndefinedBooleanContent)
680     return false;
681
682   LHS = N.getOperand(0);
683   RHS = N.getOperand(1);
684   CC  = N.getOperand(4);
685   return true;
686 }
687
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
692   SDValue N0, N1, N2;
693   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
694     return true;
695   return false;
696 }
697
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702   if (!C)
703     return false;
704
705   APInt SplatUndef;
706   unsigned SplatBitSize;
707   bool HasAnyUndefs;
708   EVT EltVT = N->getValueType(0).getVectorElementType();
709   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710                              HasAnyUndefs) &&
711           EltVT.getSizeInBits() >= SplatBitSize);
712 }
713
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717   if (isa<ConstantSDNode>(N))
718     return N.getNode();
719   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720     return N.getNode();
721   return nullptr;
722 }
723
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MGATHER:            return visitMGATHER(N);
1388   case ISD::MLOAD:              return visitMLOAD(N);
1389   case ISD::MSCATTER:           return visitMSCATTER(N);
1390   case ISD::MSTORE:             return visitMSTORE(N);
1391   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397   SDValue RV = visit(N);
1398
1399   // If nothing happened, try a target-specific DAG combine.
1400   if (!RV.getNode()) {
1401     assert(N->getOpcode() != ISD::DELETED_NODE &&
1402            "Node was deleted but visit returned NULL!");
1403
1404     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407       // Expose the DAG combiner to the target combiner impls.
1408       TargetLowering::DAGCombinerInfo
1409         DagCombineInfo(DAG, Level, false, this);
1410
1411       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412     }
1413   }
1414
1415   // If nothing happened still, try promoting the operation.
1416   if (!RV.getNode()) {
1417     switch (N->getOpcode()) {
1418     default: break;
1419     case ISD::ADD:
1420     case ISD::SUB:
1421     case ISD::MUL:
1422     case ISD::AND:
1423     case ISD::OR:
1424     case ISD::XOR:
1425       RV = PromoteIntBinOp(SDValue(N, 0));
1426       break;
1427     case ISD::SHL:
1428     case ISD::SRA:
1429     case ISD::SRL:
1430       RV = PromoteIntShiftOp(SDValue(N, 0));
1431       break;
1432     case ISD::SIGN_EXTEND:
1433     case ISD::ZERO_EXTEND:
1434     case ISD::ANY_EXTEND:
1435       RV = PromoteExtend(SDValue(N, 0));
1436       break;
1437     case ISD::LOAD:
1438       if (PromoteLoad(SDValue(N, 0)))
1439         RV = SDValue(N, 0);
1440       break;
1441     }
1442   }
1443
1444   // If N is a commutative binary node, try commuting it to enable more
1445   // sdisel CSE.
1446   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447       N->getNumValues() == 1) {
1448     SDValue N0 = N->getOperand(0);
1449     SDValue N1 = N->getOperand(1);
1450
1451     // Constant operands are canonicalized to RHS.
1452     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453       SDValue Ops[] = {N1, N0};
1454       SDNode *CSENode;
1455       if (const BinaryWithFlagsSDNode *BinNode =
1456               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458                                       BinNode->Flags.hasNoUnsignedWrap(),
1459                                       BinNode->Flags.hasNoSignedWrap(),
1460                                       BinNode->Flags.hasExact());
1461       } else {
1462         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463       }
1464       if (CSENode)
1465         return SDValue(CSENode, 0);
1466     }
1467   }
1468
1469   return RV;
1470 }
1471
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1473 /// sd operand.
1474 static SDValue getInputChainForNode(SDNode *N) {
1475   if (unsigned NumOps = N->getNumOperands()) {
1476     if (N->getOperand(0).getValueType() == MVT::Other)
1477       return N->getOperand(0);
1478     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479       return N->getOperand(NumOps-1);
1480     for (unsigned i = 1; i < NumOps-1; ++i)
1481       if (N->getOperand(i).getValueType() == MVT::Other)
1482         return N->getOperand(i);
1483   }
1484   return SDValue();
1485 }
1486
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488   // If N has two operands, where one has an input chain equal to the other,
1489   // the 'other' chain is redundant.
1490   if (N->getNumOperands() == 2) {
1491     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492       return N->getOperand(0);
1493     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494       return N->getOperand(1);
1495   }
1496
1497   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1498   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1499   SmallPtrSet<SDNode*, 16> SeenOps;
1500   bool Changed = false;             // If we should replace this token factor.
1501
1502   // Start out with this token factor.
1503   TFs.push_back(N);
1504
1505   // Iterate through token factors.  The TFs grows when new token factors are
1506   // encountered.
1507   for (unsigned i = 0; i < TFs.size(); ++i) {
1508     SDNode *TF = TFs[i];
1509
1510     // Check each of the operands.
1511     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512       SDValue Op = TF->getOperand(i);
1513
1514       switch (Op.getOpcode()) {
1515       case ISD::EntryToken:
1516         // Entry tokens don't need to be added to the list. They are
1517         // redundant.
1518         Changed = true;
1519         break;
1520
1521       case ISD::TokenFactor:
1522         if (Op.hasOneUse() &&
1523             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524           // Queue up for processing.
1525           TFs.push_back(Op.getNode());
1526           // Clean up in case the token factor is removed.
1527           AddToWorklist(Op.getNode());
1528           Changed = true;
1529           break;
1530         }
1531         // Fall thru
1532
1533       default:
1534         // Only add if it isn't already in the list.
1535         if (SeenOps.insert(Op.getNode()).second)
1536           Ops.push_back(Op);
1537         else
1538           Changed = true;
1539         break;
1540       }
1541     }
1542   }
1543
1544   SDValue Result;
1545
1546   // If we've changed things around then replace token factor.
1547   if (Changed) {
1548     if (Ops.empty()) {
1549       // The entry token is the only possible outcome.
1550       Result = DAG.getEntryNode();
1551     } else {
1552       // New and improved token factor.
1553       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1554     }
1555
1556     // Add users to worklist if AA is enabled, since it may introduce
1557     // a lot of new chained token factors while removing memory deps.
1558     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559       : DAG.getSubtarget().useAA();
1560     return CombineTo(N, Result, UseAA /*add to worklist*/);
1561   }
1562
1563   return Result;
1564 }
1565
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568   WorklistRemover DeadNodes(*this);
1569   // Replacing results may cause a different MERGE_VALUES to suddenly
1570   // be CSE'd with N, and carry its uses with it. Iterate until no
1571   // uses remain, to ensure that the node can be safely deleted.
1572   // First add the users of this node to the work list so that they
1573   // can be tried again once they have new operands.
1574   AddUsersToWorklist(N);
1575   do {
1576     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578   } while (!N->use_empty());
1579   deleteAndRecombine(N);
1580   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1581 }
1582
1583 SDValue DAGCombiner::visitADD(SDNode *N) {
1584   SDValue N0 = N->getOperand(0);
1585   SDValue N1 = N->getOperand(1);
1586   EVT VT = N0.getValueType();
1587
1588   // fold vector ops
1589   if (VT.isVector()) {
1590     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1591       return FoldedVOp;
1592
1593     // fold (add x, 0) -> x, vector edition
1594     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1595       return N0;
1596     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1597       return N1;
1598   }
1599
1600   // fold (add x, undef) -> undef
1601   if (N0.getOpcode() == ISD::UNDEF)
1602     return N0;
1603   if (N1.getOpcode() == ISD::UNDEF)
1604     return N1;
1605   // fold (add c1, c2) -> c1+c2
1606   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1607   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1608   if (N0C && N1C)
1609     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1610   // canonicalize constant to RHS
1611   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1612      !isConstantIntBuildVectorOrConstantInt(N1))
1613     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1614   // fold (add x, 0) -> x
1615   if (N1C && N1C->isNullValue())
1616     return N0;
1617   // fold (add Sym, c) -> Sym+c
1618   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1619     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1620         GA->getOpcode() == ISD::GlobalAddress)
1621       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1622                                   GA->getOffset() +
1623                                     (uint64_t)N1C->getSExtValue());
1624   // fold ((c1-A)+c2) -> (c1+c2)-A
1625   if (N1C && N0.getOpcode() == ISD::SUB)
1626     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1627       SDLoc DL(N);
1628       return DAG.getNode(ISD::SUB, DL, VT,
1629                          DAG.getConstant(N1C->getAPIntValue()+
1630                                          N0C->getAPIntValue(), DL, VT),
1631                          N0.getOperand(1));
1632     }
1633   // reassociate add
1634   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1635     return RADD;
1636   // fold ((0-A) + B) -> B-A
1637   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1638       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1639     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1640   // fold (A + (0-B)) -> A-B
1641   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1642       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1643     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1644   // fold (A+(B-A)) -> B
1645   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1646     return N1.getOperand(0);
1647   // fold ((B-A)+A) -> B
1648   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1649     return N0.getOperand(0);
1650   // fold (A+(B-(A+C))) to (B-C)
1651   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1652       N0 == N1.getOperand(1).getOperand(0))
1653     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1654                        N1.getOperand(1).getOperand(1));
1655   // fold (A+(B-(C+A))) to (B-C)
1656   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1657       N0 == N1.getOperand(1).getOperand(1))
1658     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1659                        N1.getOperand(1).getOperand(0));
1660   // fold (A+((B-A)+or-C)) to (B+or-C)
1661   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1662       N1.getOperand(0).getOpcode() == ISD::SUB &&
1663       N0 == N1.getOperand(0).getOperand(1))
1664     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1665                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1666
1667   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1668   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1669     SDValue N00 = N0.getOperand(0);
1670     SDValue N01 = N0.getOperand(1);
1671     SDValue N10 = N1.getOperand(0);
1672     SDValue N11 = N1.getOperand(1);
1673
1674     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1675       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1676                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1677                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1678   }
1679
1680   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1681     return SDValue(N, 0);
1682
1683   // fold (a+b) -> (a|b) iff a and b share no bits.
1684   if (VT.isInteger() && !VT.isVector()) {
1685     APInt LHSZero, LHSOne;
1686     APInt RHSZero, RHSOne;
1687     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1688
1689     if (LHSZero.getBoolValue()) {
1690       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1691
1692       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1693       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1694       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1695         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1696           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1697       }
1698     }
1699   }
1700
1701   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1702   if (N1.getOpcode() == ISD::SHL &&
1703       N1.getOperand(0).getOpcode() == ISD::SUB)
1704     if (ConstantSDNode *C =
1705           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1706       if (C->getAPIntValue() == 0)
1707         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1708                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709                                        N1.getOperand(0).getOperand(1),
1710                                        N1.getOperand(1)));
1711   if (N0.getOpcode() == ISD::SHL &&
1712       N0.getOperand(0).getOpcode() == ISD::SUB)
1713     if (ConstantSDNode *C =
1714           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1715       if (C->getAPIntValue() == 0)
1716         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1717                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1718                                        N0.getOperand(0).getOperand(1),
1719                                        N0.getOperand(1)));
1720
1721   if (N1.getOpcode() == ISD::AND) {
1722     SDValue AndOp0 = N1.getOperand(0);
1723     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1724     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1725     unsigned DestBits = VT.getScalarType().getSizeInBits();
1726
1727     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1728     // and similar xforms where the inner op is either ~0 or 0.
1729     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1730       SDLoc DL(N);
1731       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1732     }
1733   }
1734
1735   // add (sext i1), X -> sub X, (zext i1)
1736   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1737       N0.getOperand(0).getValueType() == MVT::i1 &&
1738       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1739     SDLoc DL(N);
1740     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1741     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1742   }
1743
1744   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1745   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1746     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1747     if (TN->getVT() == MVT::i1) {
1748       SDLoc DL(N);
1749       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1750                                  DAG.getConstant(1, DL, VT));
1751       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1752     }
1753   }
1754
1755   return SDValue();
1756 }
1757
1758 SDValue DAGCombiner::visitADDC(SDNode *N) {
1759   SDValue N0 = N->getOperand(0);
1760   SDValue N1 = N->getOperand(1);
1761   EVT VT = N0.getValueType();
1762
1763   // If the flag result is dead, turn this into an ADD.
1764   if (!N->hasAnyUseOfValue(1))
1765     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1766                      DAG.getNode(ISD::CARRY_FALSE,
1767                                  SDLoc(N), MVT::Glue));
1768
1769   // canonicalize constant to RHS.
1770   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1771   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1772   if (N0C && !N1C)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1774
1775   // fold (addc x, 0) -> x + no carry out
1776   if (N1C && N1C->isNullValue())
1777     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1778                                         SDLoc(N), MVT::Glue));
1779
1780   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1781   APInt LHSZero, LHSOne;
1782   APInt RHSZero, RHSOne;
1783   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1784
1785   if (LHSZero.getBoolValue()) {
1786     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1787
1788     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1789     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1790     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1791       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1792                        DAG.getNode(ISD::CARRY_FALSE,
1793                                    SDLoc(N), MVT::Glue));
1794   }
1795
1796   return SDValue();
1797 }
1798
1799 SDValue DAGCombiner::visitADDE(SDNode *N) {
1800   SDValue N0 = N->getOperand(0);
1801   SDValue N1 = N->getOperand(1);
1802   SDValue CarryIn = N->getOperand(2);
1803
1804   // canonicalize constant to RHS
1805   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1806   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1807   if (N0C && !N1C)
1808     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1809                        N1, N0, CarryIn);
1810
1811   // fold (adde x, y, false) -> (addc x, y)
1812   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1813     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1814
1815   return SDValue();
1816 }
1817
1818 // Since it may not be valid to emit a fold to zero for vector initializers
1819 // check if we can before folding.
1820 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1821                              SelectionDAG &DAG,
1822                              bool LegalOperations, bool LegalTypes) {
1823   if (!VT.isVector())
1824     return DAG.getConstant(0, DL, VT);
1825   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1826     return DAG.getConstant(0, DL, VT);
1827   return SDValue();
1828 }
1829
1830 SDValue DAGCombiner::visitSUB(SDNode *N) {
1831   SDValue N0 = N->getOperand(0);
1832   SDValue N1 = N->getOperand(1);
1833   EVT VT = N0.getValueType();
1834
1835   // fold vector ops
1836   if (VT.isVector()) {
1837     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1838       return FoldedVOp;
1839
1840     // fold (sub x, 0) -> x, vector edition
1841     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1842       return N0;
1843   }
1844
1845   // fold (sub x, x) -> 0
1846   // FIXME: Refactor this and xor and other similar operations together.
1847   if (N0 == N1)
1848     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1849   // fold (sub c1, c2) -> c1-c2
1850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1852   if (N0C && N1C)
1853     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1854   // fold (sub x, c) -> (add x, -c)
1855   if (N1C) {
1856     SDLoc DL(N);
1857     return DAG.getNode(ISD::ADD, DL, VT, N0,
1858                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1859   }
1860   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1861   if (N0C && N0C->isAllOnesValue())
1862     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1863   // fold A-(A-B) -> B
1864   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1865     return N1.getOperand(1);
1866   // fold (A+B)-A -> B
1867   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1868     return N0.getOperand(1);
1869   // fold (A+B)-B -> A
1870   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1871     return N0.getOperand(0);
1872   // fold C2-(A+C1) -> (C2-C1)-A
1873   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1874     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1875   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1876     SDLoc DL(N);
1877     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1878                                    DL, VT);
1879     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1880                        N1.getOperand(0));
1881   }
1882   // fold ((A+(B+or-C))-B) -> A+or-C
1883   if (N0.getOpcode() == ISD::ADD &&
1884       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1885        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1886       N0.getOperand(1).getOperand(0) == N1)
1887     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1888                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1889   // fold ((A+(C+B))-B) -> A+C
1890   if (N0.getOpcode() == ISD::ADD &&
1891       N0.getOperand(1).getOpcode() == ISD::ADD &&
1892       N0.getOperand(1).getOperand(1) == N1)
1893     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1894                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1895   // fold ((A-(B-C))-C) -> A-B
1896   if (N0.getOpcode() == ISD::SUB &&
1897       N0.getOperand(1).getOpcode() == ISD::SUB &&
1898       N0.getOperand(1).getOperand(1) == N1)
1899     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1900                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1901
1902   // If either operand of a sub is undef, the result is undef
1903   if (N0.getOpcode() == ISD::UNDEF)
1904     return N0;
1905   if (N1.getOpcode() == ISD::UNDEF)
1906     return N1;
1907
1908   // If the relocation model supports it, consider symbol offsets.
1909   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1910     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1911       // fold (sub Sym, c) -> Sym-c
1912       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1913         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1914                                     GA->getOffset() -
1915                                       (uint64_t)N1C->getSExtValue());
1916       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1917       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1918         if (GA->getGlobal() == GB->getGlobal())
1919           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1920                                  SDLoc(N), VT);
1921     }
1922
1923   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1924   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1925     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1926     if (TN->getVT() == MVT::i1) {
1927       SDLoc DL(N);
1928       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1929                                  DAG.getConstant(1, DL, VT));
1930       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1931     }
1932   }
1933
1934   return SDValue();
1935 }
1936
1937 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1938   SDValue N0 = N->getOperand(0);
1939   SDValue N1 = N->getOperand(1);
1940   EVT VT = N0.getValueType();
1941
1942   // If the flag result is dead, turn this into an SUB.
1943   if (!N->hasAnyUseOfValue(1))
1944     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1945                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1946                                  MVT::Glue));
1947
1948   // fold (subc x, x) -> 0 + no borrow
1949   if (N0 == N1) {
1950     SDLoc DL(N);
1951     return CombineTo(N, DAG.getConstant(0, DL, VT),
1952                      DAG.getNode(ISD::CARRY_FALSE, DL,
1953                                  MVT::Glue));
1954   }
1955
1956   // fold (subc x, 0) -> x + no borrow
1957   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1958   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1959   if (N1C && N1C->isNullValue())
1960     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1961                                         MVT::Glue));
1962
1963   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1964   if (N0C && N0C->isAllOnesValue())
1965     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1966                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1967                                  MVT::Glue));
1968
1969   return SDValue();
1970 }
1971
1972 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   SDValue CarryIn = N->getOperand(2);
1976
1977   // fold (sube x, y, false) -> (subc x, y)
1978   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1979     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1980
1981   return SDValue();
1982 }
1983
1984 SDValue DAGCombiner::visitMUL(SDNode *N) {
1985   SDValue N0 = N->getOperand(0);
1986   SDValue N1 = N->getOperand(1);
1987   EVT VT = N0.getValueType();
1988
1989   // fold (mul x, undef) -> 0
1990   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1991     return DAG.getConstant(0, SDLoc(N), VT);
1992
1993   bool N0IsConst = false;
1994   bool N1IsConst = false;
1995   APInt ConstValue0, ConstValue1;
1996   // fold vector ops
1997   if (VT.isVector()) {
1998     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1999       return FoldedVOp;
2000
2001     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2002     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2003   } else {
2004     N0IsConst = isa<ConstantSDNode>(N0);
2005     if (N0IsConst)
2006       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2007     N1IsConst = isa<ConstantSDNode>(N1);
2008     if (N1IsConst)
2009       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2010   }
2011
2012   // fold (mul c1, c2) -> c1*c2
2013   if (N0IsConst && N1IsConst)
2014     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2015                                       N0.getNode(), N1.getNode());
2016
2017   // canonicalize constant to RHS (vector doesn't have to splat)
2018   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2019      !isConstantIntBuildVectorOrConstantInt(N1))
2020     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2021   // fold (mul x, 0) -> 0
2022   if (N1IsConst && ConstValue1 == 0)
2023     return N1;
2024   // We require a splat of the entire scalar bit width for non-contiguous
2025   // bit patterns.
2026   bool IsFullSplat =
2027     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2028   // fold (mul x, 1) -> x
2029   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2030     return N0;
2031   // fold (mul x, -1) -> 0-x
2032   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2033     SDLoc DL(N);
2034     return DAG.getNode(ISD::SUB, DL, VT,
2035                        DAG.getConstant(0, DL, VT), N0);
2036   }
2037   // fold (mul x, (1 << c)) -> x << c
2038   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2039     SDLoc DL(N);
2040     return DAG.getNode(ISD::SHL, DL, VT, N0,
2041                        DAG.getConstant(ConstValue1.logBase2(), DL,
2042                                        getShiftAmountTy(N0.getValueType())));
2043   }
2044   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2045   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2046     unsigned Log2Val = (-ConstValue1).logBase2();
2047     SDLoc DL(N);
2048     // FIXME: If the input is something that is easily negated (e.g. a
2049     // single-use add), we should put the negate there.
2050     return DAG.getNode(ISD::SUB, DL, VT,
2051                        DAG.getConstant(0, DL, VT),
2052                        DAG.getNode(ISD::SHL, DL, VT, N0,
2053                             DAG.getConstant(Log2Val, DL,
2054                                       getShiftAmountTy(N0.getValueType()))));
2055   }
2056
2057   APInt Val;
2058   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2059   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2060       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2061                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2062     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2063                              N1, N0.getOperand(1));
2064     AddToWorklist(C3.getNode());
2065     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2066                        N0.getOperand(0), C3);
2067   }
2068
2069   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2070   // use.
2071   {
2072     SDValue Sh(nullptr,0), Y(nullptr,0);
2073     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2074     if (N0.getOpcode() == ISD::SHL &&
2075         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2076                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2077         N0.getNode()->hasOneUse()) {
2078       Sh = N0; Y = N1;
2079     } else if (N1.getOpcode() == ISD::SHL &&
2080                isa<ConstantSDNode>(N1.getOperand(1)) &&
2081                N1.getNode()->hasOneUse()) {
2082       Sh = N1; Y = N0;
2083     }
2084
2085     if (Sh.getNode()) {
2086       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2087                                 Sh.getOperand(0), Y);
2088       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2089                          Mul, Sh.getOperand(1));
2090     }
2091   }
2092
2093   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2094   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2095       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2096                      isa<ConstantSDNode>(N0.getOperand(1))))
2097     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2098                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2099                                    N0.getOperand(0), N1),
2100                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2101                                    N0.getOperand(1), N1));
2102
2103   // reassociate mul
2104   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2105     return RMUL;
2106
2107   return SDValue();
2108 }
2109
2110 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2111   SDValue N0 = N->getOperand(0);
2112   SDValue N1 = N->getOperand(1);
2113   EVT VT = N->getValueType(0);
2114
2115   // fold vector ops
2116   if (VT.isVector())
2117     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2118       return FoldedVOp;
2119
2120   // fold (sdiv c1, c2) -> c1/c2
2121   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123   if (N0C && N1C && !N1C->isNullValue())
2124     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2125   // fold (sdiv X, 1) -> X
2126   if (N1C && N1C->getAPIntValue() == 1LL)
2127     return N0;
2128   // fold (sdiv X, -1) -> 0-X
2129   if (N1C && N1C->isAllOnesValue()) {
2130     SDLoc DL(N);
2131     return DAG.getNode(ISD::SUB, DL, VT,
2132                        DAG.getConstant(0, DL, VT), N0);
2133   }
2134   // If we know the sign bits of both operands are zero, strength reduce to a
2135   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2136   if (!VT.isVector()) {
2137     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2138       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2139                          N0, N1);
2140   }
2141
2142   // fold (sdiv X, pow2) -> simple ops after legalize
2143   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2144                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2145     // If dividing by powers of two is cheap, then don't perform the following
2146     // fold.
2147     if (TLI.isPow2SDivCheap())
2148       return SDValue();
2149
2150     // Target-specific implementation of sdiv x, pow2.
2151     SDValue Res = BuildSDIVPow2(N);
2152     if (Res.getNode())
2153       return Res;
2154
2155     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2156     SDLoc DL(N);
2157
2158     // Splat the sign bit into the register
2159     SDValue SGN =
2160         DAG.getNode(ISD::SRA, DL, VT, N0,
2161                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2162                                     getShiftAmountTy(N0.getValueType())));
2163     AddToWorklist(SGN.getNode());
2164
2165     // Add (N0 < 0) ? abs2 - 1 : 0;
2166     SDValue SRL =
2167         DAG.getNode(ISD::SRL, DL, VT, SGN,
2168                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2169                                     getShiftAmountTy(SGN.getValueType())));
2170     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2171     AddToWorklist(SRL.getNode());
2172     AddToWorklist(ADD.getNode());    // Divide by pow2
2173     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2174                   DAG.getConstant(lg2, DL,
2175                                   getShiftAmountTy(ADD.getValueType())));
2176
2177     // If we're dividing by a positive value, we're done.  Otherwise, we must
2178     // negate the result.
2179     if (N1C->getAPIntValue().isNonNegative())
2180       return SRA;
2181
2182     AddToWorklist(SRA.getNode());
2183     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2184   }
2185
2186   // If integer divide is expensive and we satisfy the requirements, emit an
2187   // alternate sequence.
2188   if (N1C && !TLI.isIntDivCheap()) {
2189     SDValue Op = BuildSDIV(N);
2190     if (Op.getNode()) return Op;
2191   }
2192
2193   // undef / X -> 0
2194   if (N0.getOpcode() == ISD::UNDEF)
2195     return DAG.getConstant(0, SDLoc(N), VT);
2196   // X / undef -> undef
2197   if (N1.getOpcode() == ISD::UNDEF)
2198     return N1;
2199
2200   return SDValue();
2201 }
2202
2203 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2204   SDValue N0 = N->getOperand(0);
2205   SDValue N1 = N->getOperand(1);
2206   EVT VT = N->getValueType(0);
2207
2208   // fold vector ops
2209   if (VT.isVector())
2210     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2211       return FoldedVOp;
2212
2213   // fold (udiv c1, c2) -> c1/c2
2214   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2215   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2216   if (N0C && N1C && !N1C->isNullValue())
2217     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2218   // fold (udiv x, (1 << c)) -> x >>u c
2219   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2220     SDLoc DL(N);
2221     return DAG.getNode(ISD::SRL, DL, VT, N0,
2222                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2223                                        getShiftAmountTy(N0.getValueType())));
2224   }
2225   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2226   if (N1.getOpcode() == ISD::SHL) {
2227     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2228       if (SHC->getAPIntValue().isPowerOf2()) {
2229         EVT ADDVT = N1.getOperand(1).getValueType();
2230         SDLoc DL(N);
2231         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2232                                   N1.getOperand(1),
2233                                   DAG.getConstant(SHC->getAPIntValue()
2234                                                                   .logBase2(),
2235                                                   DL, ADDVT));
2236         AddToWorklist(Add.getNode());
2237         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2238       }
2239     }
2240   }
2241   // fold (udiv x, c) -> alternate
2242   if (N1C && !TLI.isIntDivCheap()) {
2243     SDValue Op = BuildUDIV(N);
2244     if (Op.getNode()) return Op;
2245   }
2246
2247   // undef / X -> 0
2248   if (N0.getOpcode() == ISD::UNDEF)
2249     return DAG.getConstant(0, SDLoc(N), VT);
2250   // X / undef -> undef
2251   if (N1.getOpcode() == ISD::UNDEF)
2252     return N1;
2253
2254   return SDValue();
2255 }
2256
2257 SDValue DAGCombiner::visitSREM(SDNode *N) {
2258   SDValue N0 = N->getOperand(0);
2259   SDValue N1 = N->getOperand(1);
2260   EVT VT = N->getValueType(0);
2261
2262   // fold (srem c1, c2) -> c1%c2
2263   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2264   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2265   if (N0C && N1C && !N1C->isNullValue())
2266     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2267   // If we know the sign bits of both operands are zero, strength reduce to a
2268   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2269   if (!VT.isVector()) {
2270     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2271       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2272   }
2273
2274   // If X/C can be simplified by the division-by-constant logic, lower
2275   // X%C to the equivalent of X-X/C*C.
2276   if (N1C && !N1C->isNullValue()) {
2277     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2278     AddToWorklist(Div.getNode());
2279     SDValue OptimizedDiv = combine(Div.getNode());
2280     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2281       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2282                                 OptimizedDiv, N1);
2283       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2284       AddToWorklist(Mul.getNode());
2285       return Sub;
2286     }
2287   }
2288
2289   // undef % X -> 0
2290   if (N0.getOpcode() == ISD::UNDEF)
2291     return DAG.getConstant(0, SDLoc(N), VT);
2292   // X % undef -> undef
2293   if (N1.getOpcode() == ISD::UNDEF)
2294     return N1;
2295
2296   return SDValue();
2297 }
2298
2299 SDValue DAGCombiner::visitUREM(SDNode *N) {
2300   SDValue N0 = N->getOperand(0);
2301   SDValue N1 = N->getOperand(1);
2302   EVT VT = N->getValueType(0);
2303
2304   // fold (urem c1, c2) -> c1%c2
2305   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2307   if (N0C && N1C && !N1C->isNullValue())
2308     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2309   // fold (urem x, pow2) -> (and x, pow2-1)
2310   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2311     SDLoc DL(N);
2312     return DAG.getNode(ISD::AND, DL, VT, N0,
2313                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2314   }
2315   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2316   if (N1.getOpcode() == ISD::SHL) {
2317     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2318       if (SHC->getAPIntValue().isPowerOf2()) {
2319         SDLoc DL(N);
2320         SDValue Add =
2321           DAG.getNode(ISD::ADD, DL, VT, N1,
2322                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2323                                  VT));
2324         AddToWorklist(Add.getNode());
2325         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2326       }
2327     }
2328   }
2329
2330   // If X/C can be simplified by the division-by-constant logic, lower
2331   // X%C to the equivalent of X-X/C*C.
2332   if (N1C && !N1C->isNullValue()) {
2333     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2334     AddToWorklist(Div.getNode());
2335     SDValue OptimizedDiv = combine(Div.getNode());
2336     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2338                                 OptimizedDiv, N1);
2339       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340       AddToWorklist(Mul.getNode());
2341       return Sub;
2342     }
2343   }
2344
2345   // undef % X -> 0
2346   if (N0.getOpcode() == ISD::UNDEF)
2347     return DAG.getConstant(0, SDLoc(N), VT);
2348   // X % undef -> undef
2349   if (N1.getOpcode() == ISD::UNDEF)
2350     return N1;
2351
2352   return SDValue();
2353 }
2354
2355 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2356   SDValue N0 = N->getOperand(0);
2357   SDValue N1 = N->getOperand(1);
2358   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2359   EVT VT = N->getValueType(0);
2360   SDLoc DL(N);
2361
2362   // fold (mulhs x, 0) -> 0
2363   if (N1C && N1C->isNullValue())
2364     return N1;
2365   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2366   if (N1C && N1C->getAPIntValue() == 1) {
2367     SDLoc DL(N);
2368     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2369                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2370                                        DL,
2371                                        getShiftAmountTy(N0.getValueType())));
2372   }
2373   // fold (mulhs x, undef) -> 0
2374   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2375     return DAG.getConstant(0, SDLoc(N), VT);
2376
2377   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2378   // plus a shift.
2379   if (VT.isSimple() && !VT.isVector()) {
2380     MVT Simple = VT.getSimpleVT();
2381     unsigned SimpleSize = Simple.getSizeInBits();
2382     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2385       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2386       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2387       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2388             DAG.getConstant(SimpleSize, DL,
2389                             getShiftAmountTy(N1.getValueType())));
2390       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2391     }
2392   }
2393
2394   return SDValue();
2395 }
2396
2397 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2398   SDValue N0 = N->getOperand(0);
2399   SDValue N1 = N->getOperand(1);
2400   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2401   EVT VT = N->getValueType(0);
2402   SDLoc DL(N);
2403
2404   // fold (mulhu x, 0) -> 0
2405   if (N1C && N1C->isNullValue())
2406     return N1;
2407   // fold (mulhu x, 1) -> 0
2408   if (N1C && N1C->getAPIntValue() == 1)
2409     return DAG.getConstant(0, DL, N0.getValueType());
2410   // fold (mulhu x, undef) -> 0
2411   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2412     return DAG.getConstant(0, DL, VT);
2413
2414   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2415   // plus a shift.
2416   if (VT.isSimple() && !VT.isVector()) {
2417     MVT Simple = VT.getSimpleVT();
2418     unsigned SimpleSize = Simple.getSizeInBits();
2419     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2420     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2421       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2422       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2423       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2424       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2425             DAG.getConstant(SimpleSize, DL,
2426                             getShiftAmountTy(N1.getValueType())));
2427       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2428     }
2429   }
2430
2431   return SDValue();
2432 }
2433
2434 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2435 /// give the opcodes for the two computations that are being performed. Return
2436 /// true if a simplification was made.
2437 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2438                                                 unsigned HiOp) {
2439   // If the high half is not needed, just compute the low half.
2440   bool HiExists = N->hasAnyUseOfValue(1);
2441   if (!HiExists &&
2442       (!LegalOperations ||
2443        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2444     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2445     return CombineTo(N, Res, Res);
2446   }
2447
2448   // If the low half is not needed, just compute the high half.
2449   bool LoExists = N->hasAnyUseOfValue(0);
2450   if (!LoExists &&
2451       (!LegalOperations ||
2452        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2453     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2454     return CombineTo(N, Res, Res);
2455   }
2456
2457   // If both halves are used, return as it is.
2458   if (LoExists && HiExists)
2459     return SDValue();
2460
2461   // If the two computed results can be simplified separately, separate them.
2462   if (LoExists) {
2463     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2464     AddToWorklist(Lo.getNode());
2465     SDValue LoOpt = combine(Lo.getNode());
2466     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2467         (!LegalOperations ||
2468          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2469       return CombineTo(N, LoOpt, LoOpt);
2470   }
2471
2472   if (HiExists) {
2473     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2474     AddToWorklist(Hi.getNode());
2475     SDValue HiOpt = combine(Hi.getNode());
2476     if (HiOpt.getNode() && HiOpt != Hi &&
2477         (!LegalOperations ||
2478          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2479       return CombineTo(N, HiOpt, HiOpt);
2480   }
2481
2482   return SDValue();
2483 }
2484
2485 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2486   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2487   if (Res.getNode()) return Res;
2488
2489   EVT VT = N->getValueType(0);
2490   SDLoc DL(N);
2491
2492   // If the type is twice as wide is legal, transform the mulhu to a wider
2493   // multiply plus a shift.
2494   if (VT.isSimple() && !VT.isVector()) {
2495     MVT Simple = VT.getSimpleVT();
2496     unsigned SimpleSize = Simple.getSizeInBits();
2497     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2500       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2501       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502       // Compute the high part as N1.
2503       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504             DAG.getConstant(SimpleSize, DL,
2505                             getShiftAmountTy(Lo.getValueType())));
2506       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2507       // Compute the low part as N0.
2508       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2509       return CombineTo(N, Lo, Hi);
2510     }
2511   }
2512
2513   return SDValue();
2514 }
2515
2516 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2517   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2518   if (Res.getNode()) return Res;
2519
2520   EVT VT = N->getValueType(0);
2521   SDLoc DL(N);
2522
2523   // If the type is twice as wide is legal, transform the mulhu to a wider
2524   // multiply plus a shift.
2525   if (VT.isSimple() && !VT.isVector()) {
2526     MVT Simple = VT.getSimpleVT();
2527     unsigned SimpleSize = Simple.getSizeInBits();
2528     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2529     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2530       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2531       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2532       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2533       // Compute the high part as N1.
2534       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2535             DAG.getConstant(SimpleSize, DL,
2536                             getShiftAmountTy(Lo.getValueType())));
2537       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2538       // Compute the low part as N0.
2539       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2540       return CombineTo(N, Lo, Hi);
2541     }
2542   }
2543
2544   return SDValue();
2545 }
2546
2547 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2548   // (smulo x, 2) -> (saddo x, x)
2549   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2550     if (C2->getAPIntValue() == 2)
2551       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2552                          N->getOperand(0), N->getOperand(0));
2553
2554   return SDValue();
2555 }
2556
2557 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2558   // (umulo x, 2) -> (uaddo x, x)
2559   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2560     if (C2->getAPIntValue() == 2)
2561       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2562                          N->getOperand(0), N->getOperand(0));
2563
2564   return SDValue();
2565 }
2566
2567 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2568   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2569   if (Res.getNode()) return Res;
2570
2571   return SDValue();
2572 }
2573
2574 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2575   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2576   if (Res.getNode()) return Res;
2577
2578   return SDValue();
2579 }
2580
2581 /// If this is a binary operator with two operands of the same opcode, try to
2582 /// simplify it.
2583 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2584   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2585   EVT VT = N0.getValueType();
2586   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2587
2588   // Bail early if none of these transforms apply.
2589   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2590
2591   // For each of OP in AND/OR/XOR:
2592   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2593   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2594   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2595   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2596   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2597   //
2598   // do not sink logical op inside of a vector extend, since it may combine
2599   // into a vsetcc.
2600   EVT Op0VT = N0.getOperand(0).getValueType();
2601   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2602        N0.getOpcode() == ISD::SIGN_EXTEND ||
2603        N0.getOpcode() == ISD::BSWAP ||
2604        // Avoid infinite looping with PromoteIntBinOp.
2605        (N0.getOpcode() == ISD::ANY_EXTEND &&
2606         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2607        (N0.getOpcode() == ISD::TRUNCATE &&
2608         (!TLI.isZExtFree(VT, Op0VT) ||
2609          !TLI.isTruncateFree(Op0VT, VT)) &&
2610         TLI.isTypeLegal(Op0VT))) &&
2611       !VT.isVector() &&
2612       Op0VT == N1.getOperand(0).getValueType() &&
2613       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2614     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2615                                  N0.getOperand(0).getValueType(),
2616                                  N0.getOperand(0), N1.getOperand(0));
2617     AddToWorklist(ORNode.getNode());
2618     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2619   }
2620
2621   // For each of OP in SHL/SRL/SRA/AND...
2622   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2623   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2624   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2625   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2626        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2627       N0.getOperand(1) == N1.getOperand(1)) {
2628     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2629                                  N0.getOperand(0).getValueType(),
2630                                  N0.getOperand(0), N1.getOperand(0));
2631     AddToWorklist(ORNode.getNode());
2632     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2633                        ORNode, N0.getOperand(1));
2634   }
2635
2636   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2637   // Only perform this optimization after type legalization and before
2638   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2639   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2640   // we don't want to undo this promotion.
2641   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2642   // on scalars.
2643   if ((N0.getOpcode() == ISD::BITCAST ||
2644        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2645       Level == AfterLegalizeTypes) {
2646     SDValue In0 = N0.getOperand(0);
2647     SDValue In1 = N1.getOperand(0);
2648     EVT In0Ty = In0.getValueType();
2649     EVT In1Ty = In1.getValueType();
2650     SDLoc DL(N);
2651     // If both incoming values are integers, and the original types are the
2652     // same.
2653     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2654       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2655       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2656       AddToWorklist(Op.getNode());
2657       return BC;
2658     }
2659   }
2660
2661   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2662   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2663   // If both shuffles use the same mask, and both shuffle within a single
2664   // vector, then it is worthwhile to move the swizzle after the operation.
2665   // The type-legalizer generates this pattern when loading illegal
2666   // vector types from memory. In many cases this allows additional shuffle
2667   // optimizations.
2668   // There are other cases where moving the shuffle after the xor/and/or
2669   // is profitable even if shuffles don't perform a swizzle.
2670   // If both shuffles use the same mask, and both shuffles have the same first
2671   // or second operand, then it might still be profitable to move the shuffle
2672   // after the xor/and/or operation.
2673   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2674     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2675     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2676
2677     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2678            "Inputs to shuffles are not the same type");
2679
2680     // Check that both shuffles use the same mask. The masks are known to be of
2681     // the same length because the result vector type is the same.
2682     // Check also that shuffles have only one use to avoid introducing extra
2683     // instructions.
2684     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2685         SVN0->getMask().equals(SVN1->getMask())) {
2686       SDValue ShOp = N0->getOperand(1);
2687
2688       // Don't try to fold this node if it requires introducing a
2689       // build vector of all zeros that might be illegal at this stage.
2690       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2691         if (!LegalTypes)
2692           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2693         else
2694           ShOp = SDValue();
2695       }
2696
2697       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2698       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2699       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2700       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2701         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2702                                       N0->getOperand(0), N1->getOperand(0));
2703         AddToWorklist(NewNode.getNode());
2704         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2705                                     &SVN0->getMask()[0]);
2706       }
2707
2708       // Don't try to fold this node if it requires introducing a
2709       // build vector of all zeros that might be illegal at this stage.
2710       ShOp = N0->getOperand(0);
2711       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2712         if (!LegalTypes)
2713           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2714         else
2715           ShOp = SDValue();
2716       }
2717
2718       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2719       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2720       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2721       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2722         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2723                                       N0->getOperand(1), N1->getOperand(1));
2724         AddToWorklist(NewNode.getNode());
2725         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2726                                     &SVN0->getMask()[0]);
2727       }
2728     }
2729   }
2730
2731   return SDValue();
2732 }
2733
2734 /// This contains all DAGCombine rules which reduce two values combined by
2735 /// an And operation to a single value. This makes them reusable in the context
2736 /// of visitSELECT(). Rules involving constants are not included as
2737 /// visitSELECT() already handles those cases.
2738 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2739                                   SDNode *LocReference) {
2740   EVT VT = N1.getValueType();
2741
2742   // fold (and x, undef) -> 0
2743   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2744     return DAG.getConstant(0, SDLoc(LocReference), VT);
2745   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746   SDValue LL, LR, RL, RR, CC0, CC1;
2747   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2748     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2749     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2750
2751     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2752         LL.getValueType().isInteger()) {
2753       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2754       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2755         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2756                                      LR.getValueType(), LL, RL);
2757         AddToWorklist(ORNode.getNode());
2758         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2759       }
2760       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2761       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2762         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2763                                       LR.getValueType(), LL, RL);
2764         AddToWorklist(ANDNode.getNode());
2765         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2766       }
2767       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2768       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2769         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770                                      LR.getValueType(), LL, RL);
2771         AddToWorklist(ORNode.getNode());
2772         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2773       }
2774     }
2775     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2776     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2777         Op0 == Op1 && LL.getValueType().isInteger() &&
2778       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2779                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2780                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2781                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2782       SDLoc DL(N0);
2783       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2784                                     LL, DAG.getConstant(1, DL,
2785                                                         LL.getValueType()));
2786       AddToWorklist(ADDNode.getNode());
2787       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2788                           DAG.getConstant(2, DL, LL.getValueType()),
2789                           ISD::SETUGE);
2790     }
2791     // canonicalize equivalent to ll == rl
2792     if (LL == RR && LR == RL) {
2793       Op1 = ISD::getSetCCSwappedOperands(Op1);
2794       std::swap(RL, RR);
2795     }
2796     if (LL == RL && LR == RR) {
2797       bool isInteger = LL.getValueType().isInteger();
2798       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2799       if (Result != ISD::SETCC_INVALID &&
2800           (!LegalOperations ||
2801            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802             TLI.isOperationLegal(ISD::SETCC,
2803                             getSetCCResultType(N0.getSimpleValueType())))))
2804         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2805                             LL, LR, Result);
2806     }
2807   }
2808
2809   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2810       VT.getSizeInBits() <= 64) {
2811     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2812       APInt ADDC = ADDI->getAPIntValue();
2813       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2814         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2815         // immediate for an add, but it is legal if its top c2 bits are set,
2816         // transform the ADD so the immediate doesn't need to be materialized
2817         // in a register.
2818         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2819           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2820                                              SRLI->getZExtValue());
2821           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2822             ADDC |= Mask;
2823             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2824               SDLoc DL(N0);
2825               SDValue NewAdd =
2826                 DAG.getNode(ISD::ADD, DL, VT,
2827                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2828               CombineTo(N0.getNode(), NewAdd);
2829               // Return N so it doesn't get rechecked!
2830               return SDValue(LocReference, 0);
2831             }
2832           }
2833         }
2834       }
2835     }
2836   }
2837
2838   return SDValue();
2839 }
2840
2841 SDValue DAGCombiner::visitAND(SDNode *N) {
2842   SDValue N0 = N->getOperand(0);
2843   SDValue N1 = N->getOperand(1);
2844   EVT VT = N1.getValueType();
2845
2846   // fold vector ops
2847   if (VT.isVector()) {
2848     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2849       return FoldedVOp;
2850
2851     // fold (and x, 0) -> 0, vector edition
2852     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2853       // do not return N0, because undef node may exist in N0
2854       return DAG.getConstant(
2855           APInt::getNullValue(
2856               N0.getValueType().getScalarType().getSizeInBits()),
2857           SDLoc(N), N0.getValueType());
2858     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2859       // do not return N1, because undef node may exist in N1
2860       return DAG.getConstant(
2861           APInt::getNullValue(
2862               N1.getValueType().getScalarType().getSizeInBits()),
2863           SDLoc(N), N1.getValueType());
2864
2865     // fold (and x, -1) -> x, vector edition
2866     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2867       return N1;
2868     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2869       return N0;
2870   }
2871
2872   // fold (and c1, c2) -> c1&c2
2873   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2874   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2875   if (N0C && N1C)
2876     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2877   // canonicalize constant to RHS
2878   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2879      !isConstantIntBuildVectorOrConstantInt(N1))
2880     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2881   // fold (and x, -1) -> x
2882   if (N1C && N1C->isAllOnesValue())
2883     return N0;
2884   // if (and x, c) is known to be zero, return 0
2885   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2886   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2887                                    APInt::getAllOnesValue(BitWidth)))
2888     return DAG.getConstant(0, SDLoc(N), VT);
2889   // reassociate and
2890   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2891     return RAND;
2892   // fold (and (or x, C), D) -> D if (C & D) == D
2893   if (N1C && N0.getOpcode() == ISD::OR)
2894     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2895       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2896         return N1;
2897   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2898   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2899     SDValue N0Op0 = N0.getOperand(0);
2900     APInt Mask = ~N1C->getAPIntValue();
2901     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2902     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2903       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2904                                  N0.getValueType(), N0Op0);
2905
2906       // Replace uses of the AND with uses of the Zero extend node.
2907       CombineTo(N, Zext);
2908
2909       // We actually want to replace all uses of the any_extend with the
2910       // zero_extend, to avoid duplicating things.  This will later cause this
2911       // AND to be folded.
2912       CombineTo(N0.getNode(), Zext);
2913       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2914     }
2915   }
2916   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2917   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2918   // already be zero by virtue of the width of the base type of the load.
2919   //
2920   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2921   // more cases.
2922   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2923        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2924       N0.getOpcode() == ISD::LOAD) {
2925     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2926                                          N0 : N0.getOperand(0) );
2927
2928     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2929     // This can be a pure constant or a vector splat, in which case we treat the
2930     // vector as a scalar and use the splat value.
2931     APInt Constant = APInt::getNullValue(1);
2932     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2933       Constant = C->getAPIntValue();
2934     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2935       APInt SplatValue, SplatUndef;
2936       unsigned SplatBitSize;
2937       bool HasAnyUndefs;
2938       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2939                                              SplatBitSize, HasAnyUndefs);
2940       if (IsSplat) {
2941         // Undef bits can contribute to a possible optimisation if set, so
2942         // set them.
2943         SplatValue |= SplatUndef;
2944
2945         // The splat value may be something like "0x00FFFFFF", which means 0 for
2946         // the first vector value and FF for the rest, repeating. We need a mask
2947         // that will apply equally to all members of the vector, so AND all the
2948         // lanes of the constant together.
2949         EVT VT = Vector->getValueType(0);
2950         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2951
2952         // If the splat value has been compressed to a bitlength lower
2953         // than the size of the vector lane, we need to re-expand it to
2954         // the lane size.
2955         if (BitWidth > SplatBitSize)
2956           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2957                SplatBitSize < BitWidth;
2958                SplatBitSize = SplatBitSize * 2)
2959             SplatValue |= SplatValue.shl(SplatBitSize);
2960
2961         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2962         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2963         if (SplatBitSize % BitWidth == 0) {
2964           Constant = APInt::getAllOnesValue(BitWidth);
2965           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2966             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2967         }
2968       }
2969     }
2970
2971     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2972     // actually legal and isn't going to get expanded, else this is a false
2973     // optimisation.
2974     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2975                                                     Load->getValueType(0),
2976                                                     Load->getMemoryVT());
2977
2978     // Resize the constant to the same size as the original memory access before
2979     // extension. If it is still the AllOnesValue then this AND is completely
2980     // unneeded.
2981     Constant =
2982       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2983
2984     bool B;
2985     switch (Load->getExtensionType()) {
2986     default: B = false; break;
2987     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2988     case ISD::ZEXTLOAD:
2989     case ISD::NON_EXTLOAD: B = true; break;
2990     }
2991
2992     if (B && Constant.isAllOnesValue()) {
2993       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2994       // preserve semantics once we get rid of the AND.
2995       SDValue NewLoad(Load, 0);
2996       if (Load->getExtensionType() == ISD::EXTLOAD) {
2997         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2998                               Load->getValueType(0), SDLoc(Load),
2999                               Load->getChain(), Load->getBasePtr(),
3000                               Load->getOffset(), Load->getMemoryVT(),
3001                               Load->getMemOperand());
3002         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3003         if (Load->getNumValues() == 3) {
3004           // PRE/POST_INC loads have 3 values.
3005           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3006                            NewLoad.getValue(2) };
3007           CombineTo(Load, To, 3, true);
3008         } else {
3009           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3010         }
3011       }
3012
3013       // Fold the AND away, taking care not to fold to the old load node if we
3014       // replaced it.
3015       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3016
3017       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018     }
3019   }
3020
3021   // fold (and (load x), 255) -> (zextload x, i8)
3022   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3023   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3024   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3025               (N0.getOpcode() == ISD::ANY_EXTEND &&
3026                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3027     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3028     LoadSDNode *LN0 = HasAnyExt
3029       ? cast<LoadSDNode>(N0.getOperand(0))
3030       : cast<LoadSDNode>(N0);
3031     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3032         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3033       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3034       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3035         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036         EVT LoadedVT = LN0->getMemoryVT();
3037         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3038
3039         if (ExtVT == LoadedVT &&
3040             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3041                                                     ExtVT))) {
3042
3043           SDValue NewLoad =
3044             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3045                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3046                            LN0->getMemOperand());
3047           AddToWorklist(N);
3048           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3049           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3050         }
3051
3052         // Do not change the width of a volatile load.
3053         // Do not generate loads of non-round integer types since these can
3054         // be expensive (and would be wrong if the type is not byte sized).
3055         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3056             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3057                                                     ExtVT))) {
3058           EVT PtrType = LN0->getOperand(1).getValueType();
3059
3060           unsigned Alignment = LN0->getAlignment();
3061           SDValue NewPtr = LN0->getBasePtr();
3062
3063           // For big endian targets, we need to add an offset to the pointer
3064           // to load the correct bytes.  For little endian systems, we merely
3065           // need to read fewer bytes from the same pointer.
3066           if (TLI.isBigEndian()) {
3067             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3068             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3069             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3070             SDLoc DL(LN0);
3071             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3072                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3073             Alignment = MinAlign(Alignment, PtrOff);
3074           }
3075
3076           AddToWorklist(NewPtr.getNode());
3077
3078           SDValue Load =
3079             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3080                            LN0->getChain(), NewPtr,
3081                            LN0->getPointerInfo(),
3082                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3083                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3084           AddToWorklist(N);
3085           CombineTo(LN0, Load, Load.getValue(1));
3086           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3087         }
3088       }
3089     }
3090   }
3091
3092   if (SDValue Combined = visitANDLike(N0, N1, N))
3093     return Combined;
3094
3095   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3096   if (N0.getOpcode() == N1.getOpcode()) {
3097     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3098     if (Tmp.getNode()) return Tmp;
3099   }
3100
3101   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3102   // fold (and (sra)) -> (and (srl)) when possible.
3103   if (!VT.isVector() &&
3104       SimplifyDemandedBits(SDValue(N, 0)))
3105     return SDValue(N, 0);
3106
3107   // fold (zext_inreg (extload x)) -> (zextload x)
3108   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3109     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3110     EVT MemVT = LN0->getMemoryVT();
3111     // If we zero all the possible extended bits, then we can turn this into
3112     // a zextload if we are running before legalize or the operation is legal.
3113     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3114     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3115                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3116         ((!LegalOperations && !LN0->isVolatile()) ||
3117          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3118       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3119                                        LN0->getChain(), LN0->getBasePtr(),
3120                                        MemVT, LN0->getMemOperand());
3121       AddToWorklist(N);
3122       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3123       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3124     }
3125   }
3126   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3127   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3128       N0.hasOneUse()) {
3129     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3130     EVT MemVT = LN0->getMemoryVT();
3131     // If we zero all the possible extended bits, then we can turn this into
3132     // a zextload if we are running before legalize or the operation is legal.
3133     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3134     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3135                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3136         ((!LegalOperations && !LN0->isVolatile()) ||
3137          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3138       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3139                                        LN0->getChain(), LN0->getBasePtr(),
3140                                        MemVT, LN0->getMemOperand());
3141       AddToWorklist(N);
3142       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3143       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3144     }
3145   }
3146   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3147   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3148     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3149                                        N0.getOperand(1), false);
3150     if (BSwap.getNode())
3151       return BSwap;
3152   }
3153
3154   return SDValue();
3155 }
3156
3157 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3158 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3159                                         bool DemandHighBits) {
3160   if (!LegalOperations)
3161     return SDValue();
3162
3163   EVT VT = N->getValueType(0);
3164   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3165     return SDValue();
3166   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3167     return SDValue();
3168
3169   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3170   bool LookPassAnd0 = false;
3171   bool LookPassAnd1 = false;
3172   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3173       std::swap(N0, N1);
3174   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3175       std::swap(N0, N1);
3176   if (N0.getOpcode() == ISD::AND) {
3177     if (!N0.getNode()->hasOneUse())
3178       return SDValue();
3179     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3180     if (!N01C || N01C->getZExtValue() != 0xFF00)
3181       return SDValue();
3182     N0 = N0.getOperand(0);
3183     LookPassAnd0 = true;
3184   }
3185
3186   if (N1.getOpcode() == ISD::AND) {
3187     if (!N1.getNode()->hasOneUse())
3188       return SDValue();
3189     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3190     if (!N11C || N11C->getZExtValue() != 0xFF)
3191       return SDValue();
3192     N1 = N1.getOperand(0);
3193     LookPassAnd1 = true;
3194   }
3195
3196   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3197     std::swap(N0, N1);
3198   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3199     return SDValue();
3200   if (!N0.getNode()->hasOneUse() ||
3201       !N1.getNode()->hasOneUse())
3202     return SDValue();
3203
3204   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3206   if (!N01C || !N11C)
3207     return SDValue();
3208   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3209     return SDValue();
3210
3211   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3212   SDValue N00 = N0->getOperand(0);
3213   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3214     if (!N00.getNode()->hasOneUse())
3215       return SDValue();
3216     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3217     if (!N001C || N001C->getZExtValue() != 0xFF)
3218       return SDValue();
3219     N00 = N00.getOperand(0);
3220     LookPassAnd0 = true;
3221   }
3222
3223   SDValue N10 = N1->getOperand(0);
3224   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3225     if (!N10.getNode()->hasOneUse())
3226       return SDValue();
3227     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3228     if (!N101C || N101C->getZExtValue() != 0xFF00)
3229       return SDValue();
3230     N10 = N10.getOperand(0);
3231     LookPassAnd1 = true;
3232   }
3233
3234   if (N00 != N10)
3235     return SDValue();
3236
3237   // Make sure everything beyond the low halfword gets set to zero since the SRL
3238   // 16 will clear the top bits.
3239   unsigned OpSizeInBits = VT.getSizeInBits();
3240   if (DemandHighBits && OpSizeInBits > 16) {
3241     // If the left-shift isn't masked out then the only way this is a bswap is
3242     // if all bits beyond the low 8 are 0. In that case the entire pattern
3243     // reduces to a left shift anyway: leave it for other parts of the combiner.
3244     if (!LookPassAnd0)
3245       return SDValue();
3246
3247     // However, if the right shift isn't masked out then it might be because
3248     // it's not needed. See if we can spot that too.
3249     if (!LookPassAnd1 &&
3250         !DAG.MaskedValueIsZero(
3251             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3252       return SDValue();
3253   }
3254
3255   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3256   if (OpSizeInBits > 16) {
3257     SDLoc DL(N);
3258     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3259                       DAG.getConstant(OpSizeInBits - 16, DL,
3260                                       getShiftAmountTy(VT)));
3261   }
3262   return Res;
3263 }
3264
3265 /// Return true if the specified node is an element that makes up a 32-bit
3266 /// packed halfword byteswap.
3267 /// ((x & 0x000000ff) << 8) |
3268 /// ((x & 0x0000ff00) >> 8) |
3269 /// ((x & 0x00ff0000) << 8) |
3270 /// ((x & 0xff000000) >> 8)
3271 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3272   if (!N.getNode()->hasOneUse())
3273     return false;
3274
3275   unsigned Opc = N.getOpcode();
3276   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3277     return false;
3278
3279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3280   if (!N1C)
3281     return false;
3282
3283   unsigned Num;
3284   switch (N1C->getZExtValue()) {
3285   default:
3286     return false;
3287   case 0xFF:       Num = 0; break;
3288   case 0xFF00:     Num = 1; break;
3289   case 0xFF0000:   Num = 2; break;
3290   case 0xFF000000: Num = 3; break;
3291   }
3292
3293   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3294   SDValue N0 = N.getOperand(0);
3295   if (Opc == ISD::AND) {
3296     if (Num == 0 || Num == 2) {
3297       // (x >> 8) & 0xff
3298       // (x >> 8) & 0xff0000
3299       if (N0.getOpcode() != ISD::SRL)
3300         return false;
3301       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3302       if (!C || C->getZExtValue() != 8)
3303         return false;
3304     } else {
3305       // (x << 8) & 0xff00
3306       // (x << 8) & 0xff000000
3307       if (N0.getOpcode() != ISD::SHL)
3308         return false;
3309       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3310       if (!C || C->getZExtValue() != 8)
3311         return false;
3312     }
3313   } else if (Opc == ISD::SHL) {
3314     // (x & 0xff) << 8
3315     // (x & 0xff0000) << 8
3316     if (Num != 0 && Num != 2)
3317       return false;
3318     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3319     if (!C || C->getZExtValue() != 8)
3320       return false;
3321   } else { // Opc == ISD::SRL
3322     // (x & 0xff00) >> 8
3323     // (x & 0xff000000) >> 8
3324     if (Num != 1 && Num != 3)
3325       return false;
3326     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3327     if (!C || C->getZExtValue() != 8)
3328       return false;
3329   }
3330
3331   if (Parts[Num])
3332     return false;
3333
3334   Parts[Num] = N0.getOperand(0).getNode();
3335   return true;
3336 }
3337
3338 /// Match a 32-bit packed halfword bswap. That is
3339 /// ((x & 0x000000ff) << 8) |
3340 /// ((x & 0x0000ff00) >> 8) |
3341 /// ((x & 0x00ff0000) << 8) |
3342 /// ((x & 0xff000000) >> 8)
3343 /// => (rotl (bswap x), 16)
3344 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3345   if (!LegalOperations)
3346     return SDValue();
3347
3348   EVT VT = N->getValueType(0);
3349   if (VT != MVT::i32)
3350     return SDValue();
3351   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3352     return SDValue();
3353
3354   // Look for either
3355   // (or (or (and), (and)), (or (and), (and)))
3356   // (or (or (or (and), (and)), (and)), (and))
3357   if (N0.getOpcode() != ISD::OR)
3358     return SDValue();
3359   SDValue N00 = N0.getOperand(0);
3360   SDValue N01 = N0.getOperand(1);
3361   SDNode *Parts[4] = {};
3362
3363   if (N1.getOpcode() == ISD::OR &&
3364       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3365     // (or (or (and), (and)), (or (and), (and)))
3366     SDValue N000 = N00.getOperand(0);
3367     if (!isBSwapHWordElement(N000, Parts))
3368       return SDValue();
3369
3370     SDValue N001 = N00.getOperand(1);
3371     if (!isBSwapHWordElement(N001, Parts))
3372       return SDValue();
3373     SDValue N010 = N01.getOperand(0);
3374     if (!isBSwapHWordElement(N010, Parts))
3375       return SDValue();
3376     SDValue N011 = N01.getOperand(1);
3377     if (!isBSwapHWordElement(N011, Parts))
3378       return SDValue();
3379   } else {
3380     // (or (or (or (and), (and)), (and)), (and))
3381     if (!isBSwapHWordElement(N1, Parts))
3382       return SDValue();
3383     if (!isBSwapHWordElement(N01, Parts))
3384       return SDValue();
3385     if (N00.getOpcode() != ISD::OR)
3386       return SDValue();
3387     SDValue N000 = N00.getOperand(0);
3388     if (!isBSwapHWordElement(N000, Parts))
3389       return SDValue();
3390     SDValue N001 = N00.getOperand(1);
3391     if (!isBSwapHWordElement(N001, Parts))
3392       return SDValue();
3393   }
3394
3395   // Make sure the parts are all coming from the same node.
3396   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3397     return SDValue();
3398
3399   SDLoc DL(N);
3400   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3401                               SDValue(Parts[0], 0));
3402
3403   // Result of the bswap should be rotated by 16. If it's not legal, then
3404   // do  (x << 16) | (x >> 16).
3405   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3406   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3407     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3408   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3409     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3410   return DAG.getNode(ISD::OR, DL, VT,
3411                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3412                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3413 }
3414
3415 /// This contains all DAGCombine rules which reduce two values combined by
3416 /// an Or operation to a single value \see visitANDLike().
3417 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3418   EVT VT = N1.getValueType();
3419   // fold (or x, undef) -> -1
3420   if (!LegalOperations &&
3421       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3422     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3423     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3424                            SDLoc(LocReference), VT);
3425   }
3426   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3427   SDValue LL, LR, RL, RR, CC0, CC1;
3428   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3429     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3430     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3431
3432     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3433         LL.getValueType().isInteger()) {
3434       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3435       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3436       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3437           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3438         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3439                                      LR.getValueType(), LL, RL);
3440         AddToWorklist(ORNode.getNode());
3441         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3442       }
3443       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3444       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3445       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3446           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3447         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3448                                       LR.getValueType(), LL, RL);
3449         AddToWorklist(ANDNode.getNode());
3450         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3451       }
3452     }
3453     // canonicalize equivalent to ll == rl
3454     if (LL == RR && LR == RL) {
3455       Op1 = ISD::getSetCCSwappedOperands(Op1);
3456       std::swap(RL, RR);
3457     }
3458     if (LL == RL && LR == RR) {
3459       bool isInteger = LL.getValueType().isInteger();
3460       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3461       if (Result != ISD::SETCC_INVALID &&
3462           (!LegalOperations ||
3463            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3464             TLI.isOperationLegal(ISD::SETCC,
3465               getSetCCResultType(N0.getValueType())))))
3466         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3467                             LL, LR, Result);
3468     }
3469   }
3470
3471   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3472   if (N0.getOpcode() == ISD::AND &&
3473       N1.getOpcode() == ISD::AND &&
3474       N0.getOperand(1).getOpcode() == ISD::Constant &&
3475       N1.getOperand(1).getOpcode() == ISD::Constant &&
3476       // Don't increase # computations.
3477       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3478     // We can only do this xform if we know that bits from X that are set in C2
3479     // but not in C1 are already zero.  Likewise for Y.
3480     const APInt &LHSMask =
3481       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3482     const APInt &RHSMask =
3483       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3484
3485     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3486         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3487       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3488                               N0.getOperand(0), N1.getOperand(0));
3489       SDLoc DL(LocReference);
3490       return DAG.getNode(ISD::AND, DL, VT, X,
3491                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3492     }
3493   }
3494
3495   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3496   if (N0.getOpcode() == ISD::AND &&
3497       N1.getOpcode() == ISD::AND &&
3498       N0.getOperand(0) == N1.getOperand(0) &&
3499       // Don't increase # computations.
3500       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3501     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3502                             N0.getOperand(1), N1.getOperand(1));
3503     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3504   }
3505
3506   return SDValue();
3507 }
3508
3509 SDValue DAGCombiner::visitOR(SDNode *N) {
3510   SDValue N0 = N->getOperand(0);
3511   SDValue N1 = N->getOperand(1);
3512   EVT VT = N1.getValueType();
3513
3514   // fold vector ops
3515   if (VT.isVector()) {
3516     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3517       return FoldedVOp;
3518
3519     // fold (or x, 0) -> x, vector edition
3520     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3521       return N1;
3522     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3523       return N0;
3524
3525     // fold (or x, -1) -> -1, vector edition
3526     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3527       // do not return N0, because undef node may exist in N0
3528       return DAG.getConstant(
3529           APInt::getAllOnesValue(
3530               N0.getValueType().getScalarType().getSizeInBits()),
3531           SDLoc(N), N0.getValueType());
3532     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3533       // do not return N1, because undef node may exist in N1
3534       return DAG.getConstant(
3535           APInt::getAllOnesValue(
3536               N1.getValueType().getScalarType().getSizeInBits()),
3537           SDLoc(N), N1.getValueType());
3538
3539     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3540     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3541     // Do this only if the resulting shuffle is legal.
3542     if (isa<ShuffleVectorSDNode>(N0) &&
3543         isa<ShuffleVectorSDNode>(N1) &&
3544         // Avoid folding a node with illegal type.
3545         TLI.isTypeLegal(VT) &&
3546         N0->getOperand(1) == N1->getOperand(1) &&
3547         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3548       bool CanFold = true;
3549       unsigned NumElts = VT.getVectorNumElements();
3550       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3551       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3552       // We construct two shuffle masks:
3553       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3554       // and N1 as the second operand.
3555       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3556       // and N0 as the second operand.
3557       // We do this because OR is commutable and therefore there might be
3558       // two ways to fold this node into a shuffle.
3559       SmallVector<int,4> Mask1;
3560       SmallVector<int,4> Mask2;
3561
3562       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3563         int M0 = SV0->getMaskElt(i);
3564         int M1 = SV1->getMaskElt(i);
3565
3566         // Both shuffle indexes are undef. Propagate Undef.
3567         if (M0 < 0 && M1 < 0) {
3568           Mask1.push_back(M0);
3569           Mask2.push_back(M0);
3570           continue;
3571         }
3572
3573         if (M0 < 0 || M1 < 0 ||
3574             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3575             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3576           CanFold = false;
3577           break;
3578         }
3579
3580         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3581         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3582       }
3583
3584       if (CanFold) {
3585         // Fold this sequence only if the resulting shuffle is 'legal'.
3586         if (TLI.isShuffleMaskLegal(Mask1, VT))
3587           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3588                                       N1->getOperand(0), &Mask1[0]);
3589         if (TLI.isShuffleMaskLegal(Mask2, VT))
3590           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3591                                       N0->getOperand(0), &Mask2[0]);
3592       }
3593     }
3594   }
3595
3596   // fold (or c1, c2) -> c1|c2
3597   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3598   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3599   if (N0C && N1C)
3600     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3601   // canonicalize constant to RHS
3602   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3603      !isConstantIntBuildVectorOrConstantInt(N1))
3604     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3605   // fold (or x, 0) -> x
3606   if (N1C && N1C->isNullValue())
3607     return N0;
3608   // fold (or x, -1) -> -1
3609   if (N1C && N1C->isAllOnesValue())
3610     return N1;
3611   // fold (or x, c) -> c iff (x & ~c) == 0
3612   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3613     return N1;
3614
3615   if (SDValue Combined = visitORLike(N0, N1, N))
3616     return Combined;
3617
3618   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3619   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3620   if (BSwap.getNode())
3621     return BSwap;
3622   BSwap = MatchBSwapHWordLow(N, N0, N1);
3623   if (BSwap.getNode())
3624     return BSwap;
3625
3626   // reassociate or
3627   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3628     return ROR;
3629   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3630   // iff (c1 & c2) == 0.
3631   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3632              isa<ConstantSDNode>(N0.getOperand(1))) {
3633     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3634     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3635       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3636                                                    N1C, C1))
3637         return DAG.getNode(
3638             ISD::AND, SDLoc(N), VT,
3639             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3640       return SDValue();
3641     }
3642   }
3643   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3644   if (N0.getOpcode() == N1.getOpcode()) {
3645     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3646     if (Tmp.getNode()) return Tmp;
3647   }
3648
3649   // See if this is some rotate idiom.
3650   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3651     return SDValue(Rot, 0);
3652
3653   // Simplify the operands using demanded-bits information.
3654   if (!VT.isVector() &&
3655       SimplifyDemandedBits(SDValue(N, 0)))
3656     return SDValue(N, 0);
3657
3658   return SDValue();
3659 }
3660
3661 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3662 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3663   if (Op.getOpcode() == ISD::AND) {
3664     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3665       Mask = Op.getOperand(1);
3666       Op = Op.getOperand(0);
3667     } else {
3668       return false;
3669     }
3670   }
3671
3672   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3673     Shift = Op;
3674     return true;
3675   }
3676
3677   return false;
3678 }
3679
3680 // Return true if we can prove that, whenever Neg and Pos are both in the
3681 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3682 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3683 //
3684 //     (or (shift1 X, Neg), (shift2 X, Pos))
3685 //
3686 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3687 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3688 // to consider shift amounts with defined behavior.
3689 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3690   // If OpSize is a power of 2 then:
3691   //
3692   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3693   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3694   //
3695   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3696   // for the stronger condition:
3697   //
3698   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3699   //
3700   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3701   // we can just replace Neg with Neg' for the rest of the function.
3702   //
3703   // In other cases we check for the even stronger condition:
3704   //
3705   //     Neg == OpSize - Pos                                    [B]
3706   //
3707   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3708   // behavior if Pos == 0 (and consequently Neg == OpSize).
3709   //
3710   // We could actually use [A] whenever OpSize is a power of 2, but the
3711   // only extra cases that it would match are those uninteresting ones
3712   // where Neg and Pos are never in range at the same time.  E.g. for
3713   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3714   // as well as (sub 32, Pos), but:
3715   //
3716   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3717   //
3718   // always invokes undefined behavior for 32-bit X.
3719   //
3720   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3721   unsigned MaskLoBits = 0;
3722   if (Neg.getOpcode() == ISD::AND &&
3723       isPowerOf2_64(OpSize) &&
3724       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3725       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3726     Neg = Neg.getOperand(0);
3727     MaskLoBits = Log2_64(OpSize);
3728   }
3729
3730   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3731   if (Neg.getOpcode() != ISD::SUB)
3732     return 0;
3733   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3734   if (!NegC)
3735     return 0;
3736   SDValue NegOp1 = Neg.getOperand(1);
3737
3738   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3739   // Pos'.  The truncation is redundant for the purpose of the equality.
3740   if (MaskLoBits &&
3741       Pos.getOpcode() == ISD::AND &&
3742       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3743       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3744     Pos = Pos.getOperand(0);
3745
3746   // The condition we need is now:
3747   //
3748   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3749   //
3750   // If NegOp1 == Pos then we need:
3751   //
3752   //              OpSize & Mask == NegC & Mask
3753   //
3754   // (because "x & Mask" is a truncation and distributes through subtraction).
3755   APInt Width;
3756   if (Pos == NegOp1)
3757     Width = NegC->getAPIntValue();
3758   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3759   // Then the condition we want to prove becomes:
3760   //
3761   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3762   //
3763   // which, again because "x & Mask" is a truncation, becomes:
3764   //
3765   //                NegC & Mask == (OpSize - PosC) & Mask
3766   //              OpSize & Mask == (NegC + PosC) & Mask
3767   else if (Pos.getOpcode() == ISD::ADD &&
3768            Pos.getOperand(0) == NegOp1 &&
3769            Pos.getOperand(1).getOpcode() == ISD::Constant)
3770     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3771              NegC->getAPIntValue());
3772   else
3773     return false;
3774
3775   // Now we just need to check that OpSize & Mask == Width & Mask.
3776   if (MaskLoBits)
3777     // Opsize & Mask is 0 since Mask is Opsize - 1.
3778     return Width.getLoBits(MaskLoBits) == 0;
3779   return Width == OpSize;
3780 }
3781
3782 // A subroutine of MatchRotate used once we have found an OR of two opposite
3783 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3784 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3785 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3786 // Neg with outer conversions stripped away.
3787 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3788                                        SDValue Neg, SDValue InnerPos,
3789                                        SDValue InnerNeg, unsigned PosOpcode,
3790                                        unsigned NegOpcode, SDLoc DL) {
3791   // fold (or (shl x, (*ext y)),
3792   //          (srl x, (*ext (sub 32, y)))) ->
3793   //   (rotl x, y) or (rotr x, (sub 32, y))
3794   //
3795   // fold (or (shl x, (*ext (sub 32, y))),
3796   //          (srl x, (*ext y))) ->
3797   //   (rotr x, y) or (rotl x, (sub 32, y))
3798   EVT VT = Shifted.getValueType();
3799   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3800     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3801     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3802                        HasPos ? Pos : Neg).getNode();
3803   }
3804
3805   return nullptr;
3806 }
3807
3808 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3809 // idioms for rotate, and if the target supports rotation instructions, generate
3810 // a rot[lr].
3811 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3812   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3813   EVT VT = LHS.getValueType();
3814   if (!TLI.isTypeLegal(VT)) return nullptr;
3815
3816   // The target must have at least one rotate flavor.
3817   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3818   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3819   if (!HasROTL && !HasROTR) return nullptr;
3820
3821   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3822   SDValue LHSShift;   // The shift.
3823   SDValue LHSMask;    // AND value if any.
3824   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3825     return nullptr; // Not part of a rotate.
3826
3827   SDValue RHSShift;   // The shift.
3828   SDValue RHSMask;    // AND value if any.
3829   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3830     return nullptr; // Not part of a rotate.
3831
3832   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3833     return nullptr;   // Not shifting the same value.
3834
3835   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3836     return nullptr;   // Shifts must disagree.
3837
3838   // Canonicalize shl to left side in a shl/srl pair.
3839   if (RHSShift.getOpcode() == ISD::SHL) {
3840     std::swap(LHS, RHS);
3841     std::swap(LHSShift, RHSShift);
3842     std::swap(LHSMask , RHSMask );
3843   }
3844
3845   unsigned OpSizeInBits = VT.getSizeInBits();
3846   SDValue LHSShiftArg = LHSShift.getOperand(0);
3847   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3848   SDValue RHSShiftArg = RHSShift.getOperand(0);
3849   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3850
3851   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3852   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3853   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3854       RHSShiftAmt.getOpcode() == ISD::Constant) {
3855     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3856     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3857     if ((LShVal + RShVal) != OpSizeInBits)
3858       return nullptr;
3859
3860     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3861                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3862
3863     // If there is an AND of either shifted operand, apply it to the result.
3864     if (LHSMask.getNode() || RHSMask.getNode()) {
3865       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3866
3867       if (LHSMask.getNode()) {
3868         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3869         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3870       }
3871       if (RHSMask.getNode()) {
3872         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3873         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3874       }
3875
3876       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3877     }
3878
3879     return Rot.getNode();
3880   }
3881
3882   // If there is a mask here, and we have a variable shift, we can't be sure
3883   // that we're masking out the right stuff.
3884   if (LHSMask.getNode() || RHSMask.getNode())
3885     return nullptr;
3886
3887   // If the shift amount is sign/zext/any-extended just peel it off.
3888   SDValue LExtOp0 = LHSShiftAmt;
3889   SDValue RExtOp0 = RHSShiftAmt;
3890   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3894       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3895        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3896        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3897        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3898     LExtOp0 = LHSShiftAmt.getOperand(0);
3899     RExtOp0 = RHSShiftAmt.getOperand(0);
3900   }
3901
3902   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3903                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3904   if (TryL)
3905     return TryL;
3906
3907   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3908                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3909   if (TryR)
3910     return TryR;
3911
3912   return nullptr;
3913 }
3914
3915 SDValue DAGCombiner::visitXOR(SDNode *N) {
3916   SDValue N0 = N->getOperand(0);
3917   SDValue N1 = N->getOperand(1);
3918   EVT VT = N0.getValueType();
3919
3920   // fold vector ops
3921   if (VT.isVector()) {
3922     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3923       return FoldedVOp;
3924
3925     // fold (xor x, 0) -> x, vector edition
3926     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3927       return N1;
3928     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3929       return N0;
3930   }
3931
3932   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3933   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3934     return DAG.getConstant(0, SDLoc(N), VT);
3935   // fold (xor x, undef) -> undef
3936   if (N0.getOpcode() == ISD::UNDEF)
3937     return N0;
3938   if (N1.getOpcode() == ISD::UNDEF)
3939     return N1;
3940   // fold (xor c1, c2) -> c1^c2
3941   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3942   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3943   if (N0C && N1C)
3944     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3945   // canonicalize constant to RHS
3946   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3947      !isConstantIntBuildVectorOrConstantInt(N1))
3948     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3949   // fold (xor x, 0) -> x
3950   if (N1C && N1C->isNullValue())
3951     return N0;
3952   // reassociate xor
3953   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3954     return RXOR;
3955
3956   // fold !(x cc y) -> (x !cc y)
3957   SDValue LHS, RHS, CC;
3958   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3959     bool isInt = LHS.getValueType().isInteger();
3960     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3961                                                isInt);
3962
3963     if (!LegalOperations ||
3964         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3965       switch (N0.getOpcode()) {
3966       default:
3967         llvm_unreachable("Unhandled SetCC Equivalent!");
3968       case ISD::SETCC:
3969         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3970       case ISD::SELECT_CC:
3971         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3972                                N0.getOperand(3), NotCC);
3973       }
3974     }
3975   }
3976
3977   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3978   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3979       N0.getNode()->hasOneUse() &&
3980       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3981     SDValue V = N0.getOperand(0);
3982     SDLoc DL(N0);
3983     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3984                     DAG.getConstant(1, DL, V.getValueType()));
3985     AddToWorklist(V.getNode());
3986     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3987   }
3988
3989   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3990   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3991       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3992     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3993     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3994       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3995       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3996       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3997       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3998       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3999     }
4000   }
4001   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4002   if (N1C && N1C->isAllOnesValue() &&
4003       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4004     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4005     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4006       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4007       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4008       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4009       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4010       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4011     }
4012   }
4013   // fold (xor (and x, y), y) -> (and (not x), y)
4014   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4015       N0->getOperand(1) == N1) {
4016     SDValue X = N0->getOperand(0);
4017     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4018     AddToWorklist(NotX.getNode());
4019     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4020   }
4021   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4022   if (N1C && N0.getOpcode() == ISD::XOR) {
4023     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4024     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4025     if (N00C) {
4026       SDLoc DL(N);
4027       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4028                          DAG.getConstant(N1C->getAPIntValue() ^
4029                                          N00C->getAPIntValue(), DL, VT));
4030     }
4031     if (N01C) {
4032       SDLoc DL(N);
4033       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4034                          DAG.getConstant(N1C->getAPIntValue() ^
4035                                          N01C->getAPIntValue(), DL, VT));
4036     }
4037   }
4038   // fold (xor x, x) -> 0
4039   if (N0 == N1)
4040     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4041
4042   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4043   // Here is a concrete example of this equivalence:
4044   // i16   x ==  14
4045   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4046   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4047   //
4048   // =>
4049   //
4050   // i16     ~1      == 0b1111111111111110
4051   // i16 rol(~1, 14) == 0b1011111111111111
4052   //
4053   // Some additional tips to help conceptualize this transform:
4054   // - Try to see the operation as placing a single zero in a value of all ones.
4055   // - There exists no value for x which would allow the result to contain zero.
4056   // - Values of x larger than the bitwidth are undefined and do not require a
4057   //   consistent result.
4058   // - Pushing the zero left requires shifting one bits in from the right.
4059   // A rotate left of ~1 is a nice way of achieving the desired result.
4060   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4061     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4062       if (N0.getOpcode() == ISD::SHL)
4063         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4064           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4065             SDLoc DL(N);
4066             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4067                                N0.getOperand(1));
4068           }
4069
4070   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4071   if (N0.getOpcode() == N1.getOpcode()) {
4072     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4073     if (Tmp.getNode()) return Tmp;
4074   }
4075
4076   // Simplify the expression using non-local knowledge.
4077   if (!VT.isVector() &&
4078       SimplifyDemandedBits(SDValue(N, 0)))
4079     return SDValue(N, 0);
4080
4081   return SDValue();
4082 }
4083
4084 /// Handle transforms common to the three shifts, when the shift amount is a
4085 /// constant.
4086 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4087   // We can't and shouldn't fold opaque constants.
4088   if (Amt->isOpaque())
4089     return SDValue();
4090
4091   SDNode *LHS = N->getOperand(0).getNode();
4092   if (!LHS->hasOneUse()) return SDValue();
4093
4094   // We want to pull some binops through shifts, so that we have (and (shift))
4095   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4096   // thing happens with address calculations, so it's important to canonicalize
4097   // it.
4098   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4099
4100   switch (LHS->getOpcode()) {
4101   default: return SDValue();
4102   case ISD::OR:
4103   case ISD::XOR:
4104     HighBitSet = false; // We can only transform sra if the high bit is clear.
4105     break;
4106   case ISD::AND:
4107     HighBitSet = true;  // We can only transform sra if the high bit is set.
4108     break;
4109   case ISD::ADD:
4110     if (N->getOpcode() != ISD::SHL)
4111       return SDValue(); // only shl(add) not sr[al](add).
4112     HighBitSet = false; // We can only transform sra if the high bit is clear.
4113     break;
4114   }
4115
4116   // We require the RHS of the binop to be a constant and not opaque as well.
4117   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4118   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4119
4120   // FIXME: disable this unless the input to the binop is a shift by a constant.
4121   // If it is not a shift, it pessimizes some common cases like:
4122   //
4123   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4124   //    int bar(int *X, int i) { return X[i & 255]; }
4125   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4126   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4127        BinOpLHSVal->getOpcode() != ISD::SRA &&
4128        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4129       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4130     return SDValue();
4131
4132   EVT VT = N->getValueType(0);
4133
4134   // If this is a signed shift right, and the high bit is modified by the
4135   // logical operation, do not perform the transformation. The highBitSet
4136   // boolean indicates the value of the high bit of the constant which would
4137   // cause it to be modified for this operation.
4138   if (N->getOpcode() == ISD::SRA) {
4139     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4140     if (BinOpRHSSignSet != HighBitSet)
4141       return SDValue();
4142   }
4143
4144   if (!TLI.isDesirableToCommuteWithShift(LHS))
4145     return SDValue();
4146
4147   // Fold the constants, shifting the binop RHS by the shift amount.
4148   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4149                                N->getValueType(0),
4150                                LHS->getOperand(1), N->getOperand(1));
4151   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4152
4153   // Create the new shift.
4154   SDValue NewShift = DAG.getNode(N->getOpcode(),
4155                                  SDLoc(LHS->getOperand(0)),
4156                                  VT, LHS->getOperand(0), N->getOperand(1));
4157
4158   // Create the new binop.
4159   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4160 }
4161
4162 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4163   assert(N->getOpcode() == ISD::TRUNCATE);
4164   assert(N->getOperand(0).getOpcode() == ISD::AND);
4165
4166   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4167   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4168     SDValue N01 = N->getOperand(0).getOperand(1);
4169
4170     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4171       EVT TruncVT = N->getValueType(0);
4172       SDValue N00 = N->getOperand(0).getOperand(0);
4173       APInt TruncC = N01C->getAPIntValue();
4174       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4175       SDLoc DL(N);
4176
4177       return DAG.getNode(ISD::AND, DL, TruncVT,
4178                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4179                          DAG.getConstant(TruncC, DL, TruncVT));
4180     }
4181   }
4182
4183   return SDValue();
4184 }
4185
4186 SDValue DAGCombiner::visitRotate(SDNode *N) {
4187   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4188   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4189       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4190     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4191     if (NewOp1.getNode())
4192       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4193                          N->getOperand(0), NewOp1);
4194   }
4195   return SDValue();
4196 }
4197
4198 SDValue DAGCombiner::visitSHL(SDNode *N) {
4199   SDValue N0 = N->getOperand(0);
4200   SDValue N1 = N->getOperand(1);
4201   EVT VT = N0.getValueType();
4202   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4203
4204   // fold vector ops
4205   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4206   if (VT.isVector()) {
4207     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4208       return FoldedVOp;
4209
4210     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4211     // If setcc produces all-one true value then:
4212     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4213     if (N1CV && N1CV->isConstant()) {
4214       if (N0.getOpcode() == ISD::AND) {
4215         SDValue N00 = N0->getOperand(0);
4216         SDValue N01 = N0->getOperand(1);
4217         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4218
4219         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4220             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4221                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4222           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4223                                                      N01CV, N1CV))
4224             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4225         }
4226       } else {
4227         N1C = isConstOrConstSplat(N1);
4228       }
4229     }
4230   }
4231
4232   // fold (shl c1, c2) -> c1<<c2
4233   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4234   if (N0C && N1C)
4235     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4236   // fold (shl 0, x) -> 0
4237   if (N0C && N0C->isNullValue())
4238     return N0;
4239   // fold (shl x, c >= size(x)) -> undef
4240   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4241     return DAG.getUNDEF(VT);
4242   // fold (shl x, 0) -> x
4243   if (N1C && N1C->isNullValue())
4244     return N0;
4245   // fold (shl undef, x) -> 0
4246   if (N0.getOpcode() == ISD::UNDEF)
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // if (shl x, c) is known to be zero, return 0
4249   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4250                             APInt::getAllOnesValue(OpSizeInBits)))
4251     return DAG.getConstant(0, SDLoc(N), VT);
4252   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4253   if (N1.getOpcode() == ISD::TRUNCATE &&
4254       N1.getOperand(0).getOpcode() == ISD::AND) {
4255     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4256     if (NewOp1.getNode())
4257       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4258   }
4259
4260   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4261     return SDValue(N, 0);
4262
4263   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4264   if (N1C && N0.getOpcode() == ISD::SHL) {
4265     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4266       uint64_t c1 = N0C1->getZExtValue();
4267       uint64_t c2 = N1C->getZExtValue();
4268       SDLoc DL(N);
4269       if (c1 + c2 >= OpSizeInBits)
4270         return DAG.getConstant(0, DL, VT);
4271       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4272                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4273     }
4274   }
4275
4276   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4277   // For this to be valid, the second form must not preserve any of the bits
4278   // that are shifted out by the inner shift in the first form.  This means
4279   // the outer shift size must be >= the number of bits added by the ext.
4280   // As a corollary, we don't care what kind of ext it is.
4281   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4282               N0.getOpcode() == ISD::ANY_EXTEND ||
4283               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4284       N0.getOperand(0).getOpcode() == ISD::SHL) {
4285     SDValue N0Op0 = N0.getOperand(0);
4286     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4287       uint64_t c1 = N0Op0C1->getZExtValue();
4288       uint64_t c2 = N1C->getZExtValue();
4289       EVT InnerShiftVT = N0Op0.getValueType();
4290       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4291       if (c2 >= OpSizeInBits - InnerShiftSize) {
4292         SDLoc DL(N0);
4293         if (c1 + c2 >= OpSizeInBits)
4294           return DAG.getConstant(0, DL, VT);
4295         return DAG.getNode(ISD::SHL, DL, VT,
4296                            DAG.getNode(N0.getOpcode(), DL, VT,
4297                                        N0Op0->getOperand(0)),
4298                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4299       }
4300     }
4301   }
4302
4303   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4304   // Only fold this if the inner zext has no other uses to avoid increasing
4305   // the total number of instructions.
4306   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4307       N0.getOperand(0).getOpcode() == ISD::SRL) {
4308     SDValue N0Op0 = N0.getOperand(0);
4309     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4310       uint64_t c1 = N0Op0C1->getZExtValue();
4311       if (c1 < VT.getScalarSizeInBits()) {
4312         uint64_t c2 = N1C->getZExtValue();
4313         if (c1 == c2) {
4314           SDValue NewOp0 = N0.getOperand(0);
4315           EVT CountVT = NewOp0.getOperand(1).getValueType();
4316           SDLoc DL(N);
4317           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4318                                        NewOp0,
4319                                        DAG.getConstant(c2, DL, CountVT));
4320           AddToWorklist(NewSHL.getNode());
4321           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4322         }
4323       }
4324     }
4325   }
4326
4327   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4328   //                               (and (srl x, (sub c1, c2), MASK)
4329   // Only fold this if the inner shift has no other uses -- if it does, folding
4330   // this will increase the total number of instructions.
4331   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4332     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4333       uint64_t c1 = N0C1->getZExtValue();
4334       if (c1 < OpSizeInBits) {
4335         uint64_t c2 = N1C->getZExtValue();
4336         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4337         SDValue Shift;
4338         if (c2 > c1) {
4339           Mask = Mask.shl(c2 - c1);
4340           SDLoc DL(N);
4341           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4342                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4343         } else {
4344           Mask = Mask.lshr(c1 - c2);
4345           SDLoc DL(N);
4346           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4347                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4348         }
4349         SDLoc DL(N0);
4350         return DAG.getNode(ISD::AND, DL, VT, Shift,
4351                            DAG.getConstant(Mask, DL, VT));
4352       }
4353     }
4354   }
4355   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4356   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4357     unsigned BitSize = VT.getScalarSizeInBits();
4358     SDLoc DL(N);
4359     SDValue HiBitsMask =
4360       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4361                                             BitSize - N1C->getZExtValue()),
4362                       DL, VT);
4363     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4364                        HiBitsMask);
4365   }
4366
4367   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4368   // Variant of version done on multiply, except mul by a power of 2 is turned
4369   // into a shift.
4370   APInt Val;
4371   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4372       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4373        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4374     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4375     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4376     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4377   }
4378
4379   if (N1C) {
4380     SDValue NewSHL = visitShiftByConstant(N, N1C);
4381     if (NewSHL.getNode())
4382       return NewSHL;
4383   }
4384
4385   return SDValue();
4386 }
4387
4388 SDValue DAGCombiner::visitSRA(SDNode *N) {
4389   SDValue N0 = N->getOperand(0);
4390   SDValue N1 = N->getOperand(1);
4391   EVT VT = N0.getValueType();
4392   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4393
4394   // fold vector ops
4395   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4396   if (VT.isVector()) {
4397     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4398       return FoldedVOp;
4399
4400     N1C = isConstOrConstSplat(N1);
4401   }
4402
4403   // fold (sra c1, c2) -> (sra c1, c2)
4404   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4405   if (N0C && N1C)
4406     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4407   // fold (sra 0, x) -> 0
4408   if (N0C && N0C->isNullValue())
4409     return N0;
4410   // fold (sra -1, x) -> -1
4411   if (N0C && N0C->isAllOnesValue())
4412     return N0;
4413   // fold (sra x, (setge c, size(x))) -> undef
4414   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4415     return DAG.getUNDEF(VT);
4416   // fold (sra x, 0) -> x
4417   if (N1C && N1C->isNullValue())
4418     return N0;
4419   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4420   // sext_inreg.
4421   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4422     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4423     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4424     if (VT.isVector())
4425       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4426                                ExtVT, VT.getVectorNumElements());
4427     if ((!LegalOperations ||
4428          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4429       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4430                          N0.getOperand(0), DAG.getValueType(ExtVT));
4431   }
4432
4433   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4434   if (N1C && N0.getOpcode() == ISD::SRA) {
4435     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4436       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4437       if (Sum >= OpSizeInBits)
4438         Sum = OpSizeInBits - 1;
4439       SDLoc DL(N);
4440       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4441                          DAG.getConstant(Sum, DL, N1.getValueType()));
4442     }
4443   }
4444
4445   // fold (sra (shl X, m), (sub result_size, n))
4446   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4447   // result_size - n != m.
4448   // If truncate is free for the target sext(shl) is likely to result in better
4449   // code.
4450   if (N0.getOpcode() == ISD::SHL && N1C) {
4451     // Get the two constanst of the shifts, CN0 = m, CN = n.
4452     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4453     if (N01C) {
4454       LLVMContext &Ctx = *DAG.getContext();
4455       // Determine what the truncate's result bitsize and type would be.
4456       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4457
4458       if (VT.isVector())
4459         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4460
4461       // Determine the residual right-shift amount.
4462       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4463
4464       // If the shift is not a no-op (in which case this should be just a sign
4465       // extend already), the truncated to type is legal, sign_extend is legal
4466       // on that type, and the truncate to that type is both legal and free,
4467       // perform the transform.
4468       if ((ShiftAmt > 0) &&
4469           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4470           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4471           TLI.isTruncateFree(VT, TruncVT)) {
4472
4473         SDLoc DL(N);
4474         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4475             getShiftAmountTy(N0.getOperand(0).getValueType()));
4476         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4477                                     N0.getOperand(0), Amt);
4478         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4479                                     Shift);
4480         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4481                            N->getValueType(0), Trunc);
4482       }
4483     }
4484   }
4485
4486   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4487   if (N1.getOpcode() == ISD::TRUNCATE &&
4488       N1.getOperand(0).getOpcode() == ISD::AND) {
4489     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4490     if (NewOp1.getNode())
4491       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4492   }
4493
4494   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4495   //      if c1 is equal to the number of bits the trunc removes
4496   if (N0.getOpcode() == ISD::TRUNCATE &&
4497       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4498        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4499       N0.getOperand(0).hasOneUse() &&
4500       N0.getOperand(0).getOperand(1).hasOneUse() &&
4501       N1C) {
4502     SDValue N0Op0 = N0.getOperand(0);
4503     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4504       unsigned LargeShiftVal = LargeShift->getZExtValue();
4505       EVT LargeVT = N0Op0.getValueType();
4506
4507       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4508         SDLoc DL(N);
4509         SDValue Amt =
4510           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4511                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4512         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4513                                   N0Op0.getOperand(0), Amt);
4514         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4515       }
4516     }
4517   }
4518
4519   // Simplify, based on bits shifted out of the LHS.
4520   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4521     return SDValue(N, 0);
4522
4523
4524   // If the sign bit is known to be zero, switch this to a SRL.
4525   if (DAG.SignBitIsZero(N0))
4526     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4527
4528   if (N1C) {
4529     SDValue NewSRA = visitShiftByConstant(N, N1C);
4530     if (NewSRA.getNode())
4531       return NewSRA;
4532   }
4533
4534   return SDValue();
4535 }
4536
4537 SDValue DAGCombiner::visitSRL(SDNode *N) {
4538   SDValue N0 = N->getOperand(0);
4539   SDValue N1 = N->getOperand(1);
4540   EVT VT = N0.getValueType();
4541   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4542
4543   // fold vector ops
4544   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4545   if (VT.isVector()) {
4546     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4547       return FoldedVOp;
4548
4549     N1C = isConstOrConstSplat(N1);
4550   }
4551
4552   // fold (srl c1, c2) -> c1 >>u c2
4553   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4554   if (N0C && N1C)
4555     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4556   // fold (srl 0, x) -> 0
4557   if (N0C && N0C->isNullValue())
4558     return N0;
4559   // fold (srl x, c >= size(x)) -> undef
4560   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4561     return DAG.getUNDEF(VT);
4562   // fold (srl x, 0) -> x
4563   if (N1C && N1C->isNullValue())
4564     return N0;
4565   // if (srl x, c) is known to be zero, return 0
4566   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4567                                    APInt::getAllOnesValue(OpSizeInBits)))
4568     return DAG.getConstant(0, SDLoc(N), VT);
4569
4570   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4571   if (N1C && N0.getOpcode() == ISD::SRL) {
4572     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4573       uint64_t c1 = N01C->getZExtValue();
4574       uint64_t c2 = N1C->getZExtValue();
4575       SDLoc DL(N);
4576       if (c1 + c2 >= OpSizeInBits)
4577         return DAG.getConstant(0, DL, VT);
4578       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4579                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4580     }
4581   }
4582
4583   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4584   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4585       N0.getOperand(0).getOpcode() == ISD::SRL &&
4586       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4587     uint64_t c1 =
4588       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4589     uint64_t c2 = N1C->getZExtValue();
4590     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4591     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4592     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4593     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4594     if (c1 + OpSizeInBits == InnerShiftSize) {
4595       SDLoc DL(N0);
4596       if (c1 + c2 >= InnerShiftSize)
4597         return DAG.getConstant(0, DL, VT);
4598       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4599                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4600                                      N0.getOperand(0)->getOperand(0),
4601                                      DAG.getConstant(c1 + c2, DL,
4602                                                      ShiftCountVT)));
4603     }
4604   }
4605
4606   // fold (srl (shl x, c), c) -> (and x, cst2)
4607   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4608     unsigned BitSize = N0.getScalarValueSizeInBits();
4609     if (BitSize <= 64) {
4610       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4611       SDLoc DL(N);
4612       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4613                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4614     }
4615   }
4616
4617   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4618   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4619     // Shifting in all undef bits?
4620     EVT SmallVT = N0.getOperand(0).getValueType();
4621     unsigned BitSize = SmallVT.getScalarSizeInBits();
4622     if (N1C->getZExtValue() >= BitSize)
4623       return DAG.getUNDEF(VT);
4624
4625     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4626       uint64_t ShiftAmt = N1C->getZExtValue();
4627       SDLoc DL0(N0);
4628       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4629                                        N0.getOperand(0),
4630                           DAG.getConstant(ShiftAmt, DL0,
4631                                           getShiftAmountTy(SmallVT)));
4632       AddToWorklist(SmallShift.getNode());
4633       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4634       SDLoc DL(N);
4635       return DAG.getNode(ISD::AND, DL, VT,
4636                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4637                          DAG.getConstant(Mask, DL, VT));
4638     }
4639   }
4640
4641   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4642   // bit, which is unmodified by sra.
4643   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4644     if (N0.getOpcode() == ISD::SRA)
4645       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4646   }
4647
4648   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4649   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4650       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4651     APInt KnownZero, KnownOne;
4652     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4653
4654     // If any of the input bits are KnownOne, then the input couldn't be all
4655     // zeros, thus the result of the srl will always be zero.
4656     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4657
4658     // If all of the bits input the to ctlz node are known to be zero, then
4659     // the result of the ctlz is "32" and the result of the shift is one.
4660     APInt UnknownBits = ~KnownZero;
4661     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4662
4663     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4664     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4665       // Okay, we know that only that the single bit specified by UnknownBits
4666       // could be set on input to the CTLZ node. If this bit is set, the SRL
4667       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4668       // to an SRL/XOR pair, which is likely to simplify more.
4669       unsigned ShAmt = UnknownBits.countTrailingZeros();
4670       SDValue Op = N0.getOperand(0);
4671
4672       if (ShAmt) {
4673         SDLoc DL(N0);
4674         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4675                   DAG.getConstant(ShAmt, DL,
4676                                   getShiftAmountTy(Op.getValueType())));
4677         AddToWorklist(Op.getNode());
4678       }
4679
4680       SDLoc DL(N);
4681       return DAG.getNode(ISD::XOR, DL, VT,
4682                          Op, DAG.getConstant(1, DL, VT));
4683     }
4684   }
4685
4686   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4687   if (N1.getOpcode() == ISD::TRUNCATE &&
4688       N1.getOperand(0).getOpcode() == ISD::AND) {
4689     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4690     if (NewOp1.getNode())
4691       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4692   }
4693
4694   // fold operands of srl based on knowledge that the low bits are not
4695   // demanded.
4696   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4697     return SDValue(N, 0);
4698
4699   if (N1C) {
4700     SDValue NewSRL = visitShiftByConstant(N, N1C);
4701     if (NewSRL.getNode())
4702       return NewSRL;
4703   }
4704
4705   // Attempt to convert a srl of a load into a narrower zero-extending load.
4706   SDValue NarrowLoad = ReduceLoadWidth(N);
4707   if (NarrowLoad.getNode())
4708     return NarrowLoad;
4709
4710   // Here is a common situation. We want to optimize:
4711   //
4712   //   %a = ...
4713   //   %b = and i32 %a, 2
4714   //   %c = srl i32 %b, 1
4715   //   brcond i32 %c ...
4716   //
4717   // into
4718   //
4719   //   %a = ...
4720   //   %b = and %a, 2
4721   //   %c = setcc eq %b, 0
4722   //   brcond %c ...
4723   //
4724   // However when after the source operand of SRL is optimized into AND, the SRL
4725   // itself may not be optimized further. Look for it and add the BRCOND into
4726   // the worklist.
4727   if (N->hasOneUse()) {
4728     SDNode *Use = *N->use_begin();
4729     if (Use->getOpcode() == ISD::BRCOND)
4730       AddToWorklist(Use);
4731     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4732       // Also look pass the truncate.
4733       Use = *Use->use_begin();
4734       if (Use->getOpcode() == ISD::BRCOND)
4735         AddToWorklist(Use);
4736     }
4737   }
4738
4739   return SDValue();
4740 }
4741
4742 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4743   SDValue N0 = N->getOperand(0);
4744   EVT VT = N->getValueType(0);
4745
4746   // fold (ctlz c1) -> c2
4747   if (isa<ConstantSDNode>(N0))
4748     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4749   return SDValue();
4750 }
4751
4752 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4753   SDValue N0 = N->getOperand(0);
4754   EVT VT = N->getValueType(0);
4755
4756   // fold (ctlz_zero_undef c1) -> c2
4757   if (isa<ConstantSDNode>(N0))
4758     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4759   return SDValue();
4760 }
4761
4762 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4763   SDValue N0 = N->getOperand(0);
4764   EVT VT = N->getValueType(0);
4765
4766   // fold (cttz c1) -> c2
4767   if (isa<ConstantSDNode>(N0))
4768     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4769   return SDValue();
4770 }
4771
4772 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4773   SDValue N0 = N->getOperand(0);
4774   EVT VT = N->getValueType(0);
4775
4776   // fold (cttz_zero_undef c1) -> c2
4777   if (isa<ConstantSDNode>(N0))
4778     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4779   return SDValue();
4780 }
4781
4782 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4783   SDValue N0 = N->getOperand(0);
4784   EVT VT = N->getValueType(0);
4785
4786   // fold (ctpop c1) -> c2
4787   if (isa<ConstantSDNode>(N0))
4788     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4789   return SDValue();
4790 }
4791
4792
4793 /// \brief Generate Min/Max node
4794 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4795                                    SDValue True, SDValue False,
4796                                    ISD::CondCode CC, const TargetLowering &TLI,
4797                                    SelectionDAG &DAG) {
4798   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4799     return SDValue();
4800
4801   switch (CC) {
4802   case ISD::SETOLT:
4803   case ISD::SETOLE:
4804   case ISD::SETLT:
4805   case ISD::SETLE:
4806   case ISD::SETULT:
4807   case ISD::SETULE: {
4808     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4809     if (TLI.isOperationLegal(Opcode, VT))
4810       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4811     return SDValue();
4812   }
4813   case ISD::SETOGT:
4814   case ISD::SETOGE:
4815   case ISD::SETGT:
4816   case ISD::SETGE:
4817   case ISD::SETUGT:
4818   case ISD::SETUGE: {
4819     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4820     if (TLI.isOperationLegal(Opcode, VT))
4821       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4822     return SDValue();
4823   }
4824   default:
4825     return SDValue();
4826   }
4827 }
4828
4829 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4830   SDValue N0 = N->getOperand(0);
4831   SDValue N1 = N->getOperand(1);
4832   SDValue N2 = N->getOperand(2);
4833   EVT VT = N->getValueType(0);
4834   EVT VT0 = N0.getValueType();
4835
4836   // fold (select C, X, X) -> X
4837   if (N1 == N2)
4838     return N1;
4839   // fold (select true, X, Y) -> X
4840   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4841   if (N0C && !N0C->isNullValue())
4842     return N1;
4843   // fold (select false, X, Y) -> Y
4844   if (N0C && N0C->isNullValue())
4845     return N2;
4846   // fold (select C, 1, X) -> (or C, X)
4847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4848   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4849     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4850   // fold (select C, 0, 1) -> (xor C, 1)
4851   // We can't do this reliably if integer based booleans have different contents
4852   // to floating point based booleans. This is because we can't tell whether we
4853   // have an integer-based boolean or a floating-point-based boolean unless we
4854   // can find the SETCC that produced it and inspect its operands. This is
4855   // fairly easy if C is the SETCC node, but it can potentially be
4856   // undiscoverable (or not reasonably discoverable). For example, it could be
4857   // in another basic block or it could require searching a complicated
4858   // expression.
4859   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4860   if (VT.isInteger() &&
4861       (VT0 == MVT::i1 || (VT0.isInteger() &&
4862                           TLI.getBooleanContents(false, false) ==
4863                               TLI.getBooleanContents(false, true) &&
4864                           TLI.getBooleanContents(false, false) ==
4865                               TargetLowering::ZeroOrOneBooleanContent)) &&
4866       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4867     SDValue XORNode;
4868     if (VT == VT0) {
4869       SDLoc DL(N);
4870       return DAG.getNode(ISD::XOR, DL, VT0,
4871                          N0, DAG.getConstant(1, DL, VT0));
4872     }
4873     SDLoc DL0(N0);
4874     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4875                           N0, DAG.getConstant(1, DL0, VT0));
4876     AddToWorklist(XORNode.getNode());
4877     if (VT.bitsGT(VT0))
4878       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4879     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4880   }
4881   // fold (select C, 0, X) -> (and (not C), X)
4882   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4883     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4884     AddToWorklist(NOTNode.getNode());
4885     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4886   }
4887   // fold (select C, X, 1) -> (or (not C), X)
4888   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4889     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4890     AddToWorklist(NOTNode.getNode());
4891     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4892   }
4893   // fold (select C, X, 0) -> (and C, X)
4894   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4895     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4896   // fold (select X, X, Y) -> (or X, Y)
4897   // fold (select X, 1, Y) -> (or X, Y)
4898   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4899     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4900   // fold (select X, Y, X) -> (and X, Y)
4901   // fold (select X, Y, 0) -> (and X, Y)
4902   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4903     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4904
4905   // If we can fold this based on the true/false value, do so.
4906   if (SimplifySelectOps(N, N1, N2))
4907     return SDValue(N, 0);  // Don't revisit N.
4908
4909   // fold selects based on a setcc into other things, such as min/max/abs
4910   if (N0.getOpcode() == ISD::SETCC) {
4911     // select x, y (fcmp lt x, y) -> fminnum x, y
4912     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4913     //
4914     // This is OK if we don't care about what happens if either operand is a
4915     // NaN.
4916     //
4917
4918     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4919     // no signed zeros as well as no nans.
4920     const TargetOptions &Options = DAG.getTarget().Options;
4921     if (Options.UnsafeFPMath &&
4922         VT.isFloatingPoint() && N0.hasOneUse() &&
4923         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4924       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4925
4926       SDValue FMinMax =
4927           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4928                               N1, N2, CC, TLI, DAG);
4929       if (FMinMax)
4930         return FMinMax;
4931     }
4932
4933     if ((!LegalOperations &&
4934          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4935         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4936       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4937                          N0.getOperand(0), N0.getOperand(1),
4938                          N1, N2, N0.getOperand(2));
4939     return SimplifySelect(SDLoc(N), N0, N1, N2);
4940   }
4941
4942   if (VT0 == MVT::i1) {
4943     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4944       // select (and Cond0, Cond1), X, Y
4945       //   -> select Cond0, (select Cond1, X, Y), Y
4946       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4947         SDValue Cond0 = N0->getOperand(0);
4948         SDValue Cond1 = N0->getOperand(1);
4949         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4950                                           N1.getValueType(), Cond1, N1, N2);
4951         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4952                            InnerSelect, N2);
4953       }
4954       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4955       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4956         SDValue Cond0 = N0->getOperand(0);
4957         SDValue Cond1 = N0->getOperand(1);
4958         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4959                                           N1.getValueType(), Cond1, N1, N2);
4960         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4961                            InnerSelect);
4962       }
4963     }
4964
4965     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4966     if (N1->getOpcode() == ISD::SELECT) {
4967       SDValue N1_0 = N1->getOperand(0);
4968       SDValue N1_1 = N1->getOperand(1);
4969       SDValue N1_2 = N1->getOperand(2);
4970       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4971         // Create the actual and node if we can generate good code for it.
4972         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4973           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4974                                     N0, N1_0);
4975           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4976                              N1_1, N2);
4977         }
4978         // Otherwise see if we can optimize the "and" to a better pattern.
4979         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4980           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4981                              N1_1, N2);
4982       }
4983     }
4984     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4985     if (N2->getOpcode() == ISD::SELECT) {
4986       SDValue N2_0 = N2->getOperand(0);
4987       SDValue N2_1 = N2->getOperand(1);
4988       SDValue N2_2 = N2->getOperand(2);
4989       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4990         // Create the actual or node if we can generate good code for it.
4991         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4992           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4993                                    N0, N2_0);
4994           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4995                              N1, N2_2);
4996         }
4997         // Otherwise see if we can optimize to a better pattern.
4998         if (SDValue Combined = visitORLike(N0, N2_0, N))
4999           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5000                              N1, N2_2);
5001       }
5002     }
5003   }
5004
5005   return SDValue();
5006 }
5007
5008 static
5009 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5010   SDLoc DL(N);
5011   EVT LoVT, HiVT;
5012   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5013
5014   // Split the inputs.
5015   SDValue Lo, Hi, LL, LH, RL, RH;
5016   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5017   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5018
5019   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5020   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5021
5022   return std::make_pair(Lo, Hi);
5023 }
5024
5025 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5026 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5027 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5028   SDLoc dl(N);
5029   SDValue Cond = N->getOperand(0);
5030   SDValue LHS = N->getOperand(1);
5031   SDValue RHS = N->getOperand(2);
5032   EVT VT = N->getValueType(0);
5033   int NumElems = VT.getVectorNumElements();
5034   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5035          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5036          Cond.getOpcode() == ISD::BUILD_VECTOR);
5037
5038   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5039   // binary ones here.
5040   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5041     return SDValue();
5042
5043   // We're sure we have an even number of elements due to the
5044   // concat_vectors we have as arguments to vselect.
5045   // Skip BV elements until we find one that's not an UNDEF
5046   // After we find an UNDEF element, keep looping until we get to half the
5047   // length of the BV and see if all the non-undef nodes are the same.
5048   ConstantSDNode *BottomHalf = nullptr;
5049   for (int i = 0; i < NumElems / 2; ++i) {
5050     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5051       continue;
5052
5053     if (BottomHalf == nullptr)
5054       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5055     else if (Cond->getOperand(i).getNode() != BottomHalf)
5056       return SDValue();
5057   }
5058
5059   // Do the same for the second half of the BuildVector
5060   ConstantSDNode *TopHalf = nullptr;
5061   for (int i = NumElems / 2; i < NumElems; ++i) {
5062     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5063       continue;
5064
5065     if (TopHalf == nullptr)
5066       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5067     else if (Cond->getOperand(i).getNode() != TopHalf)
5068       return SDValue();
5069   }
5070
5071   assert(TopHalf && BottomHalf &&
5072          "One half of the selector was all UNDEFs and the other was all the "
5073          "same value. This should have been addressed before this function.");
5074   return DAG.getNode(
5075       ISD::CONCAT_VECTORS, dl, VT,
5076       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5077       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5078 }
5079
5080 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5081
5082   if (Level >= AfterLegalizeTypes)
5083     return SDValue();
5084
5085   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5086   SDValue Mask = MSC->getMask();
5087   SDValue Data  = MSC->getValue();
5088   SDLoc DL(N);
5089
5090   // If the MSCATTER data type requires splitting and the mask is provided by a
5091   // SETCC, then split both nodes and its operands before legalization. This
5092   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5093   // and enables future optimizations (e.g. min/max pattern matching on X86).
5094   if (Mask.getOpcode() != ISD::SETCC)
5095     return SDValue();
5096
5097   // Check if any splitting is required.
5098   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5099       TargetLowering::TypeSplitVector)
5100     return SDValue();
5101   SDValue MaskLo, MaskHi, Lo, Hi;
5102   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5103
5104   EVT LoVT, HiVT;
5105   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5106
5107   SDValue Chain = MSC->getChain();
5108
5109   EVT MemoryVT = MSC->getMemoryVT();
5110   unsigned Alignment = MSC->getOriginalAlignment();
5111
5112   EVT LoMemVT, HiMemVT;
5113   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5114
5115   SDValue DataLo, DataHi;
5116   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5117
5118   SDValue BasePtr = MSC->getBasePtr();
5119   SDValue IndexLo, IndexHi;
5120   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5121
5122   MachineMemOperand *MMO = DAG.getMachineFunction().
5123     getMachineMemOperand(MSC->getPointerInfo(), 
5124                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5125                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5126
5127   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5128   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5129                             DL, OpsLo, MMO);
5130
5131   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5132   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5133                             DL, OpsHi, MMO);
5134
5135   AddToWorklist(Lo.getNode());
5136   AddToWorklist(Hi.getNode());
5137
5138   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5139 }
5140
5141 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5142
5143   if (Level >= AfterLegalizeTypes)
5144     return SDValue();
5145
5146   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5147   SDValue Mask = MST->getMask();
5148   SDValue Data  = MST->getValue();
5149   SDLoc DL(N);
5150
5151   // If the MSTORE data type requires splitting and the mask is provided by a
5152   // SETCC, then split both nodes and its operands before legalization. This
5153   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5154   // and enables future optimizations (e.g. min/max pattern matching on X86).
5155   if (Mask.getOpcode() == ISD::SETCC) {
5156
5157     // Check if any splitting is required.
5158     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5159         TargetLowering::TypeSplitVector)
5160       return SDValue();
5161
5162     SDValue MaskLo, MaskHi, Lo, Hi;
5163     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5164
5165     EVT LoVT, HiVT;
5166     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5167
5168     SDValue Chain = MST->getChain();
5169     SDValue Ptr   = MST->getBasePtr();
5170
5171     EVT MemoryVT = MST->getMemoryVT();
5172     unsigned Alignment = MST->getOriginalAlignment();
5173
5174     // if Alignment is equal to the vector size,
5175     // take the half of it for the second part
5176     unsigned SecondHalfAlignment =
5177       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5178          Alignment/2 : Alignment;
5179
5180     EVT LoMemVT, HiMemVT;
5181     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5182
5183     SDValue DataLo, DataHi;
5184     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5185
5186     MachineMemOperand *MMO = DAG.getMachineFunction().
5187       getMachineMemOperand(MST->getPointerInfo(),
5188                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5189                            Alignment, MST->getAAInfo(), MST->getRanges());
5190
5191     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5192                             MST->isTruncatingStore());
5193
5194     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5195     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5196                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5197
5198     MMO = DAG.getMachineFunction().
5199       getMachineMemOperand(MST->getPointerInfo(),
5200                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5201                            SecondHalfAlignment, MST->getAAInfo(),
5202                            MST->getRanges());
5203
5204     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5205                             MST->isTruncatingStore());
5206
5207     AddToWorklist(Lo.getNode());
5208     AddToWorklist(Hi.getNode());
5209
5210     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5211   }
5212   return SDValue();
5213 }
5214
5215 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5216
5217   if (Level >= AfterLegalizeTypes)
5218     return SDValue();
5219
5220   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5221   SDValue Mask = MGT->getMask();
5222   SDLoc DL(N);
5223
5224   // If the MGATHER result requires splitting and the mask is provided by a
5225   // SETCC, then split both nodes and its operands before legalization. This
5226   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5227   // and enables future optimizations (e.g. min/max pattern matching on X86).
5228
5229   if (Mask.getOpcode() != ISD::SETCC)
5230     return SDValue();
5231
5232   EVT VT = N->getValueType(0);
5233
5234   // Check if any splitting is required.
5235   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5236       TargetLowering::TypeSplitVector)
5237     return SDValue();
5238
5239   SDValue MaskLo, MaskHi, Lo, Hi;
5240   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5241
5242   SDValue Src0 = MGT->getValue();
5243   SDValue Src0Lo, Src0Hi;
5244   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5245
5246   EVT LoVT, HiVT;
5247   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5248
5249   SDValue Chain = MGT->getChain();
5250   EVT MemoryVT = MGT->getMemoryVT();
5251   unsigned Alignment = MGT->getOriginalAlignment();
5252
5253   EVT LoMemVT, HiMemVT;
5254   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5255
5256   SDValue BasePtr = MGT->getBasePtr();
5257   SDValue Index = MGT->getIndex();
5258   SDValue IndexLo, IndexHi;
5259   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5260
5261   MachineMemOperand *MMO = DAG.getMachineFunction().
5262     getMachineMemOperand(MGT->getPointerInfo(), 
5263                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5264                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5265
5266   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5267   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5268                             MMO);
5269
5270   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5271   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5272                             MMO);
5273
5274   AddToWorklist(Lo.getNode());
5275   AddToWorklist(Hi.getNode());
5276
5277   // Build a factor node to remember that this load is independent of the
5278   // other one.
5279   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5280                       Hi.getValue(1));
5281
5282   // Legalized the chain result - switch anything that used the old chain to
5283   // use the new one.
5284   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5285
5286   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5287
5288   SDValue RetOps[] = { GatherRes, Chain };
5289   return DAG.getMergeValues(RetOps, DL);
5290 }
5291
5292 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5293
5294   if (Level >= AfterLegalizeTypes)
5295     return SDValue();
5296
5297   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5298   SDValue Mask = MLD->getMask();
5299   SDLoc DL(N);
5300
5301   // If the MLOAD result requires splitting and the mask is provided by a
5302   // SETCC, then split both nodes and its operands before legalization. This
5303   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5304   // and enables future optimizations (e.g. min/max pattern matching on X86).
5305
5306   if (Mask.getOpcode() == ISD::SETCC) {
5307     EVT VT = N->getValueType(0);
5308
5309     // Check if any splitting is required.
5310     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5311         TargetLowering::TypeSplitVector)
5312       return SDValue();
5313
5314     SDValue MaskLo, MaskHi, Lo, Hi;
5315     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5316
5317     SDValue Src0 = MLD->getSrc0();
5318     SDValue Src0Lo, Src0Hi;
5319     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5320
5321     EVT LoVT, HiVT;
5322     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5323
5324     SDValue Chain = MLD->getChain();
5325     SDValue Ptr   = MLD->getBasePtr();
5326     EVT MemoryVT = MLD->getMemoryVT();
5327     unsigned Alignment = MLD->getOriginalAlignment();
5328
5329     // if Alignment is equal to the vector size,
5330     // take the half of it for the second part
5331     unsigned SecondHalfAlignment =
5332       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5333          Alignment/2 : Alignment;
5334
5335     EVT LoMemVT, HiMemVT;
5336     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5337
5338     MachineMemOperand *MMO = DAG.getMachineFunction().
5339     getMachineMemOperand(MLD->getPointerInfo(),
5340                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5341                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5342
5343     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5344                            ISD::NON_EXTLOAD);
5345
5346     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5347     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5348                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5349
5350     MMO = DAG.getMachineFunction().
5351     getMachineMemOperand(MLD->getPointerInfo(),
5352                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5353                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5354
5355     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5356                            ISD::NON_EXTLOAD);
5357
5358     AddToWorklist(Lo.getNode());
5359     AddToWorklist(Hi.getNode());
5360
5361     // Build a factor node to remember that this load is independent of the
5362     // other one.
5363     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5364                         Hi.getValue(1));
5365
5366     // Legalized the chain result - switch anything that used the old chain to
5367     // use the new one.
5368     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5369
5370     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5371
5372     SDValue RetOps[] = { LoadRes, Chain };
5373     return DAG.getMergeValues(RetOps, DL);
5374   }
5375   return SDValue();
5376 }
5377
5378 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5379   SDValue N0 = N->getOperand(0);
5380   SDValue N1 = N->getOperand(1);
5381   SDValue N2 = N->getOperand(2);
5382   SDLoc DL(N);
5383
5384   // Canonicalize integer abs.
5385   // vselect (setg[te] X,  0),  X, -X ->
5386   // vselect (setgt    X, -1),  X, -X ->
5387   // vselect (setl[te] X,  0), -X,  X ->
5388   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5389   if (N0.getOpcode() == ISD::SETCC) {
5390     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5391     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5392     bool isAbs = false;
5393     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5394
5395     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5396          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5397         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5398       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5399     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5400              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5401       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5402
5403     if (isAbs) {
5404       EVT VT = LHS.getValueType();
5405       SDValue Shift = DAG.getNode(
5406           ISD::SRA, DL, VT, LHS,
5407           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5408       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5409       AddToWorklist(Shift.getNode());
5410       AddToWorklist(Add.getNode());
5411       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5412     }
5413   }
5414
5415   if (SimplifySelectOps(N, N1, N2))
5416     return SDValue(N, 0);  // Don't revisit N.
5417
5418   // If the VSELECT result requires splitting and the mask is provided by a
5419   // SETCC, then split both nodes and its operands before legalization. This
5420   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5421   // and enables future optimizations (e.g. min/max pattern matching on X86).
5422   if (N0.getOpcode() == ISD::SETCC) {
5423     EVT VT = N->getValueType(0);
5424
5425     // Check if any splitting is required.
5426     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5427         TargetLowering::TypeSplitVector)
5428       return SDValue();
5429
5430     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5431     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5432     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5433     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5434
5435     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5436     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5437
5438     // Add the new VSELECT nodes to the work list in case they need to be split
5439     // again.
5440     AddToWorklist(Lo.getNode());
5441     AddToWorklist(Hi.getNode());
5442
5443     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5444   }
5445
5446   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5447   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5448     return N1;
5449   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5450   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5451     return N2;
5452
5453   // The ConvertSelectToConcatVector function is assuming both the above
5454   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5455   // and addressed.
5456   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5457       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5458       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5459     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5460     if (CV.getNode())
5461       return CV;
5462   }
5463
5464   return SDValue();
5465 }
5466
5467 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5468   SDValue N0 = N->getOperand(0);
5469   SDValue N1 = N->getOperand(1);
5470   SDValue N2 = N->getOperand(2);
5471   SDValue N3 = N->getOperand(3);
5472   SDValue N4 = N->getOperand(4);
5473   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5474
5475   // fold select_cc lhs, rhs, x, x, cc -> x
5476   if (N2 == N3)
5477     return N2;
5478
5479   // Determine if the condition we're dealing with is constant
5480   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5481                               N0, N1, CC, SDLoc(N), false);
5482   if (SCC.getNode()) {
5483     AddToWorklist(SCC.getNode());
5484
5485     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5486       if (!SCCC->isNullValue())
5487         return N2;    // cond always true -> true val
5488       else
5489         return N3;    // cond always false -> false val
5490     } else if (SCC->getOpcode() == ISD::UNDEF) {
5491       // When the condition is UNDEF, just return the first operand. This is
5492       // coherent the DAG creation, no setcc node is created in this case
5493       return N2;
5494     } else if (SCC.getOpcode() == ISD::SETCC) {
5495       // Fold to a simpler select_cc
5496       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5497                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5498                          SCC.getOperand(2));
5499     }
5500   }
5501
5502   // If we can fold this based on the true/false value, do so.
5503   if (SimplifySelectOps(N, N2, N3))
5504     return SDValue(N, 0);  // Don't revisit N.
5505
5506   // fold select_cc into other things, such as min/max/abs
5507   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5508 }
5509
5510 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5511   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5512                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5513                        SDLoc(N));
5514 }
5515
5516 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5517 // dag node into a ConstantSDNode or a build_vector of constants.
5518 // This function is called by the DAGCombiner when visiting sext/zext/aext
5519 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5520 // Vector extends are not folded if operations are legal; this is to
5521 // avoid introducing illegal build_vector dag nodes.
5522 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5523                                          SelectionDAG &DAG, bool LegalTypes,
5524                                          bool LegalOperations) {
5525   unsigned Opcode = N->getOpcode();
5526   SDValue N0 = N->getOperand(0);
5527   EVT VT = N->getValueType(0);
5528
5529   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5530          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5531
5532   // fold (sext c1) -> c1
5533   // fold (zext c1) -> c1
5534   // fold (aext c1) -> c1
5535   if (isa<ConstantSDNode>(N0))
5536     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5537
5538   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5539   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5540   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5541   EVT SVT = VT.getScalarType();
5542   if (!(VT.isVector() &&
5543       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5544       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5545     return nullptr;
5546
5547   // We can fold this node into a build_vector.
5548   unsigned VTBits = SVT.getSizeInBits();
5549   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5550   unsigned ShAmt = VTBits - EVTBits;
5551   SmallVector<SDValue, 8> Elts;
5552   unsigned NumElts = N0->getNumOperands();
5553   SDLoc DL(N);
5554
5555   for (unsigned i=0; i != NumElts; ++i) {
5556     SDValue Op = N0->getOperand(i);
5557     if (Op->getOpcode() == ISD::UNDEF) {
5558       Elts.push_back(DAG.getUNDEF(SVT));
5559       continue;
5560     }
5561
5562     SDLoc DL(Op);
5563     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5564     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5565     if (Opcode == ISD::SIGN_EXTEND)
5566       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5567                                      DL, SVT));
5568     else
5569       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5570                                      DL, SVT));
5571   }
5572
5573   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5574 }
5575
5576 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5577 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5578 // transformation. Returns true if extension are possible and the above
5579 // mentioned transformation is profitable.
5580 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5581                                     unsigned ExtOpc,
5582                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5583                                     const TargetLowering &TLI) {
5584   bool HasCopyToRegUses = false;
5585   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5586   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5587                             UE = N0.getNode()->use_end();
5588        UI != UE; ++UI) {
5589     SDNode *User = *UI;
5590     if (User == N)
5591       continue;
5592     if (UI.getUse().getResNo() != N0.getResNo())
5593       continue;
5594     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5595     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5596       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5597       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5598         // Sign bits will be lost after a zext.
5599         return false;
5600       bool Add = false;
5601       for (unsigned i = 0; i != 2; ++i) {
5602         SDValue UseOp = User->getOperand(i);
5603         if (UseOp == N0)
5604           continue;
5605         if (!isa<ConstantSDNode>(UseOp))
5606           return false;
5607         Add = true;
5608       }
5609       if (Add)
5610         ExtendNodes.push_back(User);
5611       continue;
5612     }
5613     // If truncates aren't free and there are users we can't
5614     // extend, it isn't worthwhile.
5615     if (!isTruncFree)
5616       return false;
5617     // Remember if this value is live-out.
5618     if (User->getOpcode() == ISD::CopyToReg)
5619       HasCopyToRegUses = true;
5620   }
5621
5622   if (HasCopyToRegUses) {
5623     bool BothLiveOut = false;
5624     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5625          UI != UE; ++UI) {
5626       SDUse &Use = UI.getUse();
5627       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5628         BothLiveOut = true;
5629         break;
5630       }
5631     }
5632     if (BothLiveOut)
5633       // Both unextended and extended values are live out. There had better be
5634       // a good reason for the transformation.
5635       return ExtendNodes.size();
5636   }
5637   return true;
5638 }
5639
5640 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5641                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5642                                   ISD::NodeType ExtType) {
5643   // Extend SetCC uses if necessary.
5644   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5645     SDNode *SetCC = SetCCs[i];
5646     SmallVector<SDValue, 4> Ops;
5647
5648     for (unsigned j = 0; j != 2; ++j) {
5649       SDValue SOp = SetCC->getOperand(j);
5650       if (SOp == Trunc)
5651         Ops.push_back(ExtLoad);
5652       else
5653         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5654     }
5655
5656     Ops.push_back(SetCC->getOperand(2));
5657     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5658   }
5659 }
5660
5661 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5662 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5663   SDValue N0 = N->getOperand(0);
5664   EVT DstVT = N->getValueType(0);
5665   EVT SrcVT = N0.getValueType();
5666
5667   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5668           N->getOpcode() == ISD::ZERO_EXTEND) &&
5669          "Unexpected node type (not an extend)!");
5670
5671   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5672   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5673   //   (v8i32 (sext (v8i16 (load x))))
5674   // into:
5675   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5676   //                          (v4i32 (sextload (x + 16)))))
5677   // Where uses of the original load, i.e.:
5678   //   (v8i16 (load x))
5679   // are replaced with:
5680   //   (v8i16 (truncate
5681   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5682   //                            (v4i32 (sextload (x + 16)))))))
5683   //
5684   // This combine is only applicable to illegal, but splittable, vectors.
5685   // All legal types, and illegal non-vector types, are handled elsewhere.
5686   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5687   //
5688   if (N0->getOpcode() != ISD::LOAD)
5689     return SDValue();
5690
5691   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5692
5693   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5694       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5695       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5696     return SDValue();
5697
5698   SmallVector<SDNode *, 4> SetCCs;
5699   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5700     return SDValue();
5701
5702   ISD::LoadExtType ExtType =
5703       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5704
5705   // Try to split the vector types to get down to legal types.
5706   EVT SplitSrcVT = SrcVT;
5707   EVT SplitDstVT = DstVT;
5708   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5709          SplitSrcVT.getVectorNumElements() > 1) {
5710     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5711     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5712   }
5713
5714   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5715     return SDValue();
5716
5717   SDLoc DL(N);
5718   const unsigned NumSplits =
5719       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5720   const unsigned Stride = SplitSrcVT.getStoreSize();
5721   SmallVector<SDValue, 4> Loads;
5722   SmallVector<SDValue, 4> Chains;
5723
5724   SDValue BasePtr = LN0->getBasePtr();
5725   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5726     const unsigned Offset = Idx * Stride;
5727     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5728
5729     SDValue SplitLoad = DAG.getExtLoad(
5730         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5731         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5732         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5733         Align, LN0->getAAInfo());
5734
5735     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5736                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5737
5738     Loads.push_back(SplitLoad.getValue(0));
5739     Chains.push_back(SplitLoad.getValue(1));
5740   }
5741
5742   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5743   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5744
5745   CombineTo(N, NewValue);
5746
5747   // Replace uses of the original load (before extension)
5748   // with a truncate of the concatenated sextloaded vectors.
5749   SDValue Trunc =
5750       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5751   CombineTo(N0.getNode(), Trunc, NewChain);
5752   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5753                   (ISD::NodeType)N->getOpcode());
5754   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5755 }
5756
5757 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5758   SDValue N0 = N->getOperand(0);
5759   EVT VT = N->getValueType(0);
5760
5761   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5762                                               LegalOperations))
5763     return SDValue(Res, 0);
5764
5765   // fold (sext (sext x)) -> (sext x)
5766   // fold (sext (aext x)) -> (sext x)
5767   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5768     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5769                        N0.getOperand(0));
5770
5771   if (N0.getOpcode() == ISD::TRUNCATE) {
5772     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5773     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5774     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5775     if (NarrowLoad.getNode()) {
5776       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5777       if (NarrowLoad.getNode() != N0.getNode()) {
5778         CombineTo(N0.getNode(), NarrowLoad);
5779         // CombineTo deleted the truncate, if needed, but not what's under it.
5780         AddToWorklist(oye);
5781       }
5782       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5783     }
5784
5785     // See if the value being truncated is already sign extended.  If so, just
5786     // eliminate the trunc/sext pair.
5787     SDValue Op = N0.getOperand(0);
5788     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5789     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5790     unsigned DestBits = VT.getScalarType().getSizeInBits();
5791     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5792
5793     if (OpBits == DestBits) {
5794       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5795       // bits, it is already ready.
5796       if (NumSignBits > DestBits-MidBits)
5797         return Op;
5798     } else if (OpBits < DestBits) {
5799       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5800       // bits, just sext from i32.
5801       if (NumSignBits > OpBits-MidBits)
5802         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5803     } else {
5804       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5805       // bits, just truncate to i32.
5806       if (NumSignBits > OpBits-MidBits)
5807         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5808     }
5809
5810     // fold (sext (truncate x)) -> (sextinreg x).
5811     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5812                                                  N0.getValueType())) {
5813       if (OpBits < DestBits)
5814         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5815       else if (OpBits > DestBits)
5816         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5817       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5818                          DAG.getValueType(N0.getValueType()));
5819     }
5820   }
5821
5822   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5823   // Only generate vector extloads when 1) they're legal, and 2) they are
5824   // deemed desirable by the target.
5825   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826       ((!LegalOperations && !VT.isVector() &&
5827         !cast<LoadSDNode>(N0)->isVolatile()) ||
5828        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5829     bool DoXform = true;
5830     SmallVector<SDNode*, 4> SetCCs;
5831     if (!N0.hasOneUse())
5832       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5833     if (VT.isVector())
5834       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5835     if (DoXform) {
5836       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5837       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5838                                        LN0->getChain(),
5839                                        LN0->getBasePtr(), N0.getValueType(),
5840                                        LN0->getMemOperand());
5841       CombineTo(N, ExtLoad);
5842       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5843                                   N0.getValueType(), ExtLoad);
5844       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5845       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5846                       ISD::SIGN_EXTEND);
5847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5848     }
5849   }
5850
5851   // fold (sext (load x)) to multiple smaller sextloads.
5852   // Only on illegal but splittable vectors.
5853   if (SDValue ExtLoad = CombineExtLoad(N))
5854     return ExtLoad;
5855
5856   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5857   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5858   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5859       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5860     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861     EVT MemVT = LN0->getMemoryVT();
5862     if ((!LegalOperations && !LN0->isVolatile()) ||
5863         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5864       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5865                                        LN0->getChain(),
5866                                        LN0->getBasePtr(), MemVT,
5867                                        LN0->getMemOperand());
5868       CombineTo(N, ExtLoad);
5869       CombineTo(N0.getNode(),
5870                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5871                             N0.getValueType(), ExtLoad),
5872                 ExtLoad.getValue(1));
5873       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5874     }
5875   }
5876
5877   // fold (sext (and/or/xor (load x), cst)) ->
5878   //      (and/or/xor (sextload x), (sext cst))
5879   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5880        N0.getOpcode() == ISD::XOR) &&
5881       isa<LoadSDNode>(N0.getOperand(0)) &&
5882       N0.getOperand(1).getOpcode() == ISD::Constant &&
5883       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5884       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5885     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5886     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5887       bool DoXform = true;
5888       SmallVector<SDNode*, 4> SetCCs;
5889       if (!N0.hasOneUse())
5890         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5891                                           SetCCs, TLI);
5892       if (DoXform) {
5893         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5894                                          LN0->getChain(), LN0->getBasePtr(),
5895                                          LN0->getMemoryVT(),
5896                                          LN0->getMemOperand());
5897         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5898         Mask = Mask.sext(VT.getSizeInBits());
5899         SDLoc DL(N);
5900         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5901                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5902         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5903                                     SDLoc(N0.getOperand(0)),
5904                                     N0.getOperand(0).getValueType(), ExtLoad);
5905         CombineTo(N, And);
5906         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5907         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5908                         ISD::SIGN_EXTEND);
5909         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5910       }
5911     }
5912   }
5913
5914   if (N0.getOpcode() == ISD::SETCC) {
5915     EVT N0VT = N0.getOperand(0).getValueType();
5916     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5917     // Only do this before legalize for now.
5918     if (VT.isVector() && !LegalOperations &&
5919         TLI.getBooleanContents(N0VT) ==
5920             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5921       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5922       // of the same size as the compared operands. Only optimize sext(setcc())
5923       // if this is the case.
5924       EVT SVT = getSetCCResultType(N0VT);
5925
5926       // We know that the # elements of the results is the same as the
5927       // # elements of the compare (and the # elements of the compare result
5928       // for that matter).  Check to see that they are the same size.  If so,
5929       // we know that the element size of the sext'd result matches the
5930       // element size of the compare operands.
5931       if (VT.getSizeInBits() == SVT.getSizeInBits())
5932         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5933                              N0.getOperand(1),
5934                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5935
5936       // If the desired elements are smaller or larger than the source
5937       // elements we can use a matching integer vector type and then
5938       // truncate/sign extend
5939       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5940       if (SVT == MatchingVectorType) {
5941         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5942                                N0.getOperand(0), N0.getOperand(1),
5943                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5944         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5945       }
5946     }
5947
5948     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5949     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5950     SDLoc DL(N);
5951     SDValue NegOne =
5952       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5953     SDValue SCC =
5954       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5955                        NegOne, DAG.getConstant(0, DL, VT),
5956                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5957     if (SCC.getNode()) return SCC;
5958
5959     if (!VT.isVector()) {
5960       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5961       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5962         SDLoc DL(N);
5963         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5964         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5965                                      N0.getOperand(0), N0.getOperand(1), CC);
5966         return DAG.getSelect(DL, VT, SetCC,
5967                              NegOne, DAG.getConstant(0, DL, VT));
5968       }
5969     }
5970   }
5971
5972   // fold (sext x) -> (zext x) if the sign bit is known zero.
5973   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5974       DAG.SignBitIsZero(N0))
5975     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5976
5977   return SDValue();
5978 }
5979
5980 // isTruncateOf - If N is a truncate of some other value, return true, record
5981 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5982 // This function computes KnownZero to avoid a duplicated call to
5983 // computeKnownBits in the caller.
5984 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5985                          APInt &KnownZero) {
5986   APInt KnownOne;
5987   if (N->getOpcode() == ISD::TRUNCATE) {
5988     Op = N->getOperand(0);
5989     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5990     return true;
5991   }
5992
5993   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5994       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5995     return false;
5996
5997   SDValue Op0 = N->getOperand(0);
5998   SDValue Op1 = N->getOperand(1);
5999   assert(Op0.getValueType() == Op1.getValueType());
6000
6001   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
6002   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
6003   if (COp0 && COp0->isNullValue())
6004     Op = Op1;
6005   else if (COp1 && COp1->isNullValue())
6006     Op = Op0;
6007   else
6008     return false;
6009
6010   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6011
6012   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6013     return false;
6014
6015   return true;
6016 }
6017
6018 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6019   SDValue N0 = N->getOperand(0);
6020   EVT VT = N->getValueType(0);
6021
6022   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6023                                               LegalOperations))
6024     return SDValue(Res, 0);
6025
6026   // fold (zext (zext x)) -> (zext x)
6027   // fold (zext (aext x)) -> (zext x)
6028   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6029     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6030                        N0.getOperand(0));
6031
6032   // fold (zext (truncate x)) -> (zext x) or
6033   //      (zext (truncate x)) -> (truncate x)
6034   // This is valid when the truncated bits of x are already zero.
6035   // FIXME: We should extend this to work for vectors too.
6036   SDValue Op;
6037   APInt KnownZero;
6038   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6039     APInt TruncatedBits =
6040       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6041       APInt(Op.getValueSizeInBits(), 0) :
6042       APInt::getBitsSet(Op.getValueSizeInBits(),
6043                         N0.getValueSizeInBits(),
6044                         std::min(Op.getValueSizeInBits(),
6045                                  VT.getSizeInBits()));
6046     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6047       if (VT.bitsGT(Op.getValueType()))
6048         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6049       if (VT.bitsLT(Op.getValueType()))
6050         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6051
6052       return Op;
6053     }
6054   }
6055
6056   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6057   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6058   if (N0.getOpcode() == ISD::TRUNCATE) {
6059     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6060     if (NarrowLoad.getNode()) {
6061       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6062       if (NarrowLoad.getNode() != N0.getNode()) {
6063         CombineTo(N0.getNode(), NarrowLoad);
6064         // CombineTo deleted the truncate, if needed, but not what's under it.
6065         AddToWorklist(oye);
6066       }
6067       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6068     }
6069   }
6070
6071   // fold (zext (truncate x)) -> (and x, mask)
6072   if (N0.getOpcode() == ISD::TRUNCATE &&
6073       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6074
6075     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6076     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6077     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6078     if (NarrowLoad.getNode()) {
6079       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6080       if (NarrowLoad.getNode() != N0.getNode()) {
6081         CombineTo(N0.getNode(), NarrowLoad);
6082         // CombineTo deleted the truncate, if needed, but not what's under it.
6083         AddToWorklist(oye);
6084       }
6085       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6086     }
6087
6088     SDValue Op = N0.getOperand(0);
6089     if (Op.getValueType().bitsLT(VT)) {
6090       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6091       AddToWorklist(Op.getNode());
6092     } else if (Op.getValueType().bitsGT(VT)) {
6093       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6094       AddToWorklist(Op.getNode());
6095     }
6096     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6097                                   N0.getValueType().getScalarType());
6098   }
6099
6100   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6101   // if either of the casts is not free.
6102   if (N0.getOpcode() == ISD::AND &&
6103       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6104       N0.getOperand(1).getOpcode() == ISD::Constant &&
6105       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6106                            N0.getValueType()) ||
6107        !TLI.isZExtFree(N0.getValueType(), VT))) {
6108     SDValue X = N0.getOperand(0).getOperand(0);
6109     if (X.getValueType().bitsLT(VT)) {
6110       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6111     } else if (X.getValueType().bitsGT(VT)) {
6112       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6113     }
6114     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6115     Mask = Mask.zext(VT.getSizeInBits());
6116     SDLoc DL(N);
6117     return DAG.getNode(ISD::AND, DL, VT,
6118                        X, DAG.getConstant(Mask, DL, VT));
6119   }
6120
6121   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6122   // Only generate vector extloads when 1) they're legal, and 2) they are
6123   // deemed desirable by the target.
6124   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6125       ((!LegalOperations && !VT.isVector() &&
6126         !cast<LoadSDNode>(N0)->isVolatile()) ||
6127        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6128     bool DoXform = true;
6129     SmallVector<SDNode*, 4> SetCCs;
6130     if (!N0.hasOneUse())
6131       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6132     if (VT.isVector())
6133       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6134     if (DoXform) {
6135       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6136       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6137                                        LN0->getChain(),
6138                                        LN0->getBasePtr(), N0.getValueType(),
6139                                        LN0->getMemOperand());
6140       CombineTo(N, ExtLoad);
6141       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6142                                   N0.getValueType(), ExtLoad);
6143       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6144
6145       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6146                       ISD::ZERO_EXTEND);
6147       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6148     }
6149   }
6150
6151   // fold (zext (load x)) to multiple smaller zextloads.
6152   // Only on illegal but splittable vectors.
6153   if (SDValue ExtLoad = CombineExtLoad(N))
6154     return ExtLoad;
6155
6156   // fold (zext (and/or/xor (load x), cst)) ->
6157   //      (and/or/xor (zextload x), (zext cst))
6158   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6159        N0.getOpcode() == ISD::XOR) &&
6160       isa<LoadSDNode>(N0.getOperand(0)) &&
6161       N0.getOperand(1).getOpcode() == ISD::Constant &&
6162       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6163       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6164     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6165     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6166       bool DoXform = true;
6167       SmallVector<SDNode*, 4> SetCCs;
6168       if (!N0.hasOneUse())
6169         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6170                                           SetCCs, TLI);
6171       if (DoXform) {
6172         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6173                                          LN0->getChain(), LN0->getBasePtr(),
6174                                          LN0->getMemoryVT(),
6175                                          LN0->getMemOperand());
6176         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6177         Mask = Mask.zext(VT.getSizeInBits());
6178         SDLoc DL(N);
6179         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6180                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6181         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6182                                     SDLoc(N0.getOperand(0)),
6183                                     N0.getOperand(0).getValueType(), ExtLoad);
6184         CombineTo(N, And);
6185         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6186         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6187                         ISD::ZERO_EXTEND);
6188         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6189       }
6190     }
6191   }
6192
6193   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6194   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6195   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6196       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6197     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6198     EVT MemVT = LN0->getMemoryVT();
6199     if ((!LegalOperations && !LN0->isVolatile()) ||
6200         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6201       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6202                                        LN0->getChain(),
6203                                        LN0->getBasePtr(), MemVT,
6204                                        LN0->getMemOperand());
6205       CombineTo(N, ExtLoad);
6206       CombineTo(N0.getNode(),
6207                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6208                             ExtLoad),
6209                 ExtLoad.getValue(1));
6210       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6211     }
6212   }
6213
6214   if (N0.getOpcode() == ISD::SETCC) {
6215     if (!LegalOperations && VT.isVector() &&
6216         N0.getValueType().getVectorElementType() == MVT::i1) {
6217       EVT N0VT = N0.getOperand(0).getValueType();
6218       if (getSetCCResultType(N0VT) == N0.getValueType())
6219         return SDValue();
6220
6221       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6222       // Only do this before legalize for now.
6223       EVT EltVT = VT.getVectorElementType();
6224       SDLoc DL(N);
6225       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6226                                     DAG.getConstant(1, DL, EltVT));
6227       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6228         // We know that the # elements of the results is the same as the
6229         // # elements of the compare (and the # elements of the compare result
6230         // for that matter).  Check to see that they are the same size.  If so,
6231         // we know that the element size of the sext'd result matches the
6232         // element size of the compare operands.
6233         return DAG.getNode(ISD::AND, DL, VT,
6234                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6235                                          N0.getOperand(1),
6236                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6237                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6238                                        OneOps));
6239
6240       // If the desired elements are smaller or larger than the source
6241       // elements we can use a matching integer vector type and then
6242       // truncate/sign extend
6243       EVT MatchingElementType =
6244         EVT::getIntegerVT(*DAG.getContext(),
6245                           N0VT.getScalarType().getSizeInBits());
6246       EVT MatchingVectorType =
6247         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6248                          N0VT.getVectorNumElements());
6249       SDValue VsetCC =
6250         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6251                       N0.getOperand(1),
6252                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6253       return DAG.getNode(ISD::AND, DL, VT,
6254                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6255                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6256     }
6257
6258     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6259     SDLoc DL(N);
6260     SDValue SCC =
6261       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6262                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6263                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6264     if (SCC.getNode()) return SCC;
6265   }
6266
6267   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6268   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6269       isa<ConstantSDNode>(N0.getOperand(1)) &&
6270       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6271       N0.hasOneUse()) {
6272     SDValue ShAmt = N0.getOperand(1);
6273     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6274     if (N0.getOpcode() == ISD::SHL) {
6275       SDValue InnerZExt = N0.getOperand(0);
6276       // If the original shl may be shifting out bits, do not perform this
6277       // transformation.
6278       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6279         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6280       if (ShAmtVal > KnownZeroBits)
6281         return SDValue();
6282     }
6283
6284     SDLoc DL(N);
6285
6286     // Ensure that the shift amount is wide enough for the shifted value.
6287     if (VT.getSizeInBits() >= 256)
6288       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6289
6290     return DAG.getNode(N0.getOpcode(), DL, VT,
6291                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6292                        ShAmt);
6293   }
6294
6295   return SDValue();
6296 }
6297
6298 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6299   SDValue N0 = N->getOperand(0);
6300   EVT VT = N->getValueType(0);
6301
6302   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6303                                               LegalOperations))
6304     return SDValue(Res, 0);
6305
6306   // fold (aext (aext x)) -> (aext x)
6307   // fold (aext (zext x)) -> (zext x)
6308   // fold (aext (sext x)) -> (sext x)
6309   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6310       N0.getOpcode() == ISD::ZERO_EXTEND ||
6311       N0.getOpcode() == ISD::SIGN_EXTEND)
6312     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6313
6314   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6315   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6316   if (N0.getOpcode() == ISD::TRUNCATE) {
6317     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6318     if (NarrowLoad.getNode()) {
6319       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6320       if (NarrowLoad.getNode() != N0.getNode()) {
6321         CombineTo(N0.getNode(), NarrowLoad);
6322         // CombineTo deleted the truncate, if needed, but not what's under it.
6323         AddToWorklist(oye);
6324       }
6325       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6326     }
6327   }
6328
6329   // fold (aext (truncate x))
6330   if (N0.getOpcode() == ISD::TRUNCATE) {
6331     SDValue TruncOp = N0.getOperand(0);
6332     if (TruncOp.getValueType() == VT)
6333       return TruncOp; // x iff x size == zext size.
6334     if (TruncOp.getValueType().bitsGT(VT))
6335       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6336     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6337   }
6338
6339   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6340   // if the trunc is not free.
6341   if (N0.getOpcode() == ISD::AND &&
6342       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6343       N0.getOperand(1).getOpcode() == ISD::Constant &&
6344       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6345                           N0.getValueType())) {
6346     SDValue X = N0.getOperand(0).getOperand(0);
6347     if (X.getValueType().bitsLT(VT)) {
6348       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6349     } else if (X.getValueType().bitsGT(VT)) {
6350       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6351     }
6352     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6353     Mask = Mask.zext(VT.getSizeInBits());
6354     SDLoc DL(N);
6355     return DAG.getNode(ISD::AND, DL, VT,
6356                        X, DAG.getConstant(Mask, DL, VT));
6357   }
6358
6359   // fold (aext (load x)) -> (aext (truncate (extload x)))
6360   // None of the supported targets knows how to perform load and any_ext
6361   // on vectors in one instruction.  We only perform this transformation on
6362   // scalars.
6363   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6364       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6365       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6366     bool DoXform = true;
6367     SmallVector<SDNode*, 4> SetCCs;
6368     if (!N0.hasOneUse())
6369       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6370     if (DoXform) {
6371       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6372       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6373                                        LN0->getChain(),
6374                                        LN0->getBasePtr(), N0.getValueType(),
6375                                        LN0->getMemOperand());
6376       CombineTo(N, ExtLoad);
6377       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6378                                   N0.getValueType(), ExtLoad);
6379       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6380       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6381                       ISD::ANY_EXTEND);
6382       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6383     }
6384   }
6385
6386   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6387   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6388   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6389   if (N0.getOpcode() == ISD::LOAD &&
6390       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6391       N0.hasOneUse()) {
6392     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6393     ISD::LoadExtType ExtType = LN0->getExtensionType();
6394     EVT MemVT = LN0->getMemoryVT();
6395     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6396       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6397                                        VT, LN0->getChain(), LN0->getBasePtr(),
6398                                        MemVT, LN0->getMemOperand());
6399       CombineTo(N, ExtLoad);
6400       CombineTo(N0.getNode(),
6401                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6402                             N0.getValueType(), ExtLoad),
6403                 ExtLoad.getValue(1));
6404       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6405     }
6406   }
6407
6408   if (N0.getOpcode() == ISD::SETCC) {
6409     // For vectors:
6410     // aext(setcc) -> vsetcc
6411     // aext(setcc) -> truncate(vsetcc)
6412     // aext(setcc) -> aext(vsetcc)
6413     // Only do this before legalize for now.
6414     if (VT.isVector() && !LegalOperations) {
6415       EVT N0VT = N0.getOperand(0).getValueType();
6416         // We know that the # elements of the results is the same as the
6417         // # elements of the compare (and the # elements of the compare result
6418         // for that matter).  Check to see that they are the same size.  If so,
6419         // we know that the element size of the sext'd result matches the
6420         // element size of the compare operands.
6421       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6422         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6423                              N0.getOperand(1),
6424                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6425       // If the desired elements are smaller or larger than the source
6426       // elements we can use a matching integer vector type and then
6427       // truncate/any extend
6428       else {
6429         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6430         SDValue VsetCC =
6431           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6432                         N0.getOperand(1),
6433                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6434         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6435       }
6436     }
6437
6438     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6439     SDLoc DL(N);
6440     SDValue SCC =
6441       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6442                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6443                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6444     if (SCC.getNode())
6445       return SCC;
6446   }
6447
6448   return SDValue();
6449 }
6450
6451 /// See if the specified operand can be simplified with the knowledge that only
6452 /// the bits specified by Mask are used.  If so, return the simpler operand,
6453 /// otherwise return a null SDValue.
6454 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6455   switch (V.getOpcode()) {
6456   default: break;
6457   case ISD::Constant: {
6458     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6459     assert(CV && "Const value should be ConstSDNode.");
6460     const APInt &CVal = CV->getAPIntValue();
6461     APInt NewVal = CVal & Mask;
6462     if (NewVal != CVal)
6463       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6464     break;
6465   }
6466   case ISD::OR:
6467   case ISD::XOR:
6468     // If the LHS or RHS don't contribute bits to the or, drop them.
6469     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6470       return V.getOperand(1);
6471     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6472       return V.getOperand(0);
6473     break;
6474   case ISD::SRL:
6475     // Only look at single-use SRLs.
6476     if (!V.getNode()->hasOneUse())
6477       break;
6478     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6479       // See if we can recursively simplify the LHS.
6480       unsigned Amt = RHSC->getZExtValue();
6481
6482       // Watch out for shift count overflow though.
6483       if (Amt >= Mask.getBitWidth()) break;
6484       APInt NewMask = Mask << Amt;
6485       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6486       if (SimplifyLHS.getNode())
6487         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6488                            SimplifyLHS, V.getOperand(1));
6489     }
6490   }
6491   return SDValue();
6492 }
6493
6494 /// If the result of a wider load is shifted to right of N  bits and then
6495 /// truncated to a narrower type and where N is a multiple of number of bits of
6496 /// the narrower type, transform it to a narrower load from address + N / num of
6497 /// bits of new type. If the result is to be extended, also fold the extension
6498 /// to form a extending load.
6499 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6500   unsigned Opc = N->getOpcode();
6501
6502   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6503   SDValue N0 = N->getOperand(0);
6504   EVT VT = N->getValueType(0);
6505   EVT ExtVT = VT;
6506
6507   // This transformation isn't valid for vector loads.
6508   if (VT.isVector())
6509     return SDValue();
6510
6511   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6512   // extended to VT.
6513   if (Opc == ISD::SIGN_EXTEND_INREG) {
6514     ExtType = ISD::SEXTLOAD;
6515     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6516   } else if (Opc == ISD::SRL) {
6517     // Another special-case: SRL is basically zero-extending a narrower value.
6518     ExtType = ISD::ZEXTLOAD;
6519     N0 = SDValue(N, 0);
6520     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6521     if (!N01) return SDValue();
6522     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6523                               VT.getSizeInBits() - N01->getZExtValue());
6524   }
6525   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6526     return SDValue();
6527
6528   unsigned EVTBits = ExtVT.getSizeInBits();
6529
6530   // Do not generate loads of non-round integer types since these can
6531   // be expensive (and would be wrong if the type is not byte sized).
6532   if (!ExtVT.isRound())
6533     return SDValue();
6534
6535   unsigned ShAmt = 0;
6536   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6537     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6538       ShAmt = N01->getZExtValue();
6539       // Is the shift amount a multiple of size of VT?
6540       if ((ShAmt & (EVTBits-1)) == 0) {
6541         N0 = N0.getOperand(0);
6542         // Is the load width a multiple of size of VT?
6543         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6544           return SDValue();
6545       }
6546
6547       // At this point, we must have a load or else we can't do the transform.
6548       if (!isa<LoadSDNode>(N0)) return SDValue();
6549
6550       // Because a SRL must be assumed to *need* to zero-extend the high bits
6551       // (as opposed to anyext the high bits), we can't combine the zextload
6552       // lowering of SRL and an sextload.
6553       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6554         return SDValue();
6555
6556       // If the shift amount is larger than the input type then we're not
6557       // accessing any of the loaded bytes.  If the load was a zextload/extload
6558       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6559       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6560         return SDValue();
6561     }
6562   }
6563
6564   // If the load is shifted left (and the result isn't shifted back right),
6565   // we can fold the truncate through the shift.
6566   unsigned ShLeftAmt = 0;
6567   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6568       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6569     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6570       ShLeftAmt = N01->getZExtValue();
6571       N0 = N0.getOperand(0);
6572     }
6573   }
6574
6575   // If we haven't found a load, we can't narrow it.  Don't transform one with
6576   // multiple uses, this would require adding a new load.
6577   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6578     return SDValue();
6579
6580   // Don't change the width of a volatile load.
6581   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6582   if (LN0->isVolatile())
6583     return SDValue();
6584
6585   // Verify that we are actually reducing a load width here.
6586   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6587     return SDValue();
6588
6589   // For the transform to be legal, the load must produce only two values
6590   // (the value loaded and the chain).  Don't transform a pre-increment
6591   // load, for example, which produces an extra value.  Otherwise the
6592   // transformation is not equivalent, and the downstream logic to replace
6593   // uses gets things wrong.
6594   if (LN0->getNumValues() > 2)
6595     return SDValue();
6596
6597   // If the load that we're shrinking is an extload and we're not just
6598   // discarding the extension we can't simply shrink the load. Bail.
6599   // TODO: It would be possible to merge the extensions in some cases.
6600   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6601       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6602     return SDValue();
6603
6604   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6605     return SDValue();
6606
6607   EVT PtrType = N0.getOperand(1).getValueType();
6608
6609   if (PtrType == MVT::Untyped || PtrType.isExtended())
6610     // It's not possible to generate a constant of extended or untyped type.
6611     return SDValue();
6612
6613   // For big endian targets, we need to adjust the offset to the pointer to
6614   // load the correct bytes.
6615   if (TLI.isBigEndian()) {
6616     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6617     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6618     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6619   }
6620
6621   uint64_t PtrOff = ShAmt / 8;
6622   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6623   SDLoc DL(LN0);
6624   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6625                                PtrType, LN0->getBasePtr(),
6626                                DAG.getConstant(PtrOff, DL, PtrType));
6627   AddToWorklist(NewPtr.getNode());
6628
6629   SDValue Load;
6630   if (ExtType == ISD::NON_EXTLOAD)
6631     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6632                         LN0->getPointerInfo().getWithOffset(PtrOff),
6633                         LN0->isVolatile(), LN0->isNonTemporal(),
6634                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6635   else
6636     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6637                           LN0->getPointerInfo().getWithOffset(PtrOff),
6638                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6639                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6640
6641   // Replace the old load's chain with the new load's chain.
6642   WorklistRemover DeadNodes(*this);
6643   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6644
6645   // Shift the result left, if we've swallowed a left shift.
6646   SDValue Result = Load;
6647   if (ShLeftAmt != 0) {
6648     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6649     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6650       ShImmTy = VT;
6651     // If the shift amount is as large as the result size (but, presumably,
6652     // no larger than the source) then the useful bits of the result are
6653     // zero; we can't simply return the shortened shift, because the result
6654     // of that operation is undefined.
6655     SDLoc DL(N0);
6656     if (ShLeftAmt >= VT.getSizeInBits())
6657       Result = DAG.getConstant(0, DL, VT);
6658     else
6659       Result = DAG.getNode(ISD::SHL, DL, VT,
6660                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6661   }
6662
6663   // Return the new loaded value.
6664   return Result;
6665 }
6666
6667 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6668   SDValue N0 = N->getOperand(0);
6669   SDValue N1 = N->getOperand(1);
6670   EVT VT = N->getValueType(0);
6671   EVT EVT = cast<VTSDNode>(N1)->getVT();
6672   unsigned VTBits = VT.getScalarType().getSizeInBits();
6673   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6674
6675   // fold (sext_in_reg c1) -> c1
6676   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6677     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6678
6679   // If the input is already sign extended, just drop the extension.
6680   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6681     return N0;
6682
6683   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6684   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6685       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6686     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6687                        N0.getOperand(0), N1);
6688
6689   // fold (sext_in_reg (sext x)) -> (sext x)
6690   // fold (sext_in_reg (aext x)) -> (sext x)
6691   // if x is small enough.
6692   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6693     SDValue N00 = N0.getOperand(0);
6694     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6695         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6696       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6697   }
6698
6699   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6700   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6701     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6702
6703   // fold operands of sext_in_reg based on knowledge that the top bits are not
6704   // demanded.
6705   if (SimplifyDemandedBits(SDValue(N, 0)))
6706     return SDValue(N, 0);
6707
6708   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6709   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6710   SDValue NarrowLoad = ReduceLoadWidth(N);
6711   if (NarrowLoad.getNode())
6712     return NarrowLoad;
6713
6714   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6715   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6716   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6717   if (N0.getOpcode() == ISD::SRL) {
6718     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6719       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6720         // We can turn this into an SRA iff the input to the SRL is already sign
6721         // extended enough.
6722         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6723         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6724           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6725                              N0.getOperand(0), N0.getOperand(1));
6726       }
6727   }
6728
6729   // fold (sext_inreg (extload x)) -> (sextload x)
6730   if (ISD::isEXTLoad(N0.getNode()) &&
6731       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6732       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6733       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6734        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6735     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6736     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6737                                      LN0->getChain(),
6738                                      LN0->getBasePtr(), EVT,
6739                                      LN0->getMemOperand());
6740     CombineTo(N, ExtLoad);
6741     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6742     AddToWorklist(ExtLoad.getNode());
6743     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6744   }
6745   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6746   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6747       N0.hasOneUse() &&
6748       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6749       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6750        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6751     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6752     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6753                                      LN0->getChain(),
6754                                      LN0->getBasePtr(), EVT,
6755                                      LN0->getMemOperand());
6756     CombineTo(N, ExtLoad);
6757     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6758     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6759   }
6760
6761   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6762   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6763     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6764                                        N0.getOperand(1), false);
6765     if (BSwap.getNode())
6766       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6767                          BSwap, N1);
6768   }
6769
6770   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6771   // into a build_vector.
6772   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6773     SmallVector<SDValue, 8> Elts;
6774     unsigned NumElts = N0->getNumOperands();
6775     unsigned ShAmt = VTBits - EVTBits;
6776
6777     for (unsigned i = 0; i != NumElts; ++i) {
6778       SDValue Op = N0->getOperand(i);
6779       if (Op->getOpcode() == ISD::UNDEF) {
6780         Elts.push_back(Op);
6781         continue;
6782       }
6783
6784       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6785       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6786       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6787                                      SDLoc(Op), Op.getValueType()));
6788     }
6789
6790     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6791   }
6792
6793   return SDValue();
6794 }
6795
6796 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6797   SDValue N0 = N->getOperand(0);
6798   EVT VT = N->getValueType(0);
6799   bool isLE = TLI.isLittleEndian();
6800
6801   // noop truncate
6802   if (N0.getValueType() == N->getValueType(0))
6803     return N0;
6804   // fold (truncate c1) -> c1
6805   if (isConstantIntBuildVectorOrConstantInt(N0))
6806     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6807   // fold (truncate (truncate x)) -> (truncate x)
6808   if (N0.getOpcode() == ISD::TRUNCATE)
6809     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6810   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6811   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6812       N0.getOpcode() == ISD::SIGN_EXTEND ||
6813       N0.getOpcode() == ISD::ANY_EXTEND) {
6814     if (N0.getOperand(0).getValueType().bitsLT(VT))
6815       // if the source is smaller than the dest, we still need an extend
6816       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6817                          N0.getOperand(0));
6818     if (N0.getOperand(0).getValueType().bitsGT(VT))
6819       // if the source is larger than the dest, than we just need the truncate
6820       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6821     // if the source and dest are the same type, we can drop both the extend
6822     // and the truncate.
6823     return N0.getOperand(0);
6824   }
6825
6826   // Fold extract-and-trunc into a narrow extract. For example:
6827   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6828   //   i32 y = TRUNCATE(i64 x)
6829   //        -- becomes --
6830   //   v16i8 b = BITCAST (v2i64 val)
6831   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6832   //
6833   // Note: We only run this optimization after type legalization (which often
6834   // creates this pattern) and before operation legalization after which
6835   // we need to be more careful about the vector instructions that we generate.
6836   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6837       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6838
6839     EVT VecTy = N0.getOperand(0).getValueType();
6840     EVT ExTy = N0.getValueType();
6841     EVT TrTy = N->getValueType(0);
6842
6843     unsigned NumElem = VecTy.getVectorNumElements();
6844     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6845
6846     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6847     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6848
6849     SDValue EltNo = N0->getOperand(1);
6850     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6851       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6852       EVT IndexTy = TLI.getVectorIdxTy();
6853       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6854
6855       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6856                               NVT, N0.getOperand(0));
6857
6858       SDLoc DL(N);
6859       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6860                          DL, TrTy, V,
6861                          DAG.getConstant(Index, DL, IndexTy));
6862     }
6863   }
6864
6865   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6866   if (N0.getOpcode() == ISD::SELECT) {
6867     EVT SrcVT = N0.getValueType();
6868     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6869         TLI.isTruncateFree(SrcVT, VT)) {
6870       SDLoc SL(N0);
6871       SDValue Cond = N0.getOperand(0);
6872       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6873       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6874       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6875     }
6876   }
6877
6878   // Fold a series of buildvector, bitcast, and truncate if possible.
6879   // For example fold
6880   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6881   //   (2xi32 (buildvector x, y)).
6882   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6883       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6884       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6885       N0.getOperand(0).hasOneUse()) {
6886
6887     SDValue BuildVect = N0.getOperand(0);
6888     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6889     EVT TruncVecEltTy = VT.getVectorElementType();
6890
6891     // Check that the element types match.
6892     if (BuildVectEltTy == TruncVecEltTy) {
6893       // Now we only need to compute the offset of the truncated elements.
6894       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6895       unsigned TruncVecNumElts = VT.getVectorNumElements();
6896       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6897
6898       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6899              "Invalid number of elements");
6900
6901       SmallVector<SDValue, 8> Opnds;
6902       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6903         Opnds.push_back(BuildVect.getOperand(i));
6904
6905       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6906     }
6907   }
6908
6909   // See if we can simplify the input to this truncate through knowledge that
6910   // only the low bits are being used.
6911   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6912   // Currently we only perform this optimization on scalars because vectors
6913   // may have different active low bits.
6914   if (!VT.isVector()) {
6915     SDValue Shorter =
6916       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6917                                                VT.getSizeInBits()));
6918     if (Shorter.getNode())
6919       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6920   }
6921   // fold (truncate (load x)) -> (smaller load x)
6922   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6923   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6924     SDValue Reduced = ReduceLoadWidth(N);
6925     if (Reduced.getNode())
6926       return Reduced;
6927     // Handle the case where the load remains an extending load even
6928     // after truncation.
6929     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6930       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6931       if (!LN0->isVolatile() &&
6932           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6933         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6934                                          VT, LN0->getChain(), LN0->getBasePtr(),
6935                                          LN0->getMemoryVT(),
6936                                          LN0->getMemOperand());
6937         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6938         return NewLoad;
6939       }
6940     }
6941   }
6942   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6943   // where ... are all 'undef'.
6944   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6945     SmallVector<EVT, 8> VTs;
6946     SDValue V;
6947     unsigned Idx = 0;
6948     unsigned NumDefs = 0;
6949
6950     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6951       SDValue X = N0.getOperand(i);
6952       if (X.getOpcode() != ISD::UNDEF) {
6953         V = X;
6954         Idx = i;
6955         NumDefs++;
6956       }
6957       // Stop if more than one members are non-undef.
6958       if (NumDefs > 1)
6959         break;
6960       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6961                                      VT.getVectorElementType(),
6962                                      X.getValueType().getVectorNumElements()));
6963     }
6964
6965     if (NumDefs == 0)
6966       return DAG.getUNDEF(VT);
6967
6968     if (NumDefs == 1) {
6969       assert(V.getNode() && "The single defined operand is empty!");
6970       SmallVector<SDValue, 8> Opnds;
6971       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6972         if (i != Idx) {
6973           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6974           continue;
6975         }
6976         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6977         AddToWorklist(NV.getNode());
6978         Opnds.push_back(NV);
6979       }
6980       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6981     }
6982   }
6983
6984   // Simplify the operands using demanded-bits information.
6985   if (!VT.isVector() &&
6986       SimplifyDemandedBits(SDValue(N, 0)))
6987     return SDValue(N, 0);
6988
6989   return SDValue();
6990 }
6991
6992 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6993   SDValue Elt = N->getOperand(i);
6994   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6995     return Elt.getNode();
6996   return Elt.getOperand(Elt.getResNo()).getNode();
6997 }
6998
6999 /// build_pair (load, load) -> load
7000 /// if load locations are consecutive.
7001 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7002   assert(N->getOpcode() == ISD::BUILD_PAIR);
7003
7004   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7005   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7006   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7007       LD1->getAddressSpace() != LD2->getAddressSpace())
7008     return SDValue();
7009   EVT LD1VT = LD1->getValueType(0);
7010
7011   if (ISD::isNON_EXTLoad(LD2) &&
7012       LD2->hasOneUse() &&
7013       // If both are volatile this would reduce the number of volatile loads.
7014       // If one is volatile it might be ok, but play conservative and bail out.
7015       !LD1->isVolatile() &&
7016       !LD2->isVolatile() &&
7017       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7018     unsigned Align = LD1->getAlignment();
7019     unsigned NewAlign = TLI.getDataLayout()->
7020       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7021
7022     if (NewAlign <= Align &&
7023         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7024       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7025                          LD1->getBasePtr(), LD1->getPointerInfo(),
7026                          false, false, false, Align);
7027   }
7028
7029   return SDValue();
7030 }
7031
7032 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7033   SDValue N0 = N->getOperand(0);
7034   EVT VT = N->getValueType(0);
7035
7036   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7037   // Only do this before legalize, since afterward the target may be depending
7038   // on the bitconvert.
7039   // First check to see if this is all constant.
7040   if (!LegalTypes &&
7041       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7042       VT.isVector()) {
7043     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7044
7045     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7046     assert(!DestEltVT.isVector() &&
7047            "Element type of vector ValueType must not be vector!");
7048     if (isSimple)
7049       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7050   }
7051
7052   // If the input is a constant, let getNode fold it.
7053   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7054     // If we can't allow illegal operations, we need to check that this is just
7055     // a fp -> int or int -> conversion and that the resulting operation will
7056     // be legal.
7057     if (!LegalOperations ||
7058         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7059          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7060         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7061          TLI.isOperationLegal(ISD::Constant, VT)))
7062       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7063   }
7064
7065   // (conv (conv x, t1), t2) -> (conv x, t2)
7066   if (N0.getOpcode() == ISD::BITCAST)
7067     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7068                        N0.getOperand(0));
7069
7070   // fold (conv (load x)) -> (load (conv*)x)
7071   // If the resultant load doesn't need a higher alignment than the original!
7072   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7073       // Do not change the width of a volatile load.
7074       !cast<LoadSDNode>(N0)->isVolatile() &&
7075       // Do not remove the cast if the types differ in endian layout.
7076       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7077       TLI.hasBigEndianPartOrdering(VT) &&
7078       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7079       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7080     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7081     unsigned Align = TLI.getDataLayout()->
7082       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7083     unsigned OrigAlign = LN0->getAlignment();
7084
7085     if (Align <= OrigAlign) {
7086       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7087                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7088                                  LN0->isVolatile(), LN0->isNonTemporal(),
7089                                  LN0->isInvariant(), OrigAlign,
7090                                  LN0->getAAInfo());
7091       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7092       return Load;
7093     }
7094   }
7095
7096   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7097   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7098   // This often reduces constant pool loads.
7099   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7100        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7101       N0.getNode()->hasOneUse() && VT.isInteger() &&
7102       !VT.isVector() && !N0.getValueType().isVector()) {
7103     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7104                                   N0.getOperand(0));
7105     AddToWorklist(NewConv.getNode());
7106
7107     SDLoc DL(N);
7108     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7109     if (N0.getOpcode() == ISD::FNEG)
7110       return DAG.getNode(ISD::XOR, DL, VT,
7111                          NewConv, DAG.getConstant(SignBit, DL, VT));
7112     assert(N0.getOpcode() == ISD::FABS);
7113     return DAG.getNode(ISD::AND, DL, VT,
7114                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7115   }
7116
7117   // fold (bitconvert (fcopysign cst, x)) ->
7118   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7119   // Note that we don't handle (copysign x, cst) because this can always be
7120   // folded to an fneg or fabs.
7121   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7122       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7123       VT.isInteger() && !VT.isVector()) {
7124     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7125     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7126     if (isTypeLegal(IntXVT)) {
7127       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7128                               IntXVT, N0.getOperand(1));
7129       AddToWorklist(X.getNode());
7130
7131       // If X has a different width than the result/lhs, sext it or truncate it.
7132       unsigned VTWidth = VT.getSizeInBits();
7133       if (OrigXWidth < VTWidth) {
7134         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7135         AddToWorklist(X.getNode());
7136       } else if (OrigXWidth > VTWidth) {
7137         // To get the sign bit in the right place, we have to shift it right
7138         // before truncating.
7139         SDLoc DL(X);
7140         X = DAG.getNode(ISD::SRL, DL,
7141                         X.getValueType(), X,
7142                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7143                                         X.getValueType()));
7144         AddToWorklist(X.getNode());
7145         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7146         AddToWorklist(X.getNode());
7147       }
7148
7149       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7150       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7151                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7152       AddToWorklist(X.getNode());
7153
7154       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7155                                 VT, N0.getOperand(0));
7156       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7157                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7158       AddToWorklist(Cst.getNode());
7159
7160       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7161     }
7162   }
7163
7164   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7165   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7166     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7167     if (CombineLD.getNode())
7168       return CombineLD;
7169   }
7170
7171   // Remove double bitcasts from shuffles - this is often a legacy of
7172   // XformToShuffleWithZero being used to combine bitmaskings (of
7173   // float vectors bitcast to integer vectors) into shuffles.
7174   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7175   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7176       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7177       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7178       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7179     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7180
7181     // If operands are a bitcast, peek through if it casts the original VT.
7182     // If operands are a UNDEF or constant, just bitcast back to original VT.
7183     auto PeekThroughBitcast = [&](SDValue Op) {
7184       if (Op.getOpcode() == ISD::BITCAST &&
7185           Op.getOperand(0)->getValueType(0) == VT)
7186         return SDValue(Op.getOperand(0));
7187       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7188           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7189         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7190       return SDValue();
7191     };
7192
7193     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7194     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7195     if (!(SV0 && SV1))
7196       return SDValue();
7197
7198     int MaskScale =
7199         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7200     SmallVector<int, 8> NewMask;
7201     for (int M : SVN->getMask())
7202       for (int i = 0; i != MaskScale; ++i)
7203         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7204
7205     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7206     if (!LegalMask) {
7207       std::swap(SV0, SV1);
7208       ShuffleVectorSDNode::commuteMask(NewMask);
7209       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7210     }
7211
7212     if (LegalMask)
7213       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7214   }
7215
7216   return SDValue();
7217 }
7218
7219 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7220   EVT VT = N->getValueType(0);
7221   return CombineConsecutiveLoads(N, VT);
7222 }
7223
7224 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7225 /// operands. DstEltVT indicates the destination element value type.
7226 SDValue DAGCombiner::
7227 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7228   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7229
7230   // If this is already the right type, we're done.
7231   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7232
7233   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7234   unsigned DstBitSize = DstEltVT.getSizeInBits();
7235
7236   // If this is a conversion of N elements of one type to N elements of another
7237   // type, convert each element.  This handles FP<->INT cases.
7238   if (SrcBitSize == DstBitSize) {
7239     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7240                               BV->getValueType(0).getVectorNumElements());
7241
7242     // Due to the FP element handling below calling this routine recursively,
7243     // we can end up with a scalar-to-vector node here.
7244     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7245       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7246                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7247                                      DstEltVT, BV->getOperand(0)));
7248
7249     SmallVector<SDValue, 8> Ops;
7250     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7251       SDValue Op = BV->getOperand(i);
7252       // If the vector element type is not legal, the BUILD_VECTOR operands
7253       // are promoted and implicitly truncated.  Make that explicit here.
7254       if (Op.getValueType() != SrcEltVT)
7255         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7256       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7257                                 DstEltVT, Op));
7258       AddToWorklist(Ops.back().getNode());
7259     }
7260     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7261   }
7262
7263   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7264   // handle annoying details of growing/shrinking FP values, we convert them to
7265   // int first.
7266   if (SrcEltVT.isFloatingPoint()) {
7267     // Convert the input float vector to a int vector where the elements are the
7268     // same sizes.
7269     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7270     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7271     SrcEltVT = IntVT;
7272   }
7273
7274   // Now we know the input is an integer vector.  If the output is a FP type,
7275   // convert to integer first, then to FP of the right size.
7276   if (DstEltVT.isFloatingPoint()) {
7277     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7278     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7279
7280     // Next, convert to FP elements of the same size.
7281     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7282   }
7283
7284   SDLoc DL(BV);
7285
7286   // Okay, we know the src/dst types are both integers of differing types.
7287   // Handling growing first.
7288   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7289   if (SrcBitSize < DstBitSize) {
7290     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7291
7292     SmallVector<SDValue, 8> Ops;
7293     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7294          i += NumInputsPerOutput) {
7295       bool isLE = TLI.isLittleEndian();
7296       APInt NewBits = APInt(DstBitSize, 0);
7297       bool EltIsUndef = true;
7298       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7299         // Shift the previously computed bits over.
7300         NewBits <<= SrcBitSize;
7301         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7302         if (Op.getOpcode() == ISD::UNDEF) continue;
7303         EltIsUndef = false;
7304
7305         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7306                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7307       }
7308
7309       if (EltIsUndef)
7310         Ops.push_back(DAG.getUNDEF(DstEltVT));
7311       else
7312         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7313     }
7314
7315     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7316     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7317   }
7318
7319   // Finally, this must be the case where we are shrinking elements: each input
7320   // turns into multiple outputs.
7321   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7322   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7323                             NumOutputsPerInput*BV->getNumOperands());
7324   SmallVector<SDValue, 8> Ops;
7325
7326   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7327     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7328       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7329       continue;
7330     }
7331
7332     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7333                   getAPIntValue().zextOrTrunc(SrcBitSize);
7334
7335     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7336       APInt ThisVal = OpVal.trunc(DstBitSize);
7337       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7338       OpVal = OpVal.lshr(DstBitSize);
7339     }
7340
7341     // For big endian targets, swap the order of the pieces of each element.
7342     if (TLI.isBigEndian())
7343       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7344   }
7345
7346   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7347 }
7348
7349 /// Try to perform FMA combining on a given FADD node.
7350 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7351   SDValue N0 = N->getOperand(0);
7352   SDValue N1 = N->getOperand(1);
7353   EVT VT = N->getValueType(0);
7354   SDLoc SL(N);
7355
7356   const TargetOptions &Options = DAG.getTarget().Options;
7357   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7358                        Options.UnsafeFPMath);
7359
7360   // Floating-point multiply-add with intermediate rounding.
7361   bool HasFMAD = (LegalOperations &&
7362                   TLI.isOperationLegal(ISD::FMAD, VT));
7363
7364   // Floating-point multiply-add without intermediate rounding.
7365   bool HasFMA = ((!LegalOperations ||
7366                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7367                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7368                  UnsafeFPMath);
7369
7370   // No valid opcode, do not combine.
7371   if (!HasFMAD && !HasFMA)
7372     return SDValue();
7373
7374   // Always prefer FMAD to FMA for precision.
7375   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7376   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7377   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7378
7379   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7380   if (N0.getOpcode() == ISD::FMUL &&
7381       (Aggressive || N0->hasOneUse())) {
7382     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7383                        N0.getOperand(0), N0.getOperand(1), N1);
7384   }
7385
7386   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7387   // Note: Commutes FADD operands.
7388   if (N1.getOpcode() == ISD::FMUL &&
7389       (Aggressive || N1->hasOneUse())) {
7390     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7391                        N1.getOperand(0), N1.getOperand(1), N0);
7392   }
7393
7394   // Look through FP_EXTEND nodes to do more combining.
7395   if (UnsafeFPMath && LookThroughFPExt) {
7396     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7397     if (N0.getOpcode() == ISD::FP_EXTEND) {
7398       SDValue N00 = N0.getOperand(0);
7399       if (N00.getOpcode() == ISD::FMUL)
7400         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7401                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7402                                        N00.getOperand(0)),
7403                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7404                                        N00.getOperand(1)), N1);
7405     }
7406
7407     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7408     // Note: Commutes FADD operands.
7409     if (N1.getOpcode() == ISD::FP_EXTEND) {
7410       SDValue N10 = N1.getOperand(0);
7411       if (N10.getOpcode() == ISD::FMUL)
7412         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7414                                        N10.getOperand(0)),
7415                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416                                        N10.getOperand(1)), N0);
7417     }
7418   }
7419
7420   // More folding opportunities when target permits.
7421   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7422     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7423     if (N0.getOpcode() == PreferredFusedOpcode &&
7424         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7425       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7426                          N0.getOperand(0), N0.getOperand(1),
7427                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7428                                      N0.getOperand(2).getOperand(0),
7429                                      N0.getOperand(2).getOperand(1),
7430                                      N1));
7431     }
7432
7433     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7434     if (N1->getOpcode() == PreferredFusedOpcode &&
7435         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7436       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7437                          N1.getOperand(0), N1.getOperand(1),
7438                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7439                                      N1.getOperand(2).getOperand(0),
7440                                      N1.getOperand(2).getOperand(1),
7441                                      N0));
7442     }
7443
7444     if (UnsafeFPMath && LookThroughFPExt) {
7445       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7446       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7447       auto FoldFAddFMAFPExtFMul = [&] (
7448           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7449         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7450                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7451                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7452                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7453                                        Z));
7454       };
7455       if (N0.getOpcode() == PreferredFusedOpcode) {
7456         SDValue N02 = N0.getOperand(2);
7457         if (N02.getOpcode() == ISD::FP_EXTEND) {
7458           SDValue N020 = N02.getOperand(0);
7459           if (N020.getOpcode() == ISD::FMUL)
7460             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7461                                         N020.getOperand(0), N020.getOperand(1),
7462                                         N1);
7463         }
7464       }
7465
7466       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7467       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7468       // FIXME: This turns two single-precision and one double-precision
7469       // operation into two double-precision operations, which might not be
7470       // interesting for all targets, especially GPUs.
7471       auto FoldFAddFPExtFMAFMul = [&] (
7472           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7473         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7475                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7476                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7477                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7478                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7479                                        Z));
7480       };
7481       if (N0.getOpcode() == ISD::FP_EXTEND) {
7482         SDValue N00 = N0.getOperand(0);
7483         if (N00.getOpcode() == PreferredFusedOpcode) {
7484           SDValue N002 = N00.getOperand(2);
7485           if (N002.getOpcode() == ISD::FMUL)
7486             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7487                                         N002.getOperand(0), N002.getOperand(1),
7488                                         N1);
7489         }
7490       }
7491
7492       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7493       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7494       if (N1.getOpcode() == PreferredFusedOpcode) {
7495         SDValue N12 = N1.getOperand(2);
7496         if (N12.getOpcode() == ISD::FP_EXTEND) {
7497           SDValue N120 = N12.getOperand(0);
7498           if (N120.getOpcode() == ISD::FMUL)
7499             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7500                                         N120.getOperand(0), N120.getOperand(1),
7501                                         N0);
7502         }
7503       }
7504
7505       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7506       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7507       // FIXME: This turns two single-precision and one double-precision
7508       // operation into two double-precision operations, which might not be
7509       // interesting for all targets, especially GPUs.
7510       if (N1.getOpcode() == ISD::FP_EXTEND) {
7511         SDValue N10 = N1.getOperand(0);
7512         if (N10.getOpcode() == PreferredFusedOpcode) {
7513           SDValue N102 = N10.getOperand(2);
7514           if (N102.getOpcode() == ISD::FMUL)
7515             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7516                                         N102.getOperand(0), N102.getOperand(1),
7517                                         N0);
7518         }
7519       }
7520     }
7521   }
7522
7523   return SDValue();
7524 }
7525
7526 /// Try to perform FMA combining on a given FSUB node.
7527 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7528   SDValue N0 = N->getOperand(0);
7529   SDValue N1 = N->getOperand(1);
7530   EVT VT = N->getValueType(0);
7531   SDLoc SL(N);
7532
7533   const TargetOptions &Options = DAG.getTarget().Options;
7534   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7535                        Options.UnsafeFPMath);
7536
7537   // Floating-point multiply-add with intermediate rounding.
7538   bool HasFMAD = (LegalOperations &&
7539                   TLI.isOperationLegal(ISD::FMAD, VT));
7540
7541   // Floating-point multiply-add without intermediate rounding.
7542   bool HasFMA = ((!LegalOperations ||
7543                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7544                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7545                  UnsafeFPMath);
7546
7547   // No valid opcode, do not combine.
7548   if (!HasFMAD && !HasFMA)
7549     return SDValue();
7550
7551   // Always prefer FMAD to FMA for precision.
7552   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7553   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7554   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7555
7556   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7557   if (N0.getOpcode() == ISD::FMUL &&
7558       (Aggressive || N0->hasOneUse())) {
7559     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                        N0.getOperand(0), N0.getOperand(1),
7561                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7562   }
7563
7564   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7565   // Note: Commutes FSUB operands.
7566   if (N1.getOpcode() == ISD::FMUL &&
7567       (Aggressive || N1->hasOneUse()))
7568     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7569                        DAG.getNode(ISD::FNEG, SL, VT,
7570                                    N1.getOperand(0)),
7571                        N1.getOperand(1), N0);
7572
7573   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7574   if (N0.getOpcode() == ISD::FNEG &&
7575       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7576       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7577     SDValue N00 = N0.getOperand(0).getOperand(0);
7578     SDValue N01 = N0.getOperand(0).getOperand(1);
7579     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7580                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7581                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7582   }
7583
7584   // Look through FP_EXTEND nodes to do more combining.
7585   if (UnsafeFPMath && LookThroughFPExt) {
7586     // fold (fsub (fpext (fmul x, y)), z)
7587     //   -> (fma (fpext x), (fpext y), (fneg z))
7588     if (N0.getOpcode() == ISD::FP_EXTEND) {
7589       SDValue N00 = N0.getOperand(0);
7590       if (N00.getOpcode() == ISD::FMUL)
7591         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7593                                        N00.getOperand(0)),
7594                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7595                                        N00.getOperand(1)),
7596                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7597     }
7598
7599     // fold (fsub x, (fpext (fmul y, z)))
7600     //   -> (fma (fneg (fpext y)), (fpext z), x)
7601     // Note: Commutes FSUB operands.
7602     if (N1.getOpcode() == ISD::FP_EXTEND) {
7603       SDValue N10 = N1.getOperand(0);
7604       if (N10.getOpcode() == ISD::FMUL)
7605         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7606                            DAG.getNode(ISD::FNEG, SL, VT,
7607                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7608                                                    N10.getOperand(0))),
7609                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7610                                        N10.getOperand(1)),
7611                            N0);
7612     }
7613
7614     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7615     //   -> (fneg (fma (fpext x), (fpext y), z))
7616     // Note: This could be removed with appropriate canonicalization of the
7617     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7618     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7619     // from implementing the canonicalization in visitFSUB.
7620     if (N0.getOpcode() == ISD::FP_EXTEND) {
7621       SDValue N00 = N0.getOperand(0);
7622       if (N00.getOpcode() == ISD::FNEG) {
7623         SDValue N000 = N00.getOperand(0);
7624         if (N000.getOpcode() == ISD::FMUL) {
7625           return DAG.getNode(ISD::FNEG, SL, VT,
7626                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7627                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7628                                                      N000.getOperand(0)),
7629                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7630                                                      N000.getOperand(1)),
7631                                          N1));
7632         }
7633       }
7634     }
7635
7636     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7637     //   -> (fneg (fma (fpext x)), (fpext y), z)
7638     // Note: This could be removed with appropriate canonicalization of the
7639     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7640     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7641     // from implementing the canonicalization in visitFSUB.
7642     if (N0.getOpcode() == ISD::FNEG) {
7643       SDValue N00 = N0.getOperand(0);
7644       if (N00.getOpcode() == ISD::FP_EXTEND) {
7645         SDValue N000 = N00.getOperand(0);
7646         if (N000.getOpcode() == ISD::FMUL) {
7647           return DAG.getNode(ISD::FNEG, SL, VT,
7648                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7649                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7650                                                      N000.getOperand(0)),
7651                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7652                                                      N000.getOperand(1)),
7653                                          N1));
7654         }
7655       }
7656     }
7657
7658   }
7659
7660   // More folding opportunities when target permits.
7661   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7662     // fold (fsub (fma x, y, (fmul u, v)), z)
7663     //   -> (fma x, y (fma u, v, (fneg z)))
7664     if (N0.getOpcode() == PreferredFusedOpcode &&
7665         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7666       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7667                          N0.getOperand(0), N0.getOperand(1),
7668                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7669                                      N0.getOperand(2).getOperand(0),
7670                                      N0.getOperand(2).getOperand(1),
7671                                      DAG.getNode(ISD::FNEG, SL, VT,
7672                                                  N1)));
7673     }
7674
7675     // fold (fsub x, (fma y, z, (fmul u, v)))
7676     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7677     if (N1.getOpcode() == PreferredFusedOpcode &&
7678         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7679       SDValue N20 = N1.getOperand(2).getOperand(0);
7680       SDValue N21 = N1.getOperand(2).getOperand(1);
7681       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682                          DAG.getNode(ISD::FNEG, SL, VT,
7683                                      N1.getOperand(0)),
7684                          N1.getOperand(1),
7685                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7686                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7687
7688                                      N21, N0));
7689     }
7690
7691     if (UnsafeFPMath && LookThroughFPExt) {
7692       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7693       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7694       if (N0.getOpcode() == PreferredFusedOpcode) {
7695         SDValue N02 = N0.getOperand(2);
7696         if (N02.getOpcode() == ISD::FP_EXTEND) {
7697           SDValue N020 = N02.getOperand(0);
7698           if (N020.getOpcode() == ISD::FMUL)
7699             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7700                                N0.getOperand(0), N0.getOperand(1),
7701                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7702                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7703                                                        N020.getOperand(0)),
7704                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7705                                                        N020.getOperand(1)),
7706                                            DAG.getNode(ISD::FNEG, SL, VT,
7707                                                        N1)));
7708         }
7709       }
7710
7711       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7712       //   -> (fma (fpext x), (fpext y),
7713       //           (fma (fpext u), (fpext v), (fneg z)))
7714       // FIXME: This turns two single-precision and one double-precision
7715       // operation into two double-precision operations, which might not be
7716       // interesting for all targets, especially GPUs.
7717       if (N0.getOpcode() == ISD::FP_EXTEND) {
7718         SDValue N00 = N0.getOperand(0);
7719         if (N00.getOpcode() == PreferredFusedOpcode) {
7720           SDValue N002 = N00.getOperand(2);
7721           if (N002.getOpcode() == ISD::FMUL)
7722             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7723                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7724                                            N00.getOperand(0)),
7725                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                            N00.getOperand(1)),
7727                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7728                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7729                                                        N002.getOperand(0)),
7730                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731                                                        N002.getOperand(1)),
7732                                            DAG.getNode(ISD::FNEG, SL, VT,
7733                                                        N1)));
7734         }
7735       }
7736
7737       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7738       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7739       if (N1.getOpcode() == PreferredFusedOpcode &&
7740         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7741         SDValue N120 = N1.getOperand(2).getOperand(0);
7742         if (N120.getOpcode() == ISD::FMUL) {
7743           SDValue N1200 = N120.getOperand(0);
7744           SDValue N1201 = N120.getOperand(1);
7745           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7747                              N1.getOperand(1),
7748                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7749                                          DAG.getNode(ISD::FNEG, SL, VT,
7750                                              DAG.getNode(ISD::FP_EXTEND, SL,
7751                                                          VT, N1200)),
7752                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7753                                                      N1201),
7754                                          N0));
7755         }
7756       }
7757
7758       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7759       //   -> (fma (fneg (fpext y)), (fpext z),
7760       //           (fma (fneg (fpext u)), (fpext v), x))
7761       // FIXME: This turns two single-precision and one double-precision
7762       // operation into two double-precision operations, which might not be
7763       // interesting for all targets, especially GPUs.
7764       if (N1.getOpcode() == ISD::FP_EXTEND &&
7765         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7766         SDValue N100 = N1.getOperand(0).getOperand(0);
7767         SDValue N101 = N1.getOperand(0).getOperand(1);
7768         SDValue N102 = N1.getOperand(0).getOperand(2);
7769         if (N102.getOpcode() == ISD::FMUL) {
7770           SDValue N1020 = N102.getOperand(0);
7771           SDValue N1021 = N102.getOperand(1);
7772           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7773                              DAG.getNode(ISD::FNEG, SL, VT,
7774                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7775                                                      N100)),
7776                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7777                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7778                                          DAG.getNode(ISD::FNEG, SL, VT,
7779                                              DAG.getNode(ISD::FP_EXTEND, SL,
7780                                                          VT, N1020)),
7781                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782                                                      N1021),
7783                                          N0));
7784         }
7785       }
7786     }
7787   }
7788
7789   return SDValue();
7790 }
7791
7792 SDValue DAGCombiner::visitFADD(SDNode *N) {
7793   SDValue N0 = N->getOperand(0);
7794   SDValue N1 = N->getOperand(1);
7795   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7796   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7797   EVT VT = N->getValueType(0);
7798   SDLoc DL(N);
7799   const TargetOptions &Options = DAG.getTarget().Options;
7800
7801   // fold vector ops
7802   if (VT.isVector())
7803     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7804       return FoldedVOp;
7805
7806   // fold (fadd c1, c2) -> c1 + c2
7807   if (N0CFP && N1CFP)
7808     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7809
7810   // canonicalize constant to RHS
7811   if (N0CFP && !N1CFP)
7812     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7813
7814   // fold (fadd A, (fneg B)) -> (fsub A, B)
7815   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7816       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7817     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7818                        GetNegatedExpression(N1, DAG, LegalOperations));
7819
7820   // fold (fadd (fneg A), B) -> (fsub B, A)
7821   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7822       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7823     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7824                        GetNegatedExpression(N0, DAG, LegalOperations));
7825
7826   // If 'unsafe math' is enabled, fold lots of things.
7827   if (Options.UnsafeFPMath) {
7828     // No FP constant should be created after legalization as Instruction
7829     // Selection pass has a hard time dealing with FP constants.
7830     bool AllowNewConst = (Level < AfterLegalizeDAG);
7831
7832     // fold (fadd A, 0) -> A
7833     if (N1CFP && N1CFP->getValueAPF().isZero())
7834       return N0;
7835
7836     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7837     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7838         isa<ConstantFPSDNode>(N0.getOperand(1)))
7839       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7840                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7841
7842     // If allowed, fold (fadd (fneg x), x) -> 0.0
7843     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7844       return DAG.getConstantFP(0.0, DL, VT);
7845
7846     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7847     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7848       return DAG.getConstantFP(0.0, DL, VT);
7849
7850     // We can fold chains of FADD's of the same value into multiplications.
7851     // This transform is not safe in general because we are reducing the number
7852     // of rounding steps.
7853     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7854       if (N0.getOpcode() == ISD::FMUL) {
7855         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7856         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7857
7858         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7859         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7860           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7861                                        DAG.getConstantFP(1.0, DL, VT));
7862           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7863         }
7864
7865         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7866         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7867             N1.getOperand(0) == N1.getOperand(1) &&
7868             N0.getOperand(0) == N1.getOperand(0)) {
7869           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7870                                        DAG.getConstantFP(2.0, DL, VT));
7871           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7872         }
7873       }
7874
7875       if (N1.getOpcode() == ISD::FMUL) {
7876         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7877         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7878
7879         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7880         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7881           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7882                                        DAG.getConstantFP(1.0, DL, VT));
7883           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7884         }
7885
7886         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7887         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7888             N0.getOperand(0) == N0.getOperand(1) &&
7889             N1.getOperand(0) == N0.getOperand(0)) {
7890           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7891                                        DAG.getConstantFP(2.0, DL, VT));
7892           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7893         }
7894       }
7895
7896       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7897         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7898         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7899         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7900             (N0.getOperand(0) == N1)) {
7901           return DAG.getNode(ISD::FMUL, DL, VT,
7902                              N1, DAG.getConstantFP(3.0, DL, VT));
7903         }
7904       }
7905
7906       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7907         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7908         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7909         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7910             N1.getOperand(0) == N0) {
7911           return DAG.getNode(ISD::FMUL, DL, VT,
7912                              N0, DAG.getConstantFP(3.0, DL, VT));
7913         }
7914       }
7915
7916       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7917       if (AllowNewConst &&
7918           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7919           N0.getOperand(0) == N0.getOperand(1) &&
7920           N1.getOperand(0) == N1.getOperand(1) &&
7921           N0.getOperand(0) == N1.getOperand(0)) {
7922         return DAG.getNode(ISD::FMUL, DL, VT,
7923                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7924       }
7925     }
7926   } // enable-unsafe-fp-math
7927
7928   // FADD -> FMA combines:
7929   SDValue Fused = visitFADDForFMACombine(N);
7930   if (Fused) {
7931     AddToWorklist(Fused.getNode());
7932     return Fused;
7933   }
7934
7935   return SDValue();
7936 }
7937
7938 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7939   SDValue N0 = N->getOperand(0);
7940   SDValue N1 = N->getOperand(1);
7941   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7942   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7943   EVT VT = N->getValueType(0);
7944   SDLoc dl(N);
7945   const TargetOptions &Options = DAG.getTarget().Options;
7946
7947   // fold vector ops
7948   if (VT.isVector())
7949     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7950       return FoldedVOp;
7951
7952   // fold (fsub c1, c2) -> c1-c2
7953   if (N0CFP && N1CFP)
7954     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7955
7956   // fold (fsub A, (fneg B)) -> (fadd A, B)
7957   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7958     return DAG.getNode(ISD::FADD, dl, VT, N0,
7959                        GetNegatedExpression(N1, DAG, LegalOperations));
7960
7961   // If 'unsafe math' is enabled, fold lots of things.
7962   if (Options.UnsafeFPMath) {
7963     // (fsub A, 0) -> A
7964     if (N1CFP && N1CFP->getValueAPF().isZero())
7965       return N0;
7966
7967     // (fsub 0, B) -> -B
7968     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7969       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7970         return GetNegatedExpression(N1, DAG, LegalOperations);
7971       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7972         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7973     }
7974
7975     // (fsub x, x) -> 0.0
7976     if (N0 == N1)
7977       return DAG.getConstantFP(0.0f, dl, VT);
7978
7979     // (fsub x, (fadd x, y)) -> (fneg y)
7980     // (fsub x, (fadd y, x)) -> (fneg y)
7981     if (N1.getOpcode() == ISD::FADD) {
7982       SDValue N10 = N1->getOperand(0);
7983       SDValue N11 = N1->getOperand(1);
7984
7985       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7986         return GetNegatedExpression(N11, DAG, LegalOperations);
7987
7988       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7989         return GetNegatedExpression(N10, DAG, LegalOperations);
7990     }
7991   }
7992
7993   // FSUB -> FMA combines:
7994   SDValue Fused = visitFSUBForFMACombine(N);
7995   if (Fused) {
7996     AddToWorklist(Fused.getNode());
7997     return Fused;
7998   }
7999
8000   return SDValue();
8001 }
8002
8003 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8004   SDValue N0 = N->getOperand(0);
8005   SDValue N1 = N->getOperand(1);
8006   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8007   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8008   EVT VT = N->getValueType(0);
8009   SDLoc DL(N);
8010   const TargetOptions &Options = DAG.getTarget().Options;
8011
8012   // fold vector ops
8013   if (VT.isVector()) {
8014     // This just handles C1 * C2 for vectors. Other vector folds are below.
8015     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8016       return FoldedVOp;
8017   }
8018
8019   // fold (fmul c1, c2) -> c1*c2
8020   if (N0CFP && N1CFP)
8021     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8022
8023   // canonicalize constant to RHS
8024   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8025      !isConstantFPBuildVectorOrConstantFP(N1))
8026     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8027
8028   // fold (fmul A, 1.0) -> A
8029   if (N1CFP && N1CFP->isExactlyValue(1.0))
8030     return N0;
8031
8032   if (Options.UnsafeFPMath) {
8033     // fold (fmul A, 0) -> 0
8034     if (N1CFP && N1CFP->getValueAPF().isZero())
8035       return N1;
8036
8037     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8038     if (N0.getOpcode() == ISD::FMUL) {
8039       // Fold scalars or any vector constants (not just splats).
8040       // This fold is done in general by InstCombine, but extra fmul insts
8041       // may have been generated during lowering.
8042       SDValue N00 = N0.getOperand(0);
8043       SDValue N01 = N0.getOperand(1);
8044       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8045       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8046       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8047       
8048       // Check 1: Make sure that the first operand of the inner multiply is NOT
8049       // a constant. Otherwise, we may induce infinite looping.
8050       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8051         // Check 2: Make sure that the second operand of the inner multiply and
8052         // the second operand of the outer multiply are constants.
8053         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8054             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8055           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8056           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8057         }
8058       }
8059     }
8060
8061     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8062     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8063     // during an early run of DAGCombiner can prevent folding with fmuls
8064     // inserted during lowering.
8065     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8066       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8067       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8068       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8069     }
8070   }
8071
8072   // fold (fmul X, 2.0) -> (fadd X, X)
8073   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8074     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8075
8076   // fold (fmul X, -1.0) -> (fneg X)
8077   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8078     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8079       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8080
8081   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8082   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8083     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8084       // Both can be negated for free, check to see if at least one is cheaper
8085       // negated.
8086       if (LHSNeg == 2 || RHSNeg == 2)
8087         return DAG.getNode(ISD::FMUL, DL, VT,
8088                            GetNegatedExpression(N0, DAG, LegalOperations),
8089                            GetNegatedExpression(N1, DAG, LegalOperations));
8090     }
8091   }
8092
8093   return SDValue();
8094 }
8095
8096 SDValue DAGCombiner::visitFMA(SDNode *N) {
8097   SDValue N0 = N->getOperand(0);
8098   SDValue N1 = N->getOperand(1);
8099   SDValue N2 = N->getOperand(2);
8100   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8101   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8102   EVT VT = N->getValueType(0);
8103   SDLoc dl(N);
8104   const TargetOptions &Options = DAG.getTarget().Options;
8105
8106   // Constant fold FMA.
8107   if (isa<ConstantFPSDNode>(N0) &&
8108       isa<ConstantFPSDNode>(N1) &&
8109       isa<ConstantFPSDNode>(N2)) {
8110     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8111   }
8112
8113   if (Options.UnsafeFPMath) {
8114     if (N0CFP && N0CFP->isZero())
8115       return N2;
8116     if (N1CFP && N1CFP->isZero())
8117       return N2;
8118   }
8119   if (N0CFP && N0CFP->isExactlyValue(1.0))
8120     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8121   if (N1CFP && N1CFP->isExactlyValue(1.0))
8122     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8123
8124   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8125   if (N0CFP && !N1CFP)
8126     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8127
8128   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8129   if (Options.UnsafeFPMath && N1CFP &&
8130       N2.getOpcode() == ISD::FMUL &&
8131       N0 == N2.getOperand(0) &&
8132       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8133     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8134                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8135   }
8136
8137
8138   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8139   if (Options.UnsafeFPMath &&
8140       N0.getOpcode() == ISD::FMUL && N1CFP &&
8141       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8142     return DAG.getNode(ISD::FMA, dl, VT,
8143                        N0.getOperand(0),
8144                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8145                        N2);
8146   }
8147
8148   // (fma x, 1, y) -> (fadd x, y)
8149   // (fma x, -1, y) -> (fadd (fneg x), y)
8150   if (N1CFP) {
8151     if (N1CFP->isExactlyValue(1.0))
8152       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8153
8154     if (N1CFP->isExactlyValue(-1.0) &&
8155         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8156       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8157       AddToWorklist(RHSNeg.getNode());
8158       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8159     }
8160   }
8161
8162   // (fma x, c, x) -> (fmul x, (c+1))
8163   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8164     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8165                        DAG.getNode(ISD::FADD, dl, VT,
8166                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8167
8168   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8169   if (Options.UnsafeFPMath && N1CFP &&
8170       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8171     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8172                        DAG.getNode(ISD::FADD, dl, VT,
8173                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8174
8175
8176   return SDValue();
8177 }
8178
8179 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8180   SDValue N0 = N->getOperand(0);
8181   SDValue N1 = N->getOperand(1);
8182   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8183   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8184   EVT VT = N->getValueType(0);
8185   SDLoc DL(N);
8186   const TargetOptions &Options = DAG.getTarget().Options;
8187
8188   // fold vector ops
8189   if (VT.isVector())
8190     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8191       return FoldedVOp;
8192
8193   // fold (fdiv c1, c2) -> c1/c2
8194   if (N0CFP && N1CFP)
8195     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8196
8197   if (Options.UnsafeFPMath) {
8198     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8199     if (N1CFP) {
8200       // Compute the reciprocal 1.0 / c2.
8201       APFloat N1APF = N1CFP->getValueAPF();
8202       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8203       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8204       // Only do the transform if the reciprocal is a legal fp immediate that
8205       // isn't too nasty (eg NaN, denormal, ...).
8206       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8207           (!LegalOperations ||
8208            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8209            // backend)... we should handle this gracefully after Legalize.
8210            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8211            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8212            TLI.isFPImmLegal(Recip, VT)))
8213         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8214                            DAG.getConstantFP(Recip, DL, VT));
8215     }
8216
8217     // If this FDIV is part of a reciprocal square root, it may be folded
8218     // into a target-specific square root estimate instruction.
8219     if (N1.getOpcode() == ISD::FSQRT) {
8220       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8221         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8222       }
8223     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8224                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8225       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8226         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8227         AddToWorklist(RV.getNode());
8228         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8229       }
8230     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8231                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8232       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8233         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8234         AddToWorklist(RV.getNode());
8235         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8236       }
8237     } else if (N1.getOpcode() == ISD::FMUL) {
8238       // Look through an FMUL. Even though this won't remove the FDIV directly,
8239       // it's still worthwhile to get rid of the FSQRT if possible.
8240       SDValue SqrtOp;
8241       SDValue OtherOp;
8242       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8243         SqrtOp = N1.getOperand(0);
8244         OtherOp = N1.getOperand(1);
8245       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8246         SqrtOp = N1.getOperand(1);
8247         OtherOp = N1.getOperand(0);
8248       }
8249       if (SqrtOp.getNode()) {
8250         // We found a FSQRT, so try to make this fold:
8251         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8252         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8253           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8254           AddToWorklist(RV.getNode());
8255           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8256         }
8257       }
8258     }
8259
8260     // Fold into a reciprocal estimate and multiply instead of a real divide.
8261     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8262       AddToWorklist(RV.getNode());
8263       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8264     }
8265   }
8266
8267   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8268   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8269     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8270       // Both can be negated for free, check to see if at least one is cheaper
8271       // negated.
8272       if (LHSNeg == 2 || RHSNeg == 2)
8273         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8274                            GetNegatedExpression(N0, DAG, LegalOperations),
8275                            GetNegatedExpression(N1, DAG, LegalOperations));
8276     }
8277   }
8278
8279   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8280   // reciprocal.
8281   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8282   // Notice that this is not always beneficial. One reason is different target
8283   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8284   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8285   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8286   if (Options.UnsafeFPMath) {
8287     // Skip if current node is a reciprocal.
8288     if (N0CFP && N0CFP->isExactlyValue(1.0))
8289       return SDValue();
8290
8291     SmallVector<SDNode *, 4> Users;
8292     // Find all FDIV users of the same divisor.
8293     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8294                               UE = N1.getNode()->use_end();
8295          UI != UE; ++UI) {
8296       SDNode *User = UI.getUse().getUser();
8297       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8298         Users.push_back(User);
8299     }
8300
8301     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8302       SDLoc DL(N);
8303       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8304       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8305
8306       // Dividend / Divisor -> Dividend * Reciprocal
8307       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8308         if ((*I)->getOperand(0) != FPOne) {
8309           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8310                                         (*I)->getOperand(0), Reciprocal);
8311           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8312         }
8313       }
8314       return SDValue();
8315     }
8316   }
8317
8318   return SDValue();
8319 }
8320
8321 SDValue DAGCombiner::visitFREM(SDNode *N) {
8322   SDValue N0 = N->getOperand(0);
8323   SDValue N1 = N->getOperand(1);
8324   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8325   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8326   EVT VT = N->getValueType(0);
8327
8328   // fold (frem c1, c2) -> fmod(c1,c2)
8329   if (N0CFP && N1CFP)
8330     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8331
8332   return SDValue();
8333 }
8334
8335 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8336   if (DAG.getTarget().Options.UnsafeFPMath &&
8337       !TLI.isFsqrtCheap()) {
8338     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8339     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8340       EVT VT = RV.getValueType();
8341       SDLoc DL(N);
8342       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8343       AddToWorklist(RV.getNode());
8344
8345       // Unfortunately, RV is now NaN if the input was exactly 0.
8346       // Select out this case and force the answer to 0.
8347       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8348       SDValue ZeroCmp =
8349         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8350                      N->getOperand(0), Zero, ISD::SETEQ);
8351       AddToWorklist(ZeroCmp.getNode());
8352       AddToWorklist(RV.getNode());
8353
8354       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8355                        DL, VT, ZeroCmp, Zero, RV);
8356       return RV;
8357     }
8358   }
8359   return SDValue();
8360 }
8361
8362 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8363   SDValue N0 = N->getOperand(0);
8364   SDValue N1 = N->getOperand(1);
8365   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8366   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8367   EVT VT = N->getValueType(0);
8368
8369   if (N0CFP && N1CFP)  // Constant fold
8370     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8371
8372   if (N1CFP) {
8373     const APFloat& V = N1CFP->getValueAPF();
8374     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8375     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8376     if (!V.isNegative()) {
8377       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8378         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8379     } else {
8380       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8381         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8382                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8383     }
8384   }
8385
8386   // copysign(fabs(x), y) -> copysign(x, y)
8387   // copysign(fneg(x), y) -> copysign(x, y)
8388   // copysign(copysign(x,z), y) -> copysign(x, y)
8389   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8390       N0.getOpcode() == ISD::FCOPYSIGN)
8391     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8392                        N0.getOperand(0), N1);
8393
8394   // copysign(x, abs(y)) -> abs(x)
8395   if (N1.getOpcode() == ISD::FABS)
8396     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8397
8398   // copysign(x, copysign(y,z)) -> copysign(x, z)
8399   if (N1.getOpcode() == ISD::FCOPYSIGN)
8400     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8401                        N0, N1.getOperand(1));
8402
8403   // copysign(x, fp_extend(y)) -> copysign(x, y)
8404   // copysign(x, fp_round(y)) -> copysign(x, y)
8405   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8406     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8407                        N0, N1.getOperand(0));
8408
8409   return SDValue();
8410 }
8411
8412 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8413   SDValue N0 = N->getOperand(0);
8414   EVT VT = N->getValueType(0);
8415   EVT OpVT = N0.getValueType();
8416
8417   // fold (sint_to_fp c1) -> c1fp
8418   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8419       // ...but only if the target supports immediate floating-point values
8420       (!LegalOperations ||
8421        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8422     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8423
8424   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8425   // but UINT_TO_FP is legal on this target, try to convert.
8426   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8427       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8428     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8429     if (DAG.SignBitIsZero(N0))
8430       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8431   }
8432
8433   // The next optimizations are desirable only if SELECT_CC can be lowered.
8434   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8435     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8436     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8437         !VT.isVector() &&
8438         (!LegalOperations ||
8439          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8440       SDLoc DL(N);
8441       SDValue Ops[] =
8442         { N0.getOperand(0), N0.getOperand(1),
8443           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8444           N0.getOperand(2) };
8445       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8446     }
8447
8448     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8449     //      (select_cc x, y, 1.0, 0.0,, cc)
8450     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8451         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8452         (!LegalOperations ||
8453          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8454       SDLoc DL(N);
8455       SDValue Ops[] =
8456         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8457           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8458           N0.getOperand(0).getOperand(2) };
8459       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8460     }
8461   }
8462
8463   return SDValue();
8464 }
8465
8466 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8467   SDValue N0 = N->getOperand(0);
8468   EVT VT = N->getValueType(0);
8469   EVT OpVT = N0.getValueType();
8470
8471   // fold (uint_to_fp c1) -> c1fp
8472   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8473       // ...but only if the target supports immediate floating-point values
8474       (!LegalOperations ||
8475        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8476     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8477
8478   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8479   // but SINT_TO_FP is legal on this target, try to convert.
8480   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8481       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8482     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8483     if (DAG.SignBitIsZero(N0))
8484       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8485   }
8486
8487   // The next optimizations are desirable only if SELECT_CC can be lowered.
8488   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8489     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8490
8491     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8492         (!LegalOperations ||
8493          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8494       SDLoc DL(N);
8495       SDValue Ops[] =
8496         { N0.getOperand(0), N0.getOperand(1),
8497           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8498           N0.getOperand(2) };
8499       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8500     }
8501   }
8502
8503   return SDValue();
8504 }
8505
8506 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8507 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8508   SDValue N0 = N->getOperand(0);
8509   EVT VT = N->getValueType(0);
8510
8511   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8512     return SDValue();
8513
8514   SDValue Src = N0.getOperand(0);
8515   EVT SrcVT = Src.getValueType();
8516   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8517   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8518
8519   // We can safely assume the conversion won't overflow the output range,
8520   // because (for example) (uint8_t)18293.f is undefined behavior.
8521
8522   // Since we can assume the conversion won't overflow, our decision as to
8523   // whether the input will fit in the float should depend on the minimum
8524   // of the input range and output range.
8525
8526   // This means this is also safe for a signed input and unsigned output, since
8527   // a negative input would lead to undefined behavior.
8528   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8529   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8530   unsigned ActualSize = std::min(InputSize, OutputSize);
8531   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8532
8533   // We can only fold away the float conversion if the input range can be
8534   // represented exactly in the float range.
8535   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8536     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8537       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8538                                                        : ISD::ZERO_EXTEND;
8539       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8540     }
8541     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8542       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8543     if (SrcVT == VT)
8544       return Src;
8545     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8546   }
8547   return SDValue();
8548 }
8549
8550 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8551   SDValue N0 = N->getOperand(0);
8552   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8553   EVT VT = N->getValueType(0);
8554
8555   // fold (fp_to_sint c1fp) -> c1
8556   if (N0CFP)
8557     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8558
8559   return FoldIntToFPToInt(N, DAG);
8560 }
8561
8562 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8563   SDValue N0 = N->getOperand(0);
8564   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8565   EVT VT = N->getValueType(0);
8566
8567   // fold (fp_to_uint c1fp) -> c1
8568   if (N0CFP)
8569     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8570
8571   return FoldIntToFPToInt(N, DAG);
8572 }
8573
8574 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8575   SDValue N0 = N->getOperand(0);
8576   SDValue N1 = N->getOperand(1);
8577   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8578   EVT VT = N->getValueType(0);
8579
8580   // fold (fp_round c1fp) -> c1fp
8581   if (N0CFP)
8582     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8583
8584   // fold (fp_round (fp_extend x)) -> x
8585   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8586     return N0.getOperand(0);
8587
8588   // fold (fp_round (fp_round x)) -> (fp_round x)
8589   if (N0.getOpcode() == ISD::FP_ROUND) {
8590     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8591     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8592     // If the first fp_round isn't a value preserving truncation, it might
8593     // introduce a tie in the second fp_round, that wouldn't occur in the
8594     // single-step fp_round we want to fold to.
8595     // In other words, double rounding isn't the same as rounding.
8596     // Also, this is a value preserving truncation iff both fp_round's are.
8597     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8598       SDLoc DL(N);
8599       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8600                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8601     }
8602   }
8603
8604   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8605   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8606     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8607                               N0.getOperand(0), N1);
8608     AddToWorklist(Tmp.getNode());
8609     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8610                        Tmp, N0.getOperand(1));
8611   }
8612
8613   return SDValue();
8614 }
8615
8616 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8617   SDValue N0 = N->getOperand(0);
8618   EVT VT = N->getValueType(0);
8619   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8620   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8621
8622   // fold (fp_round_inreg c1fp) -> c1fp
8623   if (N0CFP && isTypeLegal(EVT)) {
8624     SDLoc DL(N);
8625     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8626     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8627   }
8628
8629   return SDValue();
8630 }
8631
8632 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8633   SDValue N0 = N->getOperand(0);
8634   EVT VT = N->getValueType(0);
8635
8636   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8637   if (N->hasOneUse() &&
8638       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8639     return SDValue();
8640
8641   // fold (fp_extend c1fp) -> c1fp
8642   if (isConstantFPBuildVectorOrConstantFP(N0))
8643     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8644
8645   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8646   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8647       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8648     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8649
8650   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8651   // value of X.
8652   if (N0.getOpcode() == ISD::FP_ROUND
8653       && N0.getNode()->getConstantOperandVal(1) == 1) {
8654     SDValue In = N0.getOperand(0);
8655     if (In.getValueType() == VT) return In;
8656     if (VT.bitsLT(In.getValueType()))
8657       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8658                          In, N0.getOperand(1));
8659     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8660   }
8661
8662   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8663   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8664        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8665     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8666     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8667                                      LN0->getChain(),
8668                                      LN0->getBasePtr(), N0.getValueType(),
8669                                      LN0->getMemOperand());
8670     CombineTo(N, ExtLoad);
8671     CombineTo(N0.getNode(),
8672               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8673                           N0.getValueType(), ExtLoad,
8674                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8675               ExtLoad.getValue(1));
8676     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8677   }
8678
8679   return SDValue();
8680 }
8681
8682 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8683   SDValue N0 = N->getOperand(0);
8684   EVT VT = N->getValueType(0);
8685
8686   // fold (fceil c1) -> fceil(c1)
8687   if (isConstantFPBuildVectorOrConstantFP(N0))
8688     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8689
8690   return SDValue();
8691 }
8692
8693 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8694   SDValue N0 = N->getOperand(0);
8695   EVT VT = N->getValueType(0);
8696
8697   // fold (ftrunc c1) -> ftrunc(c1)
8698   if (isConstantFPBuildVectorOrConstantFP(N0))
8699     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8700
8701   return SDValue();
8702 }
8703
8704 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8705   SDValue N0 = N->getOperand(0);
8706   EVT VT = N->getValueType(0);
8707
8708   // fold (ffloor c1) -> ffloor(c1)
8709   if (isConstantFPBuildVectorOrConstantFP(N0))
8710     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8711
8712   return SDValue();
8713 }
8714
8715 // FIXME: FNEG and FABS have a lot in common; refactor.
8716 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8717   SDValue N0 = N->getOperand(0);
8718   EVT VT = N->getValueType(0);
8719
8720   // Constant fold FNEG.
8721   if (isConstantFPBuildVectorOrConstantFP(N0))
8722     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8723
8724   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8725                          &DAG.getTarget().Options))
8726     return GetNegatedExpression(N0, DAG, LegalOperations);
8727
8728   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8729   // constant pool values.
8730   if (!TLI.isFNegFree(VT) &&
8731       N0.getOpcode() == ISD::BITCAST &&
8732       N0.getNode()->hasOneUse()) {
8733     SDValue Int = N0.getOperand(0);
8734     EVT IntVT = Int.getValueType();
8735     if (IntVT.isInteger() && !IntVT.isVector()) {
8736       APInt SignMask;
8737       if (N0.getValueType().isVector()) {
8738         // For a vector, get a mask such as 0x80... per scalar element
8739         // and splat it.
8740         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8741         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8742       } else {
8743         // For a scalar, just generate 0x80...
8744         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8745       }
8746       SDLoc DL0(N0);
8747       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8748                         DAG.getConstant(SignMask, DL0, IntVT));
8749       AddToWorklist(Int.getNode());
8750       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8751     }
8752   }
8753
8754   // (fneg (fmul c, x)) -> (fmul -c, x)
8755   if (N0.getOpcode() == ISD::FMUL) {
8756     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8757     if (CFP1) {
8758       APFloat CVal = CFP1->getValueAPF();
8759       CVal.changeSign();
8760       if (Level >= AfterLegalizeDAG &&
8761           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8762            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8763         return DAG.getNode(
8764             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8765             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8766     }
8767   }
8768
8769   return SDValue();
8770 }
8771
8772 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8773   SDValue N0 = N->getOperand(0);
8774   SDValue N1 = N->getOperand(1);
8775   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8776   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8777
8778   if (N0CFP && N1CFP) {
8779     const APFloat &C0 = N0CFP->getValueAPF();
8780     const APFloat &C1 = N1CFP->getValueAPF();
8781     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8782   }
8783
8784   if (N0CFP) {
8785     EVT VT = N->getValueType(0);
8786     // Canonicalize to constant on RHS.
8787     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8788   }
8789
8790   return SDValue();
8791 }
8792
8793 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8794   SDValue N0 = N->getOperand(0);
8795   SDValue N1 = N->getOperand(1);
8796   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8797   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8798
8799   if (N0CFP && N1CFP) {
8800     const APFloat &C0 = N0CFP->getValueAPF();
8801     const APFloat &C1 = N1CFP->getValueAPF();
8802     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8803   }
8804
8805   if (N0CFP) {
8806     EVT VT = N->getValueType(0);
8807     // Canonicalize to constant on RHS.
8808     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8809   }
8810
8811   return SDValue();
8812 }
8813
8814 SDValue DAGCombiner::visitFABS(SDNode *N) {
8815   SDValue N0 = N->getOperand(0);
8816   EVT VT = N->getValueType(0);
8817
8818   // fold (fabs c1) -> fabs(c1)
8819   if (isConstantFPBuildVectorOrConstantFP(N0))
8820     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8821
8822   // fold (fabs (fabs x)) -> (fabs x)
8823   if (N0.getOpcode() == ISD::FABS)
8824     return N->getOperand(0);
8825
8826   // fold (fabs (fneg x)) -> (fabs x)
8827   // fold (fabs (fcopysign x, y)) -> (fabs x)
8828   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8829     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8830
8831   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8832   // constant pool values.
8833   if (!TLI.isFAbsFree(VT) &&
8834       N0.getOpcode() == ISD::BITCAST &&
8835       N0.getNode()->hasOneUse()) {
8836     SDValue Int = N0.getOperand(0);
8837     EVT IntVT = Int.getValueType();
8838     if (IntVT.isInteger() && !IntVT.isVector()) {
8839       APInt SignMask;
8840       if (N0.getValueType().isVector()) {
8841         // For a vector, get a mask such as 0x7f... per scalar element
8842         // and splat it.
8843         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8844         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8845       } else {
8846         // For a scalar, just generate 0x7f...
8847         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8848       }
8849       SDLoc DL(N0);
8850       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8851                         DAG.getConstant(SignMask, DL, IntVT));
8852       AddToWorklist(Int.getNode());
8853       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8854     }
8855   }
8856
8857   return SDValue();
8858 }
8859
8860 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8861   SDValue Chain = N->getOperand(0);
8862   SDValue N1 = N->getOperand(1);
8863   SDValue N2 = N->getOperand(2);
8864
8865   // If N is a constant we could fold this into a fallthrough or unconditional
8866   // branch. However that doesn't happen very often in normal code, because
8867   // Instcombine/SimplifyCFG should have handled the available opportunities.
8868   // If we did this folding here, it would be necessary to update the
8869   // MachineBasicBlock CFG, which is awkward.
8870
8871   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8872   // on the target.
8873   if (N1.getOpcode() == ISD::SETCC &&
8874       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8875                                    N1.getOperand(0).getValueType())) {
8876     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8877                        Chain, N1.getOperand(2),
8878                        N1.getOperand(0), N1.getOperand(1), N2);
8879   }
8880
8881   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8882       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8883        (N1.getOperand(0).hasOneUse() &&
8884         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8885     SDNode *Trunc = nullptr;
8886     if (N1.getOpcode() == ISD::TRUNCATE) {
8887       // Look pass the truncate.
8888       Trunc = N1.getNode();
8889       N1 = N1.getOperand(0);
8890     }
8891
8892     // Match this pattern so that we can generate simpler code:
8893     //
8894     //   %a = ...
8895     //   %b = and i32 %a, 2
8896     //   %c = srl i32 %b, 1
8897     //   brcond i32 %c ...
8898     //
8899     // into
8900     //
8901     //   %a = ...
8902     //   %b = and i32 %a, 2
8903     //   %c = setcc eq %b, 0
8904     //   brcond %c ...
8905     //
8906     // This applies only when the AND constant value has one bit set and the
8907     // SRL constant is equal to the log2 of the AND constant. The back-end is
8908     // smart enough to convert the result into a TEST/JMP sequence.
8909     SDValue Op0 = N1.getOperand(0);
8910     SDValue Op1 = N1.getOperand(1);
8911
8912     if (Op0.getOpcode() == ISD::AND &&
8913         Op1.getOpcode() == ISD::Constant) {
8914       SDValue AndOp1 = Op0.getOperand(1);
8915
8916       if (AndOp1.getOpcode() == ISD::Constant) {
8917         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8918
8919         if (AndConst.isPowerOf2() &&
8920             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8921           SDLoc DL(N);
8922           SDValue SetCC =
8923             DAG.getSetCC(DL,
8924                          getSetCCResultType(Op0.getValueType()),
8925                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8926                          ISD::SETNE);
8927
8928           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8929                                           MVT::Other, Chain, SetCC, N2);
8930           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8931           // will convert it back to (X & C1) >> C2.
8932           CombineTo(N, NewBRCond, false);
8933           // Truncate is dead.
8934           if (Trunc)
8935             deleteAndRecombine(Trunc);
8936           // Replace the uses of SRL with SETCC
8937           WorklistRemover DeadNodes(*this);
8938           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8939           deleteAndRecombine(N1.getNode());
8940           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8941         }
8942       }
8943     }
8944
8945     if (Trunc)
8946       // Restore N1 if the above transformation doesn't match.
8947       N1 = N->getOperand(1);
8948   }
8949
8950   // Transform br(xor(x, y)) -> br(x != y)
8951   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8952   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8953     SDNode *TheXor = N1.getNode();
8954     SDValue Op0 = TheXor->getOperand(0);
8955     SDValue Op1 = TheXor->getOperand(1);
8956     if (Op0.getOpcode() == Op1.getOpcode()) {
8957       // Avoid missing important xor optimizations.
8958       SDValue Tmp = visitXOR(TheXor);
8959       if (Tmp.getNode()) {
8960         if (Tmp.getNode() != TheXor) {
8961           DEBUG(dbgs() << "\nReplacing.8 ";
8962                 TheXor->dump(&DAG);
8963                 dbgs() << "\nWith: ";
8964                 Tmp.getNode()->dump(&DAG);
8965                 dbgs() << '\n');
8966           WorklistRemover DeadNodes(*this);
8967           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8968           deleteAndRecombine(TheXor);
8969           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8970                              MVT::Other, Chain, Tmp, N2);
8971         }
8972
8973         // visitXOR has changed XOR's operands or replaced the XOR completely,
8974         // bail out.
8975         return SDValue(N, 0);
8976       }
8977     }
8978
8979     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8980       bool Equal = false;
8981       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8982         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8983             Op0.getOpcode() == ISD::XOR) {
8984           TheXor = Op0.getNode();
8985           Equal = true;
8986         }
8987
8988       EVT SetCCVT = N1.getValueType();
8989       if (LegalTypes)
8990         SetCCVT = getSetCCResultType(SetCCVT);
8991       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8992                                    SetCCVT,
8993                                    Op0, Op1,
8994                                    Equal ? ISD::SETEQ : ISD::SETNE);
8995       // Replace the uses of XOR with SETCC
8996       WorklistRemover DeadNodes(*this);
8997       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8998       deleteAndRecombine(N1.getNode());
8999       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9000                          MVT::Other, Chain, SetCC, N2);
9001     }
9002   }
9003
9004   return SDValue();
9005 }
9006
9007 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9008 //
9009 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9010   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9011   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9012
9013   // If N is a constant we could fold this into a fallthrough or unconditional
9014   // branch. However that doesn't happen very often in normal code, because
9015   // Instcombine/SimplifyCFG should have handled the available opportunities.
9016   // If we did this folding here, it would be necessary to update the
9017   // MachineBasicBlock CFG, which is awkward.
9018
9019   // Use SimplifySetCC to simplify SETCC's.
9020   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9021                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9022                                false);
9023   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9024
9025   // fold to a simpler setcc
9026   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9027     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9028                        N->getOperand(0), Simp.getOperand(2),
9029                        Simp.getOperand(0), Simp.getOperand(1),
9030                        N->getOperand(4));
9031
9032   return SDValue();
9033 }
9034
9035 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9036 /// and that N may be folded in the load / store addressing mode.
9037 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9038                                     SelectionDAG &DAG,
9039                                     const TargetLowering &TLI) {
9040   EVT VT;
9041   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9042     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9043       return false;
9044     VT = LD->getMemoryVT();
9045   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9046     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9047       return false;
9048     VT = ST->getMemoryVT();
9049   } else
9050     return false;
9051
9052   TargetLowering::AddrMode AM;
9053   if (N->getOpcode() == ISD::ADD) {
9054     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9055     if (Offset)
9056       // [reg +/- imm]
9057       AM.BaseOffs = Offset->getSExtValue();
9058     else
9059       // [reg +/- reg]
9060       AM.Scale = 1;
9061   } else if (N->getOpcode() == ISD::SUB) {
9062     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9063     if (Offset)
9064       // [reg +/- imm]
9065       AM.BaseOffs = -Offset->getSExtValue();
9066     else
9067       // [reg +/- reg]
9068       AM.Scale = 1;
9069   } else
9070     return false;
9071
9072   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9073 }
9074
9075 /// Try turning a load/store into a pre-indexed load/store when the base
9076 /// pointer is an add or subtract and it has other uses besides the load/store.
9077 /// After the transformation, the new indexed load/store has effectively folded
9078 /// the add/subtract in and all of its other uses are redirected to the
9079 /// new load/store.
9080 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9081   if (Level < AfterLegalizeDAG)
9082     return false;
9083
9084   bool isLoad = true;
9085   SDValue Ptr;
9086   EVT VT;
9087   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9088     if (LD->isIndexed())
9089       return false;
9090     VT = LD->getMemoryVT();
9091     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9092         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9093       return false;
9094     Ptr = LD->getBasePtr();
9095   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9096     if (ST->isIndexed())
9097       return false;
9098     VT = ST->getMemoryVT();
9099     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9100         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9101       return false;
9102     Ptr = ST->getBasePtr();
9103     isLoad = false;
9104   } else {
9105     return false;
9106   }
9107
9108   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9109   // out.  There is no reason to make this a preinc/predec.
9110   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9111       Ptr.getNode()->hasOneUse())
9112     return false;
9113
9114   // Ask the target to do addressing mode selection.
9115   SDValue BasePtr;
9116   SDValue Offset;
9117   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9118   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9119     return false;
9120
9121   // Backends without true r+i pre-indexed forms may need to pass a
9122   // constant base with a variable offset so that constant coercion
9123   // will work with the patterns in canonical form.
9124   bool Swapped = false;
9125   if (isa<ConstantSDNode>(BasePtr)) {
9126     std::swap(BasePtr, Offset);
9127     Swapped = true;
9128   }
9129
9130   // Don't create a indexed load / store with zero offset.
9131   if (isa<ConstantSDNode>(Offset) &&
9132       cast<ConstantSDNode>(Offset)->isNullValue())
9133     return false;
9134
9135   // Try turning it into a pre-indexed load / store except when:
9136   // 1) The new base ptr is a frame index.
9137   // 2) If N is a store and the new base ptr is either the same as or is a
9138   //    predecessor of the value being stored.
9139   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9140   //    that would create a cycle.
9141   // 4) All uses are load / store ops that use it as old base ptr.
9142
9143   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9144   // (plus the implicit offset) to a register to preinc anyway.
9145   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9146     return false;
9147
9148   // Check #2.
9149   if (!isLoad) {
9150     SDValue Val = cast<StoreSDNode>(N)->getValue();
9151     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9152       return false;
9153   }
9154
9155   // If the offset is a constant, there may be other adds of constants that
9156   // can be folded with this one. We should do this to avoid having to keep
9157   // a copy of the original base pointer.
9158   SmallVector<SDNode *, 16> OtherUses;
9159   if (isa<ConstantSDNode>(Offset))
9160     for (SDNode *Use : BasePtr.getNode()->uses()) {
9161       if (Use == Ptr.getNode())
9162         continue;
9163
9164       if (Use->isPredecessorOf(N))
9165         continue;
9166
9167       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9168         OtherUses.clear();
9169         break;
9170       }
9171
9172       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9173       if (Op1.getNode() == BasePtr.getNode())
9174         std::swap(Op0, Op1);
9175       assert(Op0.getNode() == BasePtr.getNode() &&
9176              "Use of ADD/SUB but not an operand");
9177
9178       if (!isa<ConstantSDNode>(Op1)) {
9179         OtherUses.clear();
9180         break;
9181       }
9182
9183       // FIXME: In some cases, we can be smarter about this.
9184       if (Op1.getValueType() != Offset.getValueType()) {
9185         OtherUses.clear();
9186         break;
9187       }
9188
9189       OtherUses.push_back(Use);
9190     }
9191
9192   if (Swapped)
9193     std::swap(BasePtr, Offset);
9194
9195   // Now check for #3 and #4.
9196   bool RealUse = false;
9197
9198   // Caches for hasPredecessorHelper
9199   SmallPtrSet<const SDNode *, 32> Visited;
9200   SmallVector<const SDNode *, 16> Worklist;
9201
9202   for (SDNode *Use : Ptr.getNode()->uses()) {
9203     if (Use == N)
9204       continue;
9205     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9206       return false;
9207
9208     // If Ptr may be folded in addressing mode of other use, then it's
9209     // not profitable to do this transformation.
9210     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9211       RealUse = true;
9212   }
9213
9214   if (!RealUse)
9215     return false;
9216
9217   SDValue Result;
9218   if (isLoad)
9219     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9220                                 BasePtr, Offset, AM);
9221   else
9222     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9223                                  BasePtr, Offset, AM);
9224   ++PreIndexedNodes;
9225   ++NodesCombined;
9226   DEBUG(dbgs() << "\nReplacing.4 ";
9227         N->dump(&DAG);
9228         dbgs() << "\nWith: ";
9229         Result.getNode()->dump(&DAG);
9230         dbgs() << '\n');
9231   WorklistRemover DeadNodes(*this);
9232   if (isLoad) {
9233     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9234     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9235   } else {
9236     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9237   }
9238
9239   // Finally, since the node is now dead, remove it from the graph.
9240   deleteAndRecombine(N);
9241
9242   if (Swapped)
9243     std::swap(BasePtr, Offset);
9244
9245   // Replace other uses of BasePtr that can be updated to use Ptr
9246   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9247     unsigned OffsetIdx = 1;
9248     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9249       OffsetIdx = 0;
9250     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9251            BasePtr.getNode() && "Expected BasePtr operand");
9252
9253     // We need to replace ptr0 in the following expression:
9254     //   x0 * offset0 + y0 * ptr0 = t0
9255     // knowing that
9256     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9257     //
9258     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9259     // indexed load/store and the expresion that needs to be re-written.
9260     //
9261     // Therefore, we have:
9262     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9263
9264     ConstantSDNode *CN =
9265       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9266     int X0, X1, Y0, Y1;
9267     APInt Offset0 = CN->getAPIntValue();
9268     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9269
9270     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9271     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9272     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9273     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9274
9275     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9276
9277     APInt CNV = Offset0;
9278     if (X0 < 0) CNV = -CNV;
9279     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9280     else CNV = CNV - Offset1;
9281
9282     SDLoc DL(OtherUses[i]);
9283
9284     // We can now generate the new expression.
9285     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9286     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9287
9288     SDValue NewUse = DAG.getNode(Opcode,
9289                                  DL,
9290                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9291     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9292     deleteAndRecombine(OtherUses[i]);
9293   }
9294
9295   // Replace the uses of Ptr with uses of the updated base value.
9296   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9297   deleteAndRecombine(Ptr.getNode());
9298
9299   return true;
9300 }
9301
9302 /// Try to combine a load/store with a add/sub of the base pointer node into a
9303 /// post-indexed load/store. The transformation folded the add/subtract into the
9304 /// new indexed load/store effectively and all of its uses are redirected to the
9305 /// new load/store.
9306 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9307   if (Level < AfterLegalizeDAG)
9308     return false;
9309
9310   bool isLoad = true;
9311   SDValue Ptr;
9312   EVT VT;
9313   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9314     if (LD->isIndexed())
9315       return false;
9316     VT = LD->getMemoryVT();
9317     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9318         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9319       return false;
9320     Ptr = LD->getBasePtr();
9321   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9322     if (ST->isIndexed())
9323       return false;
9324     VT = ST->getMemoryVT();
9325     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9326         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9327       return false;
9328     Ptr = ST->getBasePtr();
9329     isLoad = false;
9330   } else {
9331     return false;
9332   }
9333
9334   if (Ptr.getNode()->hasOneUse())
9335     return false;
9336
9337   for (SDNode *Op : Ptr.getNode()->uses()) {
9338     if (Op == N ||
9339         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9340       continue;
9341
9342     SDValue BasePtr;
9343     SDValue Offset;
9344     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9345     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9346       // Don't create a indexed load / store with zero offset.
9347       if (isa<ConstantSDNode>(Offset) &&
9348           cast<ConstantSDNode>(Offset)->isNullValue())
9349         continue;
9350
9351       // Try turning it into a post-indexed load / store except when
9352       // 1) All uses are load / store ops that use it as base ptr (and
9353       //    it may be folded as addressing mmode).
9354       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9355       //    nor a successor of N. Otherwise, if Op is folded that would
9356       //    create a cycle.
9357
9358       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9359         continue;
9360
9361       // Check for #1.
9362       bool TryNext = false;
9363       for (SDNode *Use : BasePtr.getNode()->uses()) {
9364         if (Use == Ptr.getNode())
9365           continue;
9366
9367         // If all the uses are load / store addresses, then don't do the
9368         // transformation.
9369         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9370           bool RealUse = false;
9371           for (SDNode *UseUse : Use->uses()) {
9372             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9373               RealUse = true;
9374           }
9375
9376           if (!RealUse) {
9377             TryNext = true;
9378             break;
9379           }
9380         }
9381       }
9382
9383       if (TryNext)
9384         continue;
9385
9386       // Check for #2
9387       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9388         SDValue Result = isLoad
9389           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9390                                BasePtr, Offset, AM)
9391           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9392                                 BasePtr, Offset, AM);
9393         ++PostIndexedNodes;
9394         ++NodesCombined;
9395         DEBUG(dbgs() << "\nReplacing.5 ";
9396               N->dump(&DAG);
9397               dbgs() << "\nWith: ";
9398               Result.getNode()->dump(&DAG);
9399               dbgs() << '\n');
9400         WorklistRemover DeadNodes(*this);
9401         if (isLoad) {
9402           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9403           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9404         } else {
9405           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9406         }
9407
9408         // Finally, since the node is now dead, remove it from the graph.
9409         deleteAndRecombine(N);
9410
9411         // Replace the uses of Use with uses of the updated base value.
9412         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9413                                       Result.getValue(isLoad ? 1 : 0));
9414         deleteAndRecombine(Op);
9415         return true;
9416       }
9417     }
9418   }
9419
9420   return false;
9421 }
9422
9423 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9424 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9425   ISD::MemIndexedMode AM = LD->getAddressingMode();
9426   assert(AM != ISD::UNINDEXED);
9427   SDValue BP = LD->getOperand(1);
9428   SDValue Inc = LD->getOperand(2);
9429
9430   // Some backends use TargetConstants for load offsets, but don't expect
9431   // TargetConstants in general ADD nodes. We can convert these constants into
9432   // regular Constants (if the constant is not opaque).
9433   assert((Inc.getOpcode() != ISD::TargetConstant ||
9434           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9435          "Cannot split out indexing using opaque target constants");
9436   if (Inc.getOpcode() == ISD::TargetConstant) {
9437     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9438     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9439                           ConstInc->getValueType(0));
9440   }
9441
9442   unsigned Opc =
9443       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9444   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9445 }
9446
9447 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9448   LoadSDNode *LD  = cast<LoadSDNode>(N);
9449   SDValue Chain = LD->getChain();
9450   SDValue Ptr   = LD->getBasePtr();
9451
9452   // If load is not volatile and there are no uses of the loaded value (and
9453   // the updated indexed value in case of indexed loads), change uses of the
9454   // chain value into uses of the chain input (i.e. delete the dead load).
9455   if (!LD->isVolatile()) {
9456     if (N->getValueType(1) == MVT::Other) {
9457       // Unindexed loads.
9458       if (!N->hasAnyUseOfValue(0)) {
9459         // It's not safe to use the two value CombineTo variant here. e.g.
9460         // v1, chain2 = load chain1, loc
9461         // v2, chain3 = load chain2, loc
9462         // v3         = add v2, c
9463         // Now we replace use of chain2 with chain1.  This makes the second load
9464         // isomorphic to the one we are deleting, and thus makes this load live.
9465         DEBUG(dbgs() << "\nReplacing.6 ";
9466               N->dump(&DAG);
9467               dbgs() << "\nWith chain: ";
9468               Chain.getNode()->dump(&DAG);
9469               dbgs() << "\n");
9470         WorklistRemover DeadNodes(*this);
9471         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9472
9473         if (N->use_empty())
9474           deleteAndRecombine(N);
9475
9476         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9477       }
9478     } else {
9479       // Indexed loads.
9480       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9481
9482       // If this load has an opaque TargetConstant offset, then we cannot split
9483       // the indexing into an add/sub directly (that TargetConstant may not be
9484       // valid for a different type of node, and we cannot convert an opaque
9485       // target constant into a regular constant).
9486       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9487                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9488
9489       if (!N->hasAnyUseOfValue(0) &&
9490           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9491         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9492         SDValue Index;
9493         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9494           Index = SplitIndexingFromLoad(LD);
9495           // Try to fold the base pointer arithmetic into subsequent loads and
9496           // stores.
9497           AddUsersToWorklist(N);
9498         } else
9499           Index = DAG.getUNDEF(N->getValueType(1));
9500         DEBUG(dbgs() << "\nReplacing.7 ";
9501               N->dump(&DAG);
9502               dbgs() << "\nWith: ";
9503               Undef.getNode()->dump(&DAG);
9504               dbgs() << " and 2 other values\n");
9505         WorklistRemover DeadNodes(*this);
9506         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9507         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9508         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9509         deleteAndRecombine(N);
9510         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9511       }
9512     }
9513   }
9514
9515   // If this load is directly stored, replace the load value with the stored
9516   // value.
9517   // TODO: Handle store large -> read small portion.
9518   // TODO: Handle TRUNCSTORE/LOADEXT
9519   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9520     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9521       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9522       if (PrevST->getBasePtr() == Ptr &&
9523           PrevST->getValue().getValueType() == N->getValueType(0))
9524       return CombineTo(N, Chain.getOperand(1), Chain);
9525     }
9526   }
9527
9528   // Try to infer better alignment information than the load already has.
9529   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9530     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9531       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9532         SDValue NewLoad =
9533                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9534                               LD->getValueType(0),
9535                               Chain, Ptr, LD->getPointerInfo(),
9536                               LD->getMemoryVT(),
9537                               LD->isVolatile(), LD->isNonTemporal(),
9538                               LD->isInvariant(), Align, LD->getAAInfo());
9539         if (NewLoad.getNode() != N)
9540           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9541       }
9542     }
9543   }
9544
9545   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9546                                                   : DAG.getSubtarget().useAA();
9547 #ifndef NDEBUG
9548   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9549       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9550     UseAA = false;
9551 #endif
9552   if (UseAA && LD->isUnindexed()) {
9553     // Walk up chain skipping non-aliasing memory nodes.
9554     SDValue BetterChain = FindBetterChain(N, Chain);
9555
9556     // If there is a better chain.
9557     if (Chain != BetterChain) {
9558       SDValue ReplLoad;
9559
9560       // Replace the chain to void dependency.
9561       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9562         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9563                                BetterChain, Ptr, LD->getMemOperand());
9564       } else {
9565         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9566                                   LD->getValueType(0),
9567                                   BetterChain, Ptr, LD->getMemoryVT(),
9568                                   LD->getMemOperand());
9569       }
9570
9571       // Create token factor to keep old chain connected.
9572       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9573                                   MVT::Other, Chain, ReplLoad.getValue(1));
9574
9575       // Make sure the new and old chains are cleaned up.
9576       AddToWorklist(Token.getNode());
9577
9578       // Replace uses with load result and token factor. Don't add users
9579       // to work list.
9580       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9581     }
9582   }
9583
9584   // Try transforming N to an indexed load.
9585   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9586     return SDValue(N, 0);
9587
9588   // Try to slice up N to more direct loads if the slices are mapped to
9589   // different register banks or pairing can take place.
9590   if (SliceUpLoad(N))
9591     return SDValue(N, 0);
9592
9593   return SDValue();
9594 }
9595
9596 namespace {
9597 /// \brief Helper structure used to slice a load in smaller loads.
9598 /// Basically a slice is obtained from the following sequence:
9599 /// Origin = load Ty1, Base
9600 /// Shift = srl Ty1 Origin, CstTy Amount
9601 /// Inst = trunc Shift to Ty2
9602 ///
9603 /// Then, it will be rewriten into:
9604 /// Slice = load SliceTy, Base + SliceOffset
9605 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9606 ///
9607 /// SliceTy is deduced from the number of bits that are actually used to
9608 /// build Inst.
9609 struct LoadedSlice {
9610   /// \brief Helper structure used to compute the cost of a slice.
9611   struct Cost {
9612     /// Are we optimizing for code size.
9613     bool ForCodeSize;
9614     /// Various cost.
9615     unsigned Loads;
9616     unsigned Truncates;
9617     unsigned CrossRegisterBanksCopies;
9618     unsigned ZExts;
9619     unsigned Shift;
9620
9621     Cost(bool ForCodeSize = false)
9622         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9623           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9624
9625     /// \brief Get the cost of one isolated slice.
9626     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9627         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9628           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9629       EVT TruncType = LS.Inst->getValueType(0);
9630       EVT LoadedType = LS.getLoadedType();
9631       if (TruncType != LoadedType &&
9632           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9633         ZExts = 1;
9634     }
9635
9636     /// \brief Account for slicing gain in the current cost.
9637     /// Slicing provide a few gains like removing a shift or a
9638     /// truncate. This method allows to grow the cost of the original
9639     /// load with the gain from this slice.
9640     void addSliceGain(const LoadedSlice &LS) {
9641       // Each slice saves a truncate.
9642       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9643       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9644                               LS.Inst->getOperand(0).getValueType()))
9645         ++Truncates;
9646       // If there is a shift amount, this slice gets rid of it.
9647       if (LS.Shift)
9648         ++Shift;
9649       // If this slice can merge a cross register bank copy, account for it.
9650       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9651         ++CrossRegisterBanksCopies;
9652     }
9653
9654     Cost &operator+=(const Cost &RHS) {
9655       Loads += RHS.Loads;
9656       Truncates += RHS.Truncates;
9657       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9658       ZExts += RHS.ZExts;
9659       Shift += RHS.Shift;
9660       return *this;
9661     }
9662
9663     bool operator==(const Cost &RHS) const {
9664       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9665              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9666              ZExts == RHS.ZExts && Shift == RHS.Shift;
9667     }
9668
9669     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9670
9671     bool operator<(const Cost &RHS) const {
9672       // Assume cross register banks copies are as expensive as loads.
9673       // FIXME: Do we want some more target hooks?
9674       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9675       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9676       // Unless we are optimizing for code size, consider the
9677       // expensive operation first.
9678       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9679         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9680       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9681              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9682     }
9683
9684     bool operator>(const Cost &RHS) const { return RHS < *this; }
9685
9686     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9687
9688     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9689   };
9690   // The last instruction that represent the slice. This should be a
9691   // truncate instruction.
9692   SDNode *Inst;
9693   // The original load instruction.
9694   LoadSDNode *Origin;
9695   // The right shift amount in bits from the original load.
9696   unsigned Shift;
9697   // The DAG from which Origin came from.
9698   // This is used to get some contextual information about legal types, etc.
9699   SelectionDAG *DAG;
9700
9701   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9702               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9703       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9704
9705   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9706   /// \return Result is \p BitWidth and has used bits set to 1 and
9707   ///         not used bits set to 0.
9708   APInt getUsedBits() const {
9709     // Reproduce the trunc(lshr) sequence:
9710     // - Start from the truncated value.
9711     // - Zero extend to the desired bit width.
9712     // - Shift left.
9713     assert(Origin && "No original load to compare against.");
9714     unsigned BitWidth = Origin->getValueSizeInBits(0);
9715     assert(Inst && "This slice is not bound to an instruction");
9716     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9717            "Extracted slice is bigger than the whole type!");
9718     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9719     UsedBits.setAllBits();
9720     UsedBits = UsedBits.zext(BitWidth);
9721     UsedBits <<= Shift;
9722     return UsedBits;
9723   }
9724
9725   /// \brief Get the size of the slice to be loaded in bytes.
9726   unsigned getLoadedSize() const {
9727     unsigned SliceSize = getUsedBits().countPopulation();
9728     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9729     return SliceSize / 8;
9730   }
9731
9732   /// \brief Get the type that will be loaded for this slice.
9733   /// Note: This may not be the final type for the slice.
9734   EVT getLoadedType() const {
9735     assert(DAG && "Missing context");
9736     LLVMContext &Ctxt = *DAG->getContext();
9737     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9738   }
9739
9740   /// \brief Get the alignment of the load used for this slice.
9741   unsigned getAlignment() const {
9742     unsigned Alignment = Origin->getAlignment();
9743     unsigned Offset = getOffsetFromBase();
9744     if (Offset != 0)
9745       Alignment = MinAlign(Alignment, Alignment + Offset);
9746     return Alignment;
9747   }
9748
9749   /// \brief Check if this slice can be rewritten with legal operations.
9750   bool isLegal() const {
9751     // An invalid slice is not legal.
9752     if (!Origin || !Inst || !DAG)
9753       return false;
9754
9755     // Offsets are for indexed load only, we do not handle that.
9756     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9757       return false;
9758
9759     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9760
9761     // Check that the type is legal.
9762     EVT SliceType = getLoadedType();
9763     if (!TLI.isTypeLegal(SliceType))
9764       return false;
9765
9766     // Check that the load is legal for this type.
9767     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9768       return false;
9769
9770     // Check that the offset can be computed.
9771     // 1. Check its type.
9772     EVT PtrType = Origin->getBasePtr().getValueType();
9773     if (PtrType == MVT::Untyped || PtrType.isExtended())
9774       return false;
9775
9776     // 2. Check that it fits in the immediate.
9777     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9778       return false;
9779
9780     // 3. Check that the computation is legal.
9781     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9782       return false;
9783
9784     // Check that the zext is legal if it needs one.
9785     EVT TruncateType = Inst->getValueType(0);
9786     if (TruncateType != SliceType &&
9787         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9788       return false;
9789
9790     return true;
9791   }
9792
9793   /// \brief Get the offset in bytes of this slice in the original chunk of
9794   /// bits.
9795   /// \pre DAG != nullptr.
9796   uint64_t getOffsetFromBase() const {
9797     assert(DAG && "Missing context.");
9798     bool IsBigEndian =
9799         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9800     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9801     uint64_t Offset = Shift / 8;
9802     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9803     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9804            "The size of the original loaded type is not a multiple of a"
9805            " byte.");
9806     // If Offset is bigger than TySizeInBytes, it means we are loading all
9807     // zeros. This should have been optimized before in the process.
9808     assert(TySizeInBytes > Offset &&
9809            "Invalid shift amount for given loaded size");
9810     if (IsBigEndian)
9811       Offset = TySizeInBytes - Offset - getLoadedSize();
9812     return Offset;
9813   }
9814
9815   /// \brief Generate the sequence of instructions to load the slice
9816   /// represented by this object and redirect the uses of this slice to
9817   /// this new sequence of instructions.
9818   /// \pre this->Inst && this->Origin are valid Instructions and this
9819   /// object passed the legal check: LoadedSlice::isLegal returned true.
9820   /// \return The last instruction of the sequence used to load the slice.
9821   SDValue loadSlice() const {
9822     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9823     const SDValue &OldBaseAddr = Origin->getBasePtr();
9824     SDValue BaseAddr = OldBaseAddr;
9825     // Get the offset in that chunk of bytes w.r.t. the endianess.
9826     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9827     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9828     if (Offset) {
9829       // BaseAddr = BaseAddr + Offset.
9830       EVT ArithType = BaseAddr.getValueType();
9831       SDLoc DL(Origin);
9832       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9833                               DAG->getConstant(Offset, DL, ArithType));
9834     }
9835
9836     // Create the type of the loaded slice according to its size.
9837     EVT SliceType = getLoadedType();
9838
9839     // Create the load for the slice.
9840     SDValue LastInst = DAG->getLoad(
9841         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9842         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9843         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9844     // If the final type is not the same as the loaded type, this means that
9845     // we have to pad with zero. Create a zero extend for that.
9846     EVT FinalType = Inst->getValueType(0);
9847     if (SliceType != FinalType)
9848       LastInst =
9849           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9850     return LastInst;
9851   }
9852
9853   /// \brief Check if this slice can be merged with an expensive cross register
9854   /// bank copy. E.g.,
9855   /// i = load i32
9856   /// f = bitcast i32 i to float
9857   bool canMergeExpensiveCrossRegisterBankCopy() const {
9858     if (!Inst || !Inst->hasOneUse())
9859       return false;
9860     SDNode *Use = *Inst->use_begin();
9861     if (Use->getOpcode() != ISD::BITCAST)
9862       return false;
9863     assert(DAG && "Missing context");
9864     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9865     EVT ResVT = Use->getValueType(0);
9866     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9867     const TargetRegisterClass *ArgRC =
9868         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9869     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9870       return false;
9871
9872     // At this point, we know that we perform a cross-register-bank copy.
9873     // Check if it is expensive.
9874     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9875     // Assume bitcasts are cheap, unless both register classes do not
9876     // explicitly share a common sub class.
9877     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9878       return false;
9879
9880     // Check if it will be merged with the load.
9881     // 1. Check the alignment constraint.
9882     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9883         ResVT.getTypeForEVT(*DAG->getContext()));
9884
9885     if (RequiredAlignment > getAlignment())
9886       return false;
9887
9888     // 2. Check that the load is a legal operation for that type.
9889     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9890       return false;
9891
9892     // 3. Check that we do not have a zext in the way.
9893     if (Inst->getValueType(0) != getLoadedType())
9894       return false;
9895
9896     return true;
9897   }
9898 };
9899 }
9900
9901 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9902 /// \p UsedBits looks like 0..0 1..1 0..0.
9903 static bool areUsedBitsDense(const APInt &UsedBits) {
9904   // If all the bits are one, this is dense!
9905   if (UsedBits.isAllOnesValue())
9906     return true;
9907
9908   // Get rid of the unused bits on the right.
9909   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9910   // Get rid of the unused bits on the left.
9911   if (NarrowedUsedBits.countLeadingZeros())
9912     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9913   // Check that the chunk of bits is completely used.
9914   return NarrowedUsedBits.isAllOnesValue();
9915 }
9916
9917 /// \brief Check whether or not \p First and \p Second are next to each other
9918 /// in memory. This means that there is no hole between the bits loaded
9919 /// by \p First and the bits loaded by \p Second.
9920 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9921                                      const LoadedSlice &Second) {
9922   assert(First.Origin == Second.Origin && First.Origin &&
9923          "Unable to match different memory origins.");
9924   APInt UsedBits = First.getUsedBits();
9925   assert((UsedBits & Second.getUsedBits()) == 0 &&
9926          "Slices are not supposed to overlap.");
9927   UsedBits |= Second.getUsedBits();
9928   return areUsedBitsDense(UsedBits);
9929 }
9930
9931 /// \brief Adjust the \p GlobalLSCost according to the target
9932 /// paring capabilities and the layout of the slices.
9933 /// \pre \p GlobalLSCost should account for at least as many loads as
9934 /// there is in the slices in \p LoadedSlices.
9935 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9936                                  LoadedSlice::Cost &GlobalLSCost) {
9937   unsigned NumberOfSlices = LoadedSlices.size();
9938   // If there is less than 2 elements, no pairing is possible.
9939   if (NumberOfSlices < 2)
9940     return;
9941
9942   // Sort the slices so that elements that are likely to be next to each
9943   // other in memory are next to each other in the list.
9944   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9945             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9946     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9947     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9948   });
9949   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9950   // First (resp. Second) is the first (resp. Second) potentially candidate
9951   // to be placed in a paired load.
9952   const LoadedSlice *First = nullptr;
9953   const LoadedSlice *Second = nullptr;
9954   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9955                 // Set the beginning of the pair.
9956                                                            First = Second) {
9957
9958     Second = &LoadedSlices[CurrSlice];
9959
9960     // If First is NULL, it means we start a new pair.
9961     // Get to the next slice.
9962     if (!First)
9963       continue;
9964
9965     EVT LoadedType = First->getLoadedType();
9966
9967     // If the types of the slices are different, we cannot pair them.
9968     if (LoadedType != Second->getLoadedType())
9969       continue;
9970
9971     // Check if the target supplies paired loads for this type.
9972     unsigned RequiredAlignment = 0;
9973     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9974       // move to the next pair, this type is hopeless.
9975       Second = nullptr;
9976       continue;
9977     }
9978     // Check if we meet the alignment requirement.
9979     if (RequiredAlignment > First->getAlignment())
9980       continue;
9981
9982     // Check that both loads are next to each other in memory.
9983     if (!areSlicesNextToEachOther(*First, *Second))
9984       continue;
9985
9986     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9987     --GlobalLSCost.Loads;
9988     // Move to the next pair.
9989     Second = nullptr;
9990   }
9991 }
9992
9993 /// \brief Check the profitability of all involved LoadedSlice.
9994 /// Currently, it is considered profitable if there is exactly two
9995 /// involved slices (1) which are (2) next to each other in memory, and
9996 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9997 ///
9998 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9999 /// the elements themselves.
10000 ///
10001 /// FIXME: When the cost model will be mature enough, we can relax
10002 /// constraints (1) and (2).
10003 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10004                                 const APInt &UsedBits, bool ForCodeSize) {
10005   unsigned NumberOfSlices = LoadedSlices.size();
10006   if (StressLoadSlicing)
10007     return NumberOfSlices > 1;
10008
10009   // Check (1).
10010   if (NumberOfSlices != 2)
10011     return false;
10012
10013   // Check (2).
10014   if (!areUsedBitsDense(UsedBits))
10015     return false;
10016
10017   // Check (3).
10018   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10019   // The original code has one big load.
10020   OrigCost.Loads = 1;
10021   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10022     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10023     // Accumulate the cost of all the slices.
10024     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10025     GlobalSlicingCost += SliceCost;
10026
10027     // Account as cost in the original configuration the gain obtained
10028     // with the current slices.
10029     OrigCost.addSliceGain(LS);
10030   }
10031
10032   // If the target supports paired load, adjust the cost accordingly.
10033   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10034   return OrigCost > GlobalSlicingCost;
10035 }
10036
10037 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10038 /// operations, split it in the various pieces being extracted.
10039 ///
10040 /// This sort of thing is introduced by SROA.
10041 /// This slicing takes care not to insert overlapping loads.
10042 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10043 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10044   if (Level < AfterLegalizeDAG)
10045     return false;
10046
10047   LoadSDNode *LD = cast<LoadSDNode>(N);
10048   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10049       !LD->getValueType(0).isInteger())
10050     return false;
10051
10052   // Keep track of already used bits to detect overlapping values.
10053   // In that case, we will just abort the transformation.
10054   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10055
10056   SmallVector<LoadedSlice, 4> LoadedSlices;
10057
10058   // Check if this load is used as several smaller chunks of bits.
10059   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10060   // of computation for each trunc.
10061   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10062        UI != UIEnd; ++UI) {
10063     // Skip the uses of the chain.
10064     if (UI.getUse().getResNo() != 0)
10065       continue;
10066
10067     SDNode *User = *UI;
10068     unsigned Shift = 0;
10069
10070     // Check if this is a trunc(lshr).
10071     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10072         isa<ConstantSDNode>(User->getOperand(1))) {
10073       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10074       User = *User->use_begin();
10075     }
10076
10077     // At this point, User is a Truncate, iff we encountered, trunc or
10078     // trunc(lshr).
10079     if (User->getOpcode() != ISD::TRUNCATE)
10080       return false;
10081
10082     // The width of the type must be a power of 2 and greater than 8-bits.
10083     // Otherwise the load cannot be represented in LLVM IR.
10084     // Moreover, if we shifted with a non-8-bits multiple, the slice
10085     // will be across several bytes. We do not support that.
10086     unsigned Width = User->getValueSizeInBits(0);
10087     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10088       return 0;
10089
10090     // Build the slice for this chain of computations.
10091     LoadedSlice LS(User, LD, Shift, &DAG);
10092     APInt CurrentUsedBits = LS.getUsedBits();
10093
10094     // Check if this slice overlaps with another.
10095     if ((CurrentUsedBits & UsedBits) != 0)
10096       return false;
10097     // Update the bits used globally.
10098     UsedBits |= CurrentUsedBits;
10099
10100     // Check if the new slice would be legal.
10101     if (!LS.isLegal())
10102       return false;
10103
10104     // Record the slice.
10105     LoadedSlices.push_back(LS);
10106   }
10107
10108   // Abort slicing if it does not seem to be profitable.
10109   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10110     return false;
10111
10112   ++SlicedLoads;
10113
10114   // Rewrite each chain to use an independent load.
10115   // By construction, each chain can be represented by a unique load.
10116
10117   // Prepare the argument for the new token factor for all the slices.
10118   SmallVector<SDValue, 8> ArgChains;
10119   for (SmallVectorImpl<LoadedSlice>::const_iterator
10120            LSIt = LoadedSlices.begin(),
10121            LSItEnd = LoadedSlices.end();
10122        LSIt != LSItEnd; ++LSIt) {
10123     SDValue SliceInst = LSIt->loadSlice();
10124     CombineTo(LSIt->Inst, SliceInst, true);
10125     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10126       SliceInst = SliceInst.getOperand(0);
10127     assert(SliceInst->getOpcode() == ISD::LOAD &&
10128            "It takes more than a zext to get to the loaded slice!!");
10129     ArgChains.push_back(SliceInst.getValue(1));
10130   }
10131
10132   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10133                               ArgChains);
10134   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10135   return true;
10136 }
10137
10138 /// Check to see if V is (and load (ptr), imm), where the load is having
10139 /// specific bytes cleared out.  If so, return the byte size being masked out
10140 /// and the shift amount.
10141 static std::pair<unsigned, unsigned>
10142 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10143   std::pair<unsigned, unsigned> Result(0, 0);
10144
10145   // Check for the structure we're looking for.
10146   if (V->getOpcode() != ISD::AND ||
10147       !isa<ConstantSDNode>(V->getOperand(1)) ||
10148       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10149     return Result;
10150
10151   // Check the chain and pointer.
10152   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10153   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10154
10155   // The store should be chained directly to the load or be an operand of a
10156   // tokenfactor.
10157   if (LD == Chain.getNode())
10158     ; // ok.
10159   else if (Chain->getOpcode() != ISD::TokenFactor)
10160     return Result; // Fail.
10161   else {
10162     bool isOk = false;
10163     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10164       if (Chain->getOperand(i).getNode() == LD) {
10165         isOk = true;
10166         break;
10167       }
10168     if (!isOk) return Result;
10169   }
10170
10171   // This only handles simple types.
10172   if (V.getValueType() != MVT::i16 &&
10173       V.getValueType() != MVT::i32 &&
10174       V.getValueType() != MVT::i64)
10175     return Result;
10176
10177   // Check the constant mask.  Invert it so that the bits being masked out are
10178   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10179   // follow the sign bit for uniformity.
10180   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10181   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10182   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10183   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10184   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10185   if (NotMaskLZ == 64) return Result;  // All zero mask.
10186
10187   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10188   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10189     return Result;
10190
10191   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10192   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10193     NotMaskLZ -= 64-V.getValueSizeInBits();
10194
10195   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10196   switch (MaskedBytes) {
10197   case 1:
10198   case 2:
10199   case 4: break;
10200   default: return Result; // All one mask, or 5-byte mask.
10201   }
10202
10203   // Verify that the first bit starts at a multiple of mask so that the access
10204   // is aligned the same as the access width.
10205   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10206
10207   Result.first = MaskedBytes;
10208   Result.second = NotMaskTZ/8;
10209   return Result;
10210 }
10211
10212
10213 /// Check to see if IVal is something that provides a value as specified by
10214 /// MaskInfo. If so, replace the specified store with a narrower store of
10215 /// truncated IVal.
10216 static SDNode *
10217 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10218                                 SDValue IVal, StoreSDNode *St,
10219                                 DAGCombiner *DC) {
10220   unsigned NumBytes = MaskInfo.first;
10221   unsigned ByteShift = MaskInfo.second;
10222   SelectionDAG &DAG = DC->getDAG();
10223
10224   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10225   // that uses this.  If not, this is not a replacement.
10226   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10227                                   ByteShift*8, (ByteShift+NumBytes)*8);
10228   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10229
10230   // Check that it is legal on the target to do this.  It is legal if the new
10231   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10232   // legalization.
10233   MVT VT = MVT::getIntegerVT(NumBytes*8);
10234   if (!DC->isTypeLegal(VT))
10235     return nullptr;
10236
10237   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10238   // shifted by ByteShift and truncated down to NumBytes.
10239   if (ByteShift) {
10240     SDLoc DL(IVal);
10241     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10242                        DAG.getConstant(ByteShift*8, DL,
10243                                     DC->getShiftAmountTy(IVal.getValueType())));
10244   }
10245
10246   // Figure out the offset for the store and the alignment of the access.
10247   unsigned StOffset;
10248   unsigned NewAlign = St->getAlignment();
10249
10250   if (DAG.getTargetLoweringInfo().isLittleEndian())
10251     StOffset = ByteShift;
10252   else
10253     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10254
10255   SDValue Ptr = St->getBasePtr();
10256   if (StOffset) {
10257     SDLoc DL(IVal);
10258     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10259                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10260     NewAlign = MinAlign(NewAlign, StOffset);
10261   }
10262
10263   // Truncate down to the new size.
10264   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10265
10266   ++OpsNarrowed;
10267   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10268                       St->getPointerInfo().getWithOffset(StOffset),
10269                       false, false, NewAlign).getNode();
10270 }
10271
10272
10273 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10274 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10275 /// narrowing the load and store if it would end up being a win for performance
10276 /// or code size.
10277 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10278   StoreSDNode *ST  = cast<StoreSDNode>(N);
10279   if (ST->isVolatile())
10280     return SDValue();
10281
10282   SDValue Chain = ST->getChain();
10283   SDValue Value = ST->getValue();
10284   SDValue Ptr   = ST->getBasePtr();
10285   EVT VT = Value.getValueType();
10286
10287   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10288     return SDValue();
10289
10290   unsigned Opc = Value.getOpcode();
10291
10292   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10293   // is a byte mask indicating a consecutive number of bytes, check to see if
10294   // Y is known to provide just those bytes.  If so, we try to replace the
10295   // load + replace + store sequence with a single (narrower) store, which makes
10296   // the load dead.
10297   if (Opc == ISD::OR) {
10298     std::pair<unsigned, unsigned> MaskedLoad;
10299     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10300     if (MaskedLoad.first)
10301       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10302                                                   Value.getOperand(1), ST,this))
10303         return SDValue(NewST, 0);
10304
10305     // Or is commutative, so try swapping X and Y.
10306     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10307     if (MaskedLoad.first)
10308       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10309                                                   Value.getOperand(0), ST,this))
10310         return SDValue(NewST, 0);
10311   }
10312
10313   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10314       Value.getOperand(1).getOpcode() != ISD::Constant)
10315     return SDValue();
10316
10317   SDValue N0 = Value.getOperand(0);
10318   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10319       Chain == SDValue(N0.getNode(), 1)) {
10320     LoadSDNode *LD = cast<LoadSDNode>(N0);
10321     if (LD->getBasePtr() != Ptr ||
10322         LD->getPointerInfo().getAddrSpace() !=
10323         ST->getPointerInfo().getAddrSpace())
10324       return SDValue();
10325
10326     // Find the type to narrow it the load / op / store to.
10327     SDValue N1 = Value.getOperand(1);
10328     unsigned BitWidth = N1.getValueSizeInBits();
10329     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10330     if (Opc == ISD::AND)
10331       Imm ^= APInt::getAllOnesValue(BitWidth);
10332     if (Imm == 0 || Imm.isAllOnesValue())
10333       return SDValue();
10334     unsigned ShAmt = Imm.countTrailingZeros();
10335     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10336     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10337     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10338     // The narrowing should be profitable, the load/store operation should be
10339     // legal (or custom) and the store size should be equal to the NewVT width.
10340     while (NewBW < BitWidth &&
10341            (NewVT.getStoreSizeInBits() != NewBW ||
10342             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10343             !TLI.isNarrowingProfitable(VT, NewVT))) {
10344       NewBW = NextPowerOf2(NewBW);
10345       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10346     }
10347     if (NewBW >= BitWidth)
10348       return SDValue();
10349
10350     // If the lsb changed does not start at the type bitwidth boundary,
10351     // start at the previous one.
10352     if (ShAmt % NewBW)
10353       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10354     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10355                                    std::min(BitWidth, ShAmt + NewBW));
10356     if ((Imm & Mask) == Imm) {
10357       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10358       if (Opc == ISD::AND)
10359         NewImm ^= APInt::getAllOnesValue(NewBW);
10360       uint64_t PtrOff = ShAmt / 8;
10361       // For big endian targets, we need to adjust the offset to the pointer to
10362       // load the correct bytes.
10363       if (TLI.isBigEndian())
10364         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10365
10366       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10367       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10368       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10369         return SDValue();
10370
10371       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10372                                    Ptr.getValueType(), Ptr,
10373                                    DAG.getConstant(PtrOff, SDLoc(LD),
10374                                                    Ptr.getValueType()));
10375       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10376                                   LD->getChain(), NewPtr,
10377                                   LD->getPointerInfo().getWithOffset(PtrOff),
10378                                   LD->isVolatile(), LD->isNonTemporal(),
10379                                   LD->isInvariant(), NewAlign,
10380                                   LD->getAAInfo());
10381       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10382                                    DAG.getConstant(NewImm, SDLoc(Value),
10383                                                    NewVT));
10384       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10385                                    NewVal, NewPtr,
10386                                    ST->getPointerInfo().getWithOffset(PtrOff),
10387                                    false, false, NewAlign);
10388
10389       AddToWorklist(NewPtr.getNode());
10390       AddToWorklist(NewLD.getNode());
10391       AddToWorklist(NewVal.getNode());
10392       WorklistRemover DeadNodes(*this);
10393       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10394       ++OpsNarrowed;
10395       return NewST;
10396     }
10397   }
10398
10399   return SDValue();
10400 }
10401
10402 /// For a given floating point load / store pair, if the load value isn't used
10403 /// by any other operations, then consider transforming the pair to integer
10404 /// load / store operations if the target deems the transformation profitable.
10405 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10406   StoreSDNode *ST  = cast<StoreSDNode>(N);
10407   SDValue Chain = ST->getChain();
10408   SDValue Value = ST->getValue();
10409   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10410       Value.hasOneUse() &&
10411       Chain == SDValue(Value.getNode(), 1)) {
10412     LoadSDNode *LD = cast<LoadSDNode>(Value);
10413     EVT VT = LD->getMemoryVT();
10414     if (!VT.isFloatingPoint() ||
10415         VT != ST->getMemoryVT() ||
10416         LD->isNonTemporal() ||
10417         ST->isNonTemporal() ||
10418         LD->getPointerInfo().getAddrSpace() != 0 ||
10419         ST->getPointerInfo().getAddrSpace() != 0)
10420       return SDValue();
10421
10422     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10423     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10424         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10425         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10426         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10427       return SDValue();
10428
10429     unsigned LDAlign = LD->getAlignment();
10430     unsigned STAlign = ST->getAlignment();
10431     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10432     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10433     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10434       return SDValue();
10435
10436     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10437                                 LD->getChain(), LD->getBasePtr(),
10438                                 LD->getPointerInfo(),
10439                                 false, false, false, LDAlign);
10440
10441     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10442                                  NewLD, ST->getBasePtr(),
10443                                  ST->getPointerInfo(),
10444                                  false, false, STAlign);
10445
10446     AddToWorklist(NewLD.getNode());
10447     AddToWorklist(NewST.getNode());
10448     WorklistRemover DeadNodes(*this);
10449     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10450     ++LdStFP2Int;
10451     return NewST;
10452   }
10453
10454   return SDValue();
10455 }
10456
10457 namespace {
10458 /// Helper struct to parse and store a memory address as base + index + offset.
10459 /// We ignore sign extensions when it is safe to do so.
10460 /// The following two expressions are not equivalent. To differentiate we need
10461 /// to store whether there was a sign extension involved in the index
10462 /// computation.
10463 ///  (load (i64 add (i64 copyfromreg %c)
10464 ///                 (i64 signextend (add (i8 load %index)
10465 ///                                      (i8 1))))
10466 /// vs
10467 ///
10468 /// (load (i64 add (i64 copyfromreg %c)
10469 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10470 ///                                         (i32 1)))))
10471 struct BaseIndexOffset {
10472   SDValue Base;
10473   SDValue Index;
10474   int64_t Offset;
10475   bool IsIndexSignExt;
10476
10477   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10478
10479   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10480                   bool IsIndexSignExt) :
10481     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10482
10483   bool equalBaseIndex(const BaseIndexOffset &Other) {
10484     return Other.Base == Base && Other.Index == Index &&
10485       Other.IsIndexSignExt == IsIndexSignExt;
10486   }
10487
10488   /// Parses tree in Ptr for base, index, offset addresses.
10489   static BaseIndexOffset match(SDValue Ptr) {
10490     bool IsIndexSignExt = false;
10491
10492     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10493     // instruction, then it could be just the BASE or everything else we don't
10494     // know how to handle. Just use Ptr as BASE and give up.
10495     if (Ptr->getOpcode() != ISD::ADD)
10496       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10497
10498     // We know that we have at least an ADD instruction. Try to pattern match
10499     // the simple case of BASE + OFFSET.
10500     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10501       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10502       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10503                               IsIndexSignExt);
10504     }
10505
10506     // Inside a loop the current BASE pointer is calculated using an ADD and a
10507     // MUL instruction. In this case Ptr is the actual BASE pointer.
10508     // (i64 add (i64 %array_ptr)
10509     //          (i64 mul (i64 %induction_var)
10510     //                   (i64 %element_size)))
10511     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10512       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10513
10514     // Look at Base + Index + Offset cases.
10515     SDValue Base = Ptr->getOperand(0);
10516     SDValue IndexOffset = Ptr->getOperand(1);
10517
10518     // Skip signextends.
10519     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10520       IndexOffset = IndexOffset->getOperand(0);
10521       IsIndexSignExt = true;
10522     }
10523
10524     // Either the case of Base + Index (no offset) or something else.
10525     if (IndexOffset->getOpcode() != ISD::ADD)
10526       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10527
10528     // Now we have the case of Base + Index + offset.
10529     SDValue Index = IndexOffset->getOperand(0);
10530     SDValue Offset = IndexOffset->getOperand(1);
10531
10532     if (!isa<ConstantSDNode>(Offset))
10533       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10534
10535     // Ignore signextends.
10536     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10537       Index = Index->getOperand(0);
10538       IsIndexSignExt = true;
10539     } else IsIndexSignExt = false;
10540
10541     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10542     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10543   }
10544 };
10545 } // namespace
10546
10547 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10548                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10549                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10550   // Make sure we have something to merge.
10551   if (NumElem < 2)
10552     return false;
10553
10554   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10555   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10556   unsigned LatestNodeUsed = 0;
10557
10558   for (unsigned i=0; i < NumElem; ++i) {
10559     // Find a chain for the new wide-store operand. Notice that some
10560     // of the store nodes that we found may not be selected for inclusion
10561     // in the wide store. The chain we use needs to be the chain of the
10562     // latest store node which is *used* and replaced by the wide store.
10563     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10564       LatestNodeUsed = i;
10565   }
10566
10567   // The latest Node in the DAG.
10568   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10569   SDLoc DL(StoreNodes[0].MemNode);
10570
10571   SDValue StoredVal;
10572   if (UseVector) {
10573     // Find a legal type for the vector store.
10574     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10575     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10576     if (IsConstantSrc) {
10577       // A vector store with a constant source implies that the constant is
10578       // zero; we only handle merging stores of constant zeros because the zero
10579       // can be materialized without a load.
10580       // It may be beneficial to loosen this restriction to allow non-zero
10581       // store merging.
10582       StoredVal = DAG.getConstant(0, DL, Ty);
10583     } else {
10584       SmallVector<SDValue, 8> Ops;
10585       for (unsigned i = 0; i < NumElem ; ++i) {
10586         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10587         SDValue Val = St->getValue();
10588         // All of the operands of a BUILD_VECTOR must have the same type.
10589         if (Val.getValueType() != MemVT)
10590           return false;
10591         Ops.push_back(Val);
10592       }
10593
10594       // Build the extracted vector elements back into a vector.
10595       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10596     }
10597   } else {
10598     // We should always use a vector store when merging extracted vector
10599     // elements, so this path implies a store of constants.
10600     assert(IsConstantSrc && "Merged vector elements should use vector store");
10601
10602     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10603     APInt StoreInt(StoreBW, 0);
10604
10605     // Construct a single integer constant which is made of the smaller
10606     // constant inputs.
10607     bool IsLE = TLI.isLittleEndian();
10608     for (unsigned i = 0; i < NumElem ; ++i) {
10609       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10610       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10611       SDValue Val = St->getValue();
10612       StoreInt <<= ElementSizeBytes*8;
10613       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10614         StoreInt |= C->getAPIntValue().zext(StoreBW);
10615       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10616         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10617       } else {
10618         llvm_unreachable("Invalid constant element type");
10619       }
10620     }
10621
10622     // Create the new Load and Store operations.
10623     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10624     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10625   }
10626
10627   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10628                                   FirstInChain->getBasePtr(),
10629                                   FirstInChain->getPointerInfo(),
10630                                   false, false,
10631                                   FirstInChain->getAlignment());
10632
10633   // Replace the last store with the new store
10634   CombineTo(LatestOp, NewStore);
10635   // Erase all other stores.
10636   for (unsigned i = 0; i < NumElem ; ++i) {
10637     if (StoreNodes[i].MemNode == LatestOp)
10638       continue;
10639     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10640     // ReplaceAllUsesWith will replace all uses that existed when it was
10641     // called, but graph optimizations may cause new ones to appear. For
10642     // example, the case in pr14333 looks like
10643     //
10644     //  St's chain -> St -> another store -> X
10645     //
10646     // And the only difference from St to the other store is the chain.
10647     // When we change it's chain to be St's chain they become identical,
10648     // get CSEed and the net result is that X is now a use of St.
10649     // Since we know that St is redundant, just iterate.
10650     while (!St->use_empty())
10651       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10652     deleteAndRecombine(St);
10653   }
10654
10655   return true;
10656 }
10657
10658 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10659   if (OptLevel == CodeGenOpt::None)
10660     return false;
10661
10662   EVT MemVT = St->getMemoryVT();
10663   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10664   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10665       Attribute::NoImplicitFloat);
10666
10667   // Don't merge vectors into wider inputs.
10668   if (MemVT.isVector() || !MemVT.isSimple())
10669     return false;
10670
10671   // Perform an early exit check. Do not bother looking at stored values that
10672   // are not constants, loads, or extracted vector elements.
10673   SDValue StoredVal = St->getValue();
10674   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10675   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10676                        isa<ConstantFPSDNode>(StoredVal);
10677   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10678
10679   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10680     return false;
10681
10682   // Only look at ends of store sequences.
10683   SDValue Chain = SDValue(St, 0);
10684   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10685     return false;
10686
10687   // This holds the base pointer, index, and the offset in bytes from the base
10688   // pointer.
10689   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10690
10691   // We must have a base and an offset.
10692   if (!BasePtr.Base.getNode())
10693     return false;
10694
10695   // Do not handle stores to undef base pointers.
10696   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10697     return false;
10698
10699   // Save the LoadSDNodes that we find in the chain.
10700   // We need to make sure that these nodes do not interfere with
10701   // any of the store nodes.
10702   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10703
10704   // Save the StoreSDNodes that we find in the chain.
10705   SmallVector<MemOpLink, 8> StoreNodes;
10706
10707   // Walk up the chain and look for nodes with offsets from the same
10708   // base pointer. Stop when reaching an instruction with a different kind
10709   // or instruction which has a different base pointer.
10710   unsigned Seq = 0;
10711   StoreSDNode *Index = St;
10712   while (Index) {
10713     // If the chain has more than one use, then we can't reorder the mem ops.
10714     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10715       break;
10716
10717     // Find the base pointer and offset for this memory node.
10718     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10719
10720     // Check that the base pointer is the same as the original one.
10721     if (!Ptr.equalBaseIndex(BasePtr))
10722       break;
10723
10724     // Check that the alignment is the same.
10725     if (Index->getAlignment() != St->getAlignment())
10726       break;
10727
10728     // The memory operands must not be volatile.
10729     if (Index->isVolatile() || Index->isIndexed())
10730       break;
10731
10732     // No truncation.
10733     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10734       if (St->isTruncatingStore())
10735         break;
10736
10737     // The stored memory type must be the same.
10738     if (Index->getMemoryVT() != MemVT)
10739       break;
10740
10741     // We do not allow unaligned stores because we want to prevent overriding
10742     // stores.
10743     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10744       break;
10745
10746     // We found a potential memory operand to merge.
10747     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10748
10749     // Find the next memory operand in the chain. If the next operand in the
10750     // chain is a store then move up and continue the scan with the next
10751     // memory operand. If the next operand is a load save it and use alias
10752     // information to check if it interferes with anything.
10753     SDNode *NextInChain = Index->getChain().getNode();
10754     while (1) {
10755       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10756         // We found a store node. Use it for the next iteration.
10757         Index = STn;
10758         break;
10759       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10760         if (Ldn->isVolatile()) {
10761           Index = nullptr;
10762           break;
10763         }
10764
10765         // Save the load node for later. Continue the scan.
10766         AliasLoadNodes.push_back(Ldn);
10767         NextInChain = Ldn->getChain().getNode();
10768         continue;
10769       } else {
10770         Index = nullptr;
10771         break;
10772       }
10773     }
10774   }
10775
10776   // Check if there is anything to merge.
10777   if (StoreNodes.size() < 2)
10778     return false;
10779
10780   // Sort the memory operands according to their distance from the base pointer.
10781   std::sort(StoreNodes.begin(), StoreNodes.end(),
10782             [](MemOpLink LHS, MemOpLink RHS) {
10783     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10784            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10785             LHS.SequenceNum > RHS.SequenceNum);
10786   });
10787
10788   // Scan the memory operations on the chain and find the first non-consecutive
10789   // store memory address.
10790   unsigned LastConsecutiveStore = 0;
10791   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10792   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10793
10794     // Check that the addresses are consecutive starting from the second
10795     // element in the list of stores.
10796     if (i > 0) {
10797       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10798       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10799         break;
10800     }
10801
10802     bool Alias = false;
10803     // Check if this store interferes with any of the loads that we found.
10804     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10805       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10806         Alias = true;
10807         break;
10808       }
10809     // We found a load that alias with this store. Stop the sequence.
10810     if (Alias)
10811       break;
10812
10813     // Mark this node as useful.
10814     LastConsecutiveStore = i;
10815   }
10816
10817   // The node with the lowest store address.
10818   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10819
10820   // Store the constants into memory as one consecutive store.
10821   if (IsConstantSrc) {
10822     unsigned LastLegalType = 0;
10823     unsigned LastLegalVectorType = 0;
10824     bool NonZero = false;
10825     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10826       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10827       SDValue StoredVal = St->getValue();
10828
10829       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10830         NonZero |= !C->isNullValue();
10831       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10832         NonZero |= !C->getConstantFPValue()->isNullValue();
10833       } else {
10834         // Non-constant.
10835         break;
10836       }
10837
10838       // Find a legal type for the constant store.
10839       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10840       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10841       if (TLI.isTypeLegal(StoreTy))
10842         LastLegalType = i+1;
10843       // Or check whether a truncstore is legal.
10844       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10845                TargetLowering::TypePromoteInteger) {
10846         EVT LegalizedStoredValueTy =
10847           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10848         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10849           LastLegalType = i+1;
10850       }
10851
10852       // Find a legal type for the vector store.
10853       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10854       if (TLI.isTypeLegal(Ty))
10855         LastLegalVectorType = i + 1;
10856     }
10857
10858     // We only use vectors if the constant is known to be zero and the
10859     // function is not marked with the noimplicitfloat attribute.
10860     if (NonZero || NoVectors)
10861       LastLegalVectorType = 0;
10862
10863     // Check if we found a legal integer type to store.
10864     if (LastLegalType == 0 && LastLegalVectorType == 0)
10865       return false;
10866
10867     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10868     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10869
10870     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10871                                            true, UseVector);
10872   }
10873
10874   // When extracting multiple vector elements, try to store them
10875   // in one vector store rather than a sequence of scalar stores.
10876   if (IsExtractVecEltSrc) {
10877     unsigned NumElem = 0;
10878     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10879       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10880       SDValue StoredVal = St->getValue();
10881       // This restriction could be loosened.
10882       // Bail out if any stored values are not elements extracted from a vector.
10883       // It should be possible to handle mixed sources, but load sources need
10884       // more careful handling (see the block of code below that handles
10885       // consecutive loads).
10886       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10887         return false;
10888
10889       // Find a legal type for the vector store.
10890       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10891       if (TLI.isTypeLegal(Ty))
10892         NumElem = i + 1;
10893     }
10894
10895     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10896                                            false, true);
10897   }
10898
10899   // Below we handle the case of multiple consecutive stores that
10900   // come from multiple consecutive loads. We merge them into a single
10901   // wide load and a single wide store.
10902
10903   // Look for load nodes which are used by the stored values.
10904   SmallVector<MemOpLink, 8> LoadNodes;
10905
10906   // Find acceptable loads. Loads need to have the same chain (token factor),
10907   // must not be zext, volatile, indexed, and they must be consecutive.
10908   BaseIndexOffset LdBasePtr;
10909   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10910     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10911     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10912     if (!Ld) break;
10913
10914     // Loads must only have one use.
10915     if (!Ld->hasNUsesOfValue(1, 0))
10916       break;
10917
10918     // Check that the alignment is the same as the stores.
10919     if (Ld->getAlignment() != St->getAlignment())
10920       break;
10921
10922     // The memory operands must not be volatile.
10923     if (Ld->isVolatile() || Ld->isIndexed())
10924       break;
10925
10926     // We do not accept ext loads.
10927     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10928       break;
10929
10930     // The stored memory type must be the same.
10931     if (Ld->getMemoryVT() != MemVT)
10932       break;
10933
10934     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10935     // If this is not the first ptr that we check.
10936     if (LdBasePtr.Base.getNode()) {
10937       // The base ptr must be the same.
10938       if (!LdPtr.equalBaseIndex(LdBasePtr))
10939         break;
10940     } else {
10941       // Check that all other base pointers are the same as this one.
10942       LdBasePtr = LdPtr;
10943     }
10944
10945     // We found a potential memory operand to merge.
10946     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10947   }
10948
10949   if (LoadNodes.size() < 2)
10950     return false;
10951
10952   // If we have load/store pair instructions and we only have two values,
10953   // don't bother.
10954   unsigned RequiredAlignment;
10955   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10956       St->getAlignment() >= RequiredAlignment)
10957     return false;
10958
10959   // Scan the memory operations on the chain and find the first non-consecutive
10960   // load memory address. These variables hold the index in the store node
10961   // array.
10962   unsigned LastConsecutiveLoad = 0;
10963   // This variable refers to the size and not index in the array.
10964   unsigned LastLegalVectorType = 0;
10965   unsigned LastLegalIntegerType = 0;
10966   StartAddress = LoadNodes[0].OffsetFromBase;
10967   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10968   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10969     // All loads much share the same chain.
10970     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10971       break;
10972
10973     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10974     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10975       break;
10976     LastConsecutiveLoad = i;
10977
10978     // Find a legal type for the vector store.
10979     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10980     if (TLI.isTypeLegal(StoreTy))
10981       LastLegalVectorType = i + 1;
10982
10983     // Find a legal type for the integer store.
10984     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10985     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10986     if (TLI.isTypeLegal(StoreTy))
10987       LastLegalIntegerType = i + 1;
10988     // Or check whether a truncstore and extload is legal.
10989     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10990              TargetLowering::TypePromoteInteger) {
10991       EVT LegalizedStoredValueTy =
10992         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10993       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10994           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10995           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10996           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10997         LastLegalIntegerType = i+1;
10998     }
10999   }
11000
11001   // Only use vector types if the vector type is larger than the integer type.
11002   // If they are the same, use integers.
11003   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11004   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11005
11006   // We add +1 here because the LastXXX variables refer to location while
11007   // the NumElem refers to array/index size.
11008   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11009   NumElem = std::min(LastLegalType, NumElem);
11010
11011   if (NumElem < 2)
11012     return false;
11013
11014   // The latest Node in the DAG.
11015   unsigned LatestNodeUsed = 0;
11016   for (unsigned i=1; i<NumElem; ++i) {
11017     // Find a chain for the new wide-store operand. Notice that some
11018     // of the store nodes that we found may not be selected for inclusion
11019     // in the wide store. The chain we use needs to be the chain of the
11020     // latest store node which is *used* and replaced by the wide store.
11021     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11022       LatestNodeUsed = i;
11023   }
11024
11025   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11026
11027   // Find if it is better to use vectors or integers to load and store
11028   // to memory.
11029   EVT JointMemOpVT;
11030   if (UseVectorTy) {
11031     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11032   } else {
11033     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11034     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11035   }
11036
11037   SDLoc LoadDL(LoadNodes[0].MemNode);
11038   SDLoc StoreDL(StoreNodes[0].MemNode);
11039
11040   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11041   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
11042                                 FirstLoad->getChain(),
11043                                 FirstLoad->getBasePtr(),
11044                                 FirstLoad->getPointerInfo(),
11045                                 false, false, false,
11046                                 FirstLoad->getAlignment());
11047
11048   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
11049                                   FirstInChain->getBasePtr(),
11050                                   FirstInChain->getPointerInfo(), false, false,
11051                                   FirstInChain->getAlignment());
11052
11053   // Replace one of the loads with the new load.
11054   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11055   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11056                                 SDValue(NewLoad.getNode(), 1));
11057
11058   // Remove the rest of the load chains.
11059   for (unsigned i = 1; i < NumElem ; ++i) {
11060     // Replace all chain users of the old load nodes with the chain of the new
11061     // load node.
11062     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11063     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11064   }
11065
11066   // Replace the last store with the new store.
11067   CombineTo(LatestOp, NewStore);
11068   // Erase all other stores.
11069   for (unsigned i = 0; i < NumElem ; ++i) {
11070     // Remove all Store nodes.
11071     if (StoreNodes[i].MemNode == LatestOp)
11072       continue;
11073     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11074     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11075     deleteAndRecombine(St);
11076   }
11077
11078   return true;
11079 }
11080
11081 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11082   StoreSDNode *ST  = cast<StoreSDNode>(N);
11083   SDValue Chain = ST->getChain();
11084   SDValue Value = ST->getValue();
11085   SDValue Ptr   = ST->getBasePtr();
11086
11087   // If this is a store of a bit convert, store the input value if the
11088   // resultant store does not need a higher alignment than the original.
11089   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11090       ST->isUnindexed()) {
11091     unsigned OrigAlign = ST->getAlignment();
11092     EVT SVT = Value.getOperand(0).getValueType();
11093     unsigned Align = TLI.getDataLayout()->
11094       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11095     if (Align <= OrigAlign &&
11096         ((!LegalOperations && !ST->isVolatile()) ||
11097          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11098       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11099                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11100                           ST->isNonTemporal(), OrigAlign,
11101                           ST->getAAInfo());
11102   }
11103
11104   // Turn 'store undef, Ptr' -> nothing.
11105   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11106     return Chain;
11107
11108   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11109   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11110     // NOTE: If the original store is volatile, this transform must not increase
11111     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11112     // processor operation but an i64 (which is not legal) requires two.  So the
11113     // transform should not be done in this case.
11114     if (Value.getOpcode() != ISD::TargetConstantFP) {
11115       SDValue Tmp;
11116       switch (CFP->getSimpleValueType(0).SimpleTy) {
11117       default: llvm_unreachable("Unknown FP type");
11118       case MVT::f16:    // We don't do this for these yet.
11119       case MVT::f80:
11120       case MVT::f128:
11121       case MVT::ppcf128:
11122         break;
11123       case MVT::f32:
11124         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11125             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11126           ;
11127           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11128                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11129                               MVT::i32);
11130           return DAG.getStore(Chain, SDLoc(N), Tmp,
11131                               Ptr, ST->getMemOperand());
11132         }
11133         break;
11134       case MVT::f64:
11135         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11136              !ST->isVolatile()) ||
11137             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11138           ;
11139           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11140                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11141           return DAG.getStore(Chain, SDLoc(N), Tmp,
11142                               Ptr, ST->getMemOperand());
11143         }
11144
11145         if (!ST->isVolatile() &&
11146             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11147           // Many FP stores are not made apparent until after legalize, e.g. for
11148           // argument passing.  Since this is so common, custom legalize the
11149           // 64-bit integer store into two 32-bit stores.
11150           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11151           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11152           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11153           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11154
11155           unsigned Alignment = ST->getAlignment();
11156           bool isVolatile = ST->isVolatile();
11157           bool isNonTemporal = ST->isNonTemporal();
11158           AAMDNodes AAInfo = ST->getAAInfo();
11159
11160           SDLoc DL(N);
11161
11162           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11163                                      Ptr, ST->getPointerInfo(),
11164                                      isVolatile, isNonTemporal,
11165                                      ST->getAlignment(), AAInfo);
11166           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11167                             DAG.getConstant(4, DL, Ptr.getValueType()));
11168           Alignment = MinAlign(Alignment, 4U);
11169           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11170                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11171                                      isVolatile, isNonTemporal,
11172                                      Alignment, AAInfo);
11173           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11174                              St0, St1);
11175         }
11176
11177         break;
11178       }
11179     }
11180   }
11181
11182   // Try to infer better alignment information than the store already has.
11183   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11184     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11185       if (Align > ST->getAlignment()) {
11186         SDValue NewStore =
11187                DAG.getTruncStore(Chain, SDLoc(N), Value,
11188                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11189                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11190                                  ST->getAAInfo());
11191         if (NewStore.getNode() != N)
11192           return CombineTo(ST, NewStore, true);
11193       }
11194     }
11195   }
11196
11197   // Try transforming a pair floating point load / store ops to integer
11198   // load / store ops.
11199   SDValue NewST = TransformFPLoadStorePair(N);
11200   if (NewST.getNode())
11201     return NewST;
11202
11203   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11204                                                   : DAG.getSubtarget().useAA();
11205 #ifndef NDEBUG
11206   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11207       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11208     UseAA = false;
11209 #endif
11210   if (UseAA && ST->isUnindexed()) {
11211     // Walk up chain skipping non-aliasing memory nodes.
11212     SDValue BetterChain = FindBetterChain(N, Chain);
11213
11214     // If there is a better chain.
11215     if (Chain != BetterChain) {
11216       SDValue ReplStore;
11217
11218       // Replace the chain to avoid dependency.
11219       if (ST->isTruncatingStore()) {
11220         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11221                                       ST->getMemoryVT(), ST->getMemOperand());
11222       } else {
11223         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11224                                  ST->getMemOperand());
11225       }
11226
11227       // Create token to keep both nodes around.
11228       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11229                                   MVT::Other, Chain, ReplStore);
11230
11231       // Make sure the new and old chains are cleaned up.
11232       AddToWorklist(Token.getNode());
11233
11234       // Don't add users to work list.
11235       return CombineTo(N, Token, false);
11236     }
11237   }
11238
11239   // Try transforming N to an indexed store.
11240   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11241     return SDValue(N, 0);
11242
11243   // FIXME: is there such a thing as a truncating indexed store?
11244   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11245       Value.getValueType().isInteger()) {
11246     // See if we can simplify the input to this truncstore with knowledge that
11247     // only the low bits are being used.  For example:
11248     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11249     SDValue Shorter =
11250       GetDemandedBits(Value,
11251                       APInt::getLowBitsSet(
11252                         Value.getValueType().getScalarType().getSizeInBits(),
11253                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11254     AddToWorklist(Value.getNode());
11255     if (Shorter.getNode())
11256       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11257                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11258
11259     // Otherwise, see if we can simplify the operation with
11260     // SimplifyDemandedBits, which only works if the value has a single use.
11261     if (SimplifyDemandedBits(Value,
11262                         APInt::getLowBitsSet(
11263                           Value.getValueType().getScalarType().getSizeInBits(),
11264                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11265       return SDValue(N, 0);
11266   }
11267
11268   // If this is a load followed by a store to the same location, then the store
11269   // is dead/noop.
11270   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11271     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11272         ST->isUnindexed() && !ST->isVolatile() &&
11273         // There can't be any side effects between the load and store, such as
11274         // a call or store.
11275         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11276       // The store is dead, remove it.
11277       return Chain;
11278     }
11279   }
11280
11281   // If this is a store followed by a store with the same value to the same
11282   // location, then the store is dead/noop.
11283   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11284     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11285         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11286         ST1->isUnindexed() && !ST1->isVolatile()) {
11287       // The store is dead, remove it.
11288       return Chain;
11289     }
11290   }
11291
11292   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11293   // truncating store.  We can do this even if this is already a truncstore.
11294   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11295       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11296       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11297                             ST->getMemoryVT())) {
11298     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11299                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11300   }
11301
11302   // Only perform this optimization before the types are legal, because we
11303   // don't want to perform this optimization on every DAGCombine invocation.
11304   if (!LegalTypes) {
11305     bool EverChanged = false;
11306
11307     do {
11308       // There can be multiple store sequences on the same chain.
11309       // Keep trying to merge store sequences until we are unable to do so
11310       // or until we merge the last store on the chain.
11311       bool Changed = MergeConsecutiveStores(ST);
11312       EverChanged |= Changed;
11313       if (!Changed) break;
11314     } while (ST->getOpcode() != ISD::DELETED_NODE);
11315
11316     if (EverChanged)
11317       return SDValue(N, 0);
11318   }
11319
11320   return ReduceLoadOpStoreWidth(N);
11321 }
11322
11323 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11324   SDValue InVec = N->getOperand(0);
11325   SDValue InVal = N->getOperand(1);
11326   SDValue EltNo = N->getOperand(2);
11327   SDLoc dl(N);
11328
11329   // If the inserted element is an UNDEF, just use the input vector.
11330   if (InVal.getOpcode() == ISD::UNDEF)
11331     return InVec;
11332
11333   EVT VT = InVec.getValueType();
11334
11335   // If we can't generate a legal BUILD_VECTOR, exit
11336   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11337     return SDValue();
11338
11339   // Check that we know which element is being inserted
11340   if (!isa<ConstantSDNode>(EltNo))
11341     return SDValue();
11342   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11343
11344   // Canonicalize insert_vector_elt dag nodes.
11345   // Example:
11346   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11347   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11348   //
11349   // Do this only if the child insert_vector node has one use; also
11350   // do this only if indices are both constants and Idx1 < Idx0.
11351   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11352       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11353     unsigned OtherElt =
11354       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11355     if (Elt < OtherElt) {
11356       // Swap nodes.
11357       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11358                                   InVec.getOperand(0), InVal, EltNo);
11359       AddToWorklist(NewOp.getNode());
11360       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11361                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11362     }
11363   }
11364
11365   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11366   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11367   // vector elements.
11368   SmallVector<SDValue, 8> Ops;
11369   // Do not combine these two vectors if the output vector will not replace
11370   // the input vector.
11371   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11372     Ops.append(InVec.getNode()->op_begin(),
11373                InVec.getNode()->op_end());
11374   } else if (InVec.getOpcode() == ISD::UNDEF) {
11375     unsigned NElts = VT.getVectorNumElements();
11376     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11377   } else {
11378     return SDValue();
11379   }
11380
11381   // Insert the element
11382   if (Elt < Ops.size()) {
11383     // All the operands of BUILD_VECTOR must have the same type;
11384     // we enforce that here.
11385     EVT OpVT = Ops[0].getValueType();
11386     if (InVal.getValueType() != OpVT)
11387       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11388                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11389                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11390     Ops[Elt] = InVal;
11391   }
11392
11393   // Return the new vector
11394   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11395 }
11396
11397 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11398     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11399   EVT ResultVT = EVE->getValueType(0);
11400   EVT VecEltVT = InVecVT.getVectorElementType();
11401   unsigned Align = OriginalLoad->getAlignment();
11402   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11403       VecEltVT.getTypeForEVT(*DAG.getContext()));
11404
11405   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11406     return SDValue();
11407
11408   Align = NewAlign;
11409
11410   SDValue NewPtr = OriginalLoad->getBasePtr();
11411   SDValue Offset;
11412   EVT PtrType = NewPtr.getValueType();
11413   MachinePointerInfo MPI;
11414   SDLoc DL(EVE);
11415   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11416     int Elt = ConstEltNo->getZExtValue();
11417     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11418     if (TLI.isBigEndian())
11419       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11420     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11421     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11422   } else {
11423     Offset = DAG.getNode(
11424         ISD::MUL, DL, EltNo.getValueType(), EltNo,
11425         DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11426     if (TLI.isBigEndian())
11427       Offset = DAG.getNode(
11428           ISD::SUB, DL, EltNo.getValueType(),
11429           DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11430           Offset);
11431     MPI = OriginalLoad->getPointerInfo();
11432   }
11433   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11434
11435   // The replacement we need to do here is a little tricky: we need to
11436   // replace an extractelement of a load with a load.
11437   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11438   // Note that this replacement assumes that the extractvalue is the only
11439   // use of the load; that's okay because we don't want to perform this
11440   // transformation in other cases anyway.
11441   SDValue Load;
11442   SDValue Chain;
11443   if (ResultVT.bitsGT(VecEltVT)) {
11444     // If the result type of vextract is wider than the load, then issue an
11445     // extending load instead.
11446     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11447                                                   VecEltVT)
11448                                    ? ISD::ZEXTLOAD
11449                                    : ISD::EXTLOAD;
11450     Load = DAG.getExtLoad(
11451         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11452         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11453         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11454     Chain = Load.getValue(1);
11455   } else {
11456     Load = DAG.getLoad(
11457         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11458         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11459         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11460     Chain = Load.getValue(1);
11461     if (ResultVT.bitsLT(VecEltVT))
11462       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11463     else
11464       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11465   }
11466   WorklistRemover DeadNodes(*this);
11467   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11468   SDValue To[] = { Load, Chain };
11469   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11470   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11471   // worklist explicitly as well.
11472   AddToWorklist(Load.getNode());
11473   AddUsersToWorklist(Load.getNode()); // Add users too
11474   // Make sure to revisit this node to clean it up; it will usually be dead.
11475   AddToWorklist(EVE);
11476   ++OpsNarrowed;
11477   return SDValue(EVE, 0);
11478 }
11479
11480 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11481   // (vextract (scalar_to_vector val, 0) -> val
11482   SDValue InVec = N->getOperand(0);
11483   EVT VT = InVec.getValueType();
11484   EVT NVT = N->getValueType(0);
11485
11486   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11487     // Check if the result type doesn't match the inserted element type. A
11488     // SCALAR_TO_VECTOR may truncate the inserted element and the
11489     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11490     SDValue InOp = InVec.getOperand(0);
11491     if (InOp.getValueType() != NVT) {
11492       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11493       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11494     }
11495     return InOp;
11496   }
11497
11498   SDValue EltNo = N->getOperand(1);
11499   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11500
11501   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11502   // We only perform this optimization before the op legalization phase because
11503   // we may introduce new vector instructions which are not backed by TD
11504   // patterns. For example on AVX, extracting elements from a wide vector
11505   // without using extract_subvector. However, if we can find an underlying
11506   // scalar value, then we can always use that.
11507   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11508       && ConstEltNo) {
11509     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11510     int NumElem = VT.getVectorNumElements();
11511     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11512     // Find the new index to extract from.
11513     int OrigElt = SVOp->getMaskElt(Elt);
11514
11515     // Extracting an undef index is undef.
11516     if (OrigElt == -1)
11517       return DAG.getUNDEF(NVT);
11518
11519     // Select the right vector half to extract from.
11520     SDValue SVInVec;
11521     if (OrigElt < NumElem) {
11522       SVInVec = InVec->getOperand(0);
11523     } else {
11524       SVInVec = InVec->getOperand(1);
11525       OrigElt -= NumElem;
11526     }
11527
11528     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11529       SDValue InOp = SVInVec.getOperand(OrigElt);
11530       if (InOp.getValueType() != NVT) {
11531         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11532         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11533       }
11534
11535       return InOp;
11536     }
11537
11538     // FIXME: We should handle recursing on other vector shuffles and
11539     // scalar_to_vector here as well.
11540
11541     if (!LegalOperations) {
11542       EVT IndexTy = TLI.getVectorIdxTy();
11543       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11544                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11545     }
11546   }
11547
11548   bool BCNumEltsChanged = false;
11549   EVT ExtVT = VT.getVectorElementType();
11550   EVT LVT = ExtVT;
11551
11552   // If the result of load has to be truncated, then it's not necessarily
11553   // profitable.
11554   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11555     return SDValue();
11556
11557   if (InVec.getOpcode() == ISD::BITCAST) {
11558     // Don't duplicate a load with other uses.
11559     if (!InVec.hasOneUse())
11560       return SDValue();
11561
11562     EVT BCVT = InVec.getOperand(0).getValueType();
11563     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11564       return SDValue();
11565     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11566       BCNumEltsChanged = true;
11567     InVec = InVec.getOperand(0);
11568     ExtVT = BCVT.getVectorElementType();
11569   }
11570
11571   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11572   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11573       ISD::isNormalLoad(InVec.getNode()) &&
11574       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11575     SDValue Index = N->getOperand(1);
11576     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11577       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11578                                                            OrigLoad);
11579   }
11580
11581   // Perform only after legalization to ensure build_vector / vector_shuffle
11582   // optimizations have already been done.
11583   if (!LegalOperations) return SDValue();
11584
11585   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11586   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11587   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11588
11589   if (ConstEltNo) {
11590     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11591
11592     LoadSDNode *LN0 = nullptr;
11593     const ShuffleVectorSDNode *SVN = nullptr;
11594     if (ISD::isNormalLoad(InVec.getNode())) {
11595       LN0 = cast<LoadSDNode>(InVec);
11596     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11597                InVec.getOperand(0).getValueType() == ExtVT &&
11598                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11599       // Don't duplicate a load with other uses.
11600       if (!InVec.hasOneUse())
11601         return SDValue();
11602
11603       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11604     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11605       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11606       // =>
11607       // (load $addr+1*size)
11608
11609       // Don't duplicate a load with other uses.
11610       if (!InVec.hasOneUse())
11611         return SDValue();
11612
11613       // If the bit convert changed the number of elements, it is unsafe
11614       // to examine the mask.
11615       if (BCNumEltsChanged)
11616         return SDValue();
11617
11618       // Select the input vector, guarding against out of range extract vector.
11619       unsigned NumElems = VT.getVectorNumElements();
11620       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11621       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
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         InVec = InVec.getOperand(0);
11629       }
11630       if (ISD::isNormalLoad(InVec.getNode())) {
11631         LN0 = cast<LoadSDNode>(InVec);
11632         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11633         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11634       }
11635     }
11636
11637     // Make sure we found a non-volatile load and the extractelement is
11638     // the only use.
11639     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11640       return SDValue();
11641
11642     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11643     if (Elt == -1)
11644       return DAG.getUNDEF(LVT);
11645
11646     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11647   }
11648
11649   return SDValue();
11650 }
11651
11652 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11653 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11654   // We perform this optimization post type-legalization because
11655   // the type-legalizer often scalarizes integer-promoted vectors.
11656   // Performing this optimization before may create bit-casts which
11657   // will be type-legalized to complex code sequences.
11658   // We perform this optimization only before the operation legalizer because we
11659   // may introduce illegal operations.
11660   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11661     return SDValue();
11662
11663   unsigned NumInScalars = N->getNumOperands();
11664   SDLoc dl(N);
11665   EVT VT = N->getValueType(0);
11666
11667   // Check to see if this is a BUILD_VECTOR of a bunch of values
11668   // which come from any_extend or zero_extend nodes. If so, we can create
11669   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11670   // optimizations. We do not handle sign-extend because we can't fill the sign
11671   // using shuffles.
11672   EVT SourceType = MVT::Other;
11673   bool AllAnyExt = true;
11674
11675   for (unsigned i = 0; i != NumInScalars; ++i) {
11676     SDValue In = N->getOperand(i);
11677     // Ignore undef inputs.
11678     if (In.getOpcode() == ISD::UNDEF) continue;
11679
11680     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11681     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11682
11683     // Abort if the element is not an extension.
11684     if (!ZeroExt && !AnyExt) {
11685       SourceType = MVT::Other;
11686       break;
11687     }
11688
11689     // The input is a ZeroExt or AnyExt. Check the original type.
11690     EVT InTy = In.getOperand(0).getValueType();
11691
11692     // Check that all of the widened source types are the same.
11693     if (SourceType == MVT::Other)
11694       // First time.
11695       SourceType = InTy;
11696     else if (InTy != SourceType) {
11697       // Multiple income types. Abort.
11698       SourceType = MVT::Other;
11699       break;
11700     }
11701
11702     // Check if all of the extends are ANY_EXTENDs.
11703     AllAnyExt &= AnyExt;
11704   }
11705
11706   // In order to have valid types, all of the inputs must be extended from the
11707   // same source type and all of the inputs must be any or zero extend.
11708   // Scalar sizes must be a power of two.
11709   EVT OutScalarTy = VT.getScalarType();
11710   bool ValidTypes = SourceType != MVT::Other &&
11711                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11712                  isPowerOf2_32(SourceType.getSizeInBits());
11713
11714   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11715   // turn into a single shuffle instruction.
11716   if (!ValidTypes)
11717     return SDValue();
11718
11719   bool isLE = TLI.isLittleEndian();
11720   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11721   assert(ElemRatio > 1 && "Invalid element size ratio");
11722   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11723                                DAG.getConstant(0, SDLoc(N), SourceType);
11724
11725   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11726   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11727
11728   // Populate the new build_vector
11729   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11730     SDValue Cast = N->getOperand(i);
11731     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11732             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11733             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11734     SDValue In;
11735     if (Cast.getOpcode() == ISD::UNDEF)
11736       In = DAG.getUNDEF(SourceType);
11737     else
11738       In = Cast->getOperand(0);
11739     unsigned Index = isLE ? (i * ElemRatio) :
11740                             (i * ElemRatio + (ElemRatio - 1));
11741
11742     assert(Index < Ops.size() && "Invalid index");
11743     Ops[Index] = In;
11744   }
11745
11746   // The type of the new BUILD_VECTOR node.
11747   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11748   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11749          "Invalid vector size");
11750   // Check if the new vector type is legal.
11751   if (!isTypeLegal(VecVT)) return SDValue();
11752
11753   // Make the new BUILD_VECTOR.
11754   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11755
11756   // The new BUILD_VECTOR node has the potential to be further optimized.
11757   AddToWorklist(BV.getNode());
11758   // Bitcast to the desired type.
11759   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11760 }
11761
11762 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11763   EVT VT = N->getValueType(0);
11764
11765   unsigned NumInScalars = N->getNumOperands();
11766   SDLoc dl(N);
11767
11768   EVT SrcVT = MVT::Other;
11769   unsigned Opcode = ISD::DELETED_NODE;
11770   unsigned NumDefs = 0;
11771
11772   for (unsigned i = 0; i != NumInScalars; ++i) {
11773     SDValue In = N->getOperand(i);
11774     unsigned Opc = In.getOpcode();
11775
11776     if (Opc == ISD::UNDEF)
11777       continue;
11778
11779     // If all scalar values are floats and converted from integers.
11780     if (Opcode == ISD::DELETED_NODE &&
11781         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11782       Opcode = Opc;
11783     }
11784
11785     if (Opc != Opcode)
11786       return SDValue();
11787
11788     EVT InVT = In.getOperand(0).getValueType();
11789
11790     // If all scalar values are typed differently, bail out. It's chosen to
11791     // simplify BUILD_VECTOR of integer types.
11792     if (SrcVT == MVT::Other)
11793       SrcVT = InVT;
11794     if (SrcVT != InVT)
11795       return SDValue();
11796     NumDefs++;
11797   }
11798
11799   // If the vector has just one element defined, it's not worth to fold it into
11800   // a vectorized one.
11801   if (NumDefs < 2)
11802     return SDValue();
11803
11804   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11805          && "Should only handle conversion from integer to float.");
11806   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11807
11808   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11809
11810   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11811     return SDValue();
11812
11813   // Just because the floating-point vector type is legal does not necessarily
11814   // mean that the corresponding integer vector type is.
11815   if (!isTypeLegal(NVT))
11816     return SDValue();
11817
11818   SmallVector<SDValue, 8> Opnds;
11819   for (unsigned i = 0; i != NumInScalars; ++i) {
11820     SDValue In = N->getOperand(i);
11821
11822     if (In.getOpcode() == ISD::UNDEF)
11823       Opnds.push_back(DAG.getUNDEF(SrcVT));
11824     else
11825       Opnds.push_back(In.getOperand(0));
11826   }
11827   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11828   AddToWorklist(BV.getNode());
11829
11830   return DAG.getNode(Opcode, dl, VT, BV);
11831 }
11832
11833 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11834   unsigned NumInScalars = N->getNumOperands();
11835   SDLoc dl(N);
11836   EVT VT = N->getValueType(0);
11837
11838   // A vector built entirely of undefs is undef.
11839   if (ISD::allOperandsUndef(N))
11840     return DAG.getUNDEF(VT);
11841
11842   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11843     return V;
11844
11845   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11846     return V;
11847
11848   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11849   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11850   // at most two distinct vectors, turn this into a shuffle node.
11851
11852   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11853   if (!isTypeLegal(VT))
11854     return SDValue();
11855
11856   // May only combine to shuffle after legalize if shuffle is legal.
11857   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11858     return SDValue();
11859
11860   SDValue VecIn1, VecIn2;
11861   bool UsesZeroVector = false;
11862   for (unsigned i = 0; i != NumInScalars; ++i) {
11863     SDValue Op = N->getOperand(i);
11864     // Ignore undef inputs.
11865     if (Op.getOpcode() == ISD::UNDEF) continue;
11866
11867     // See if we can combine this build_vector into a blend with a zero vector.
11868     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11869         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11870         (Op.getOpcode() == ISD::ConstantFP &&
11871         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11872       UsesZeroVector = true;
11873       continue;
11874     }
11875
11876     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11877     // constant index, bail out.
11878     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11879         !isa<ConstantSDNode>(Op.getOperand(1))) {
11880       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11881       break;
11882     }
11883
11884     // We allow up to two distinct input vectors.
11885     SDValue ExtractedFromVec = Op.getOperand(0);
11886     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11887       continue;
11888
11889     if (!VecIn1.getNode()) {
11890       VecIn1 = ExtractedFromVec;
11891     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11892       VecIn2 = ExtractedFromVec;
11893     } else {
11894       // Too many inputs.
11895       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11896       break;
11897     }
11898   }
11899
11900   // If everything is good, we can make a shuffle operation.
11901   if (VecIn1.getNode()) {
11902     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11903     SmallVector<int, 8> Mask;
11904     for (unsigned i = 0; i != NumInScalars; ++i) {
11905       unsigned Opcode = N->getOperand(i).getOpcode();
11906       if (Opcode == ISD::UNDEF) {
11907         Mask.push_back(-1);
11908         continue;
11909       }
11910
11911       // Operands can also be zero.
11912       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11913         assert(UsesZeroVector &&
11914                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11915                "Unexpected node found!");
11916         Mask.push_back(NumInScalars+i);
11917         continue;
11918       }
11919
11920       // If extracting from the first vector, just use the index directly.
11921       SDValue Extract = N->getOperand(i);
11922       SDValue ExtVal = Extract.getOperand(1);
11923       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11924       if (Extract.getOperand(0) == VecIn1) {
11925         Mask.push_back(ExtIndex);
11926         continue;
11927       }
11928
11929       // Otherwise, use InIdx + InputVecSize
11930       Mask.push_back(InNumElements + ExtIndex);
11931     }
11932
11933     // Avoid introducing illegal shuffles with zero.
11934     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11935       return SDValue();
11936
11937     // We can't generate a shuffle node with mismatched input and output types.
11938     // Attempt to transform a single input vector to the correct type.
11939     if ((VT != VecIn1.getValueType())) {
11940       // If the input vector type has a different base type to the output
11941       // vector type, bail out.
11942       EVT VTElemType = VT.getVectorElementType();
11943       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11944           (VecIn2.getNode() &&
11945            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11946         return SDValue();
11947
11948       // If the input vector is too small, widen it.
11949       // We only support widening of vectors which are half the size of the
11950       // output registers. For example XMM->YMM widening on X86 with AVX.
11951       EVT VecInT = VecIn1.getValueType();
11952       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11953         // If we only have one small input, widen it by adding undef values.
11954         if (!VecIn2.getNode())
11955           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11956                                DAG.getUNDEF(VecIn1.getValueType()));
11957         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11958           // If we have two small inputs of the same type, try to concat them.
11959           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11960           VecIn2 = SDValue(nullptr, 0);
11961         } else
11962           return SDValue();
11963       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11964         // If the input vector is too large, try to split it.
11965         // We don't support having two input vectors that are too large.
11966         // If the zero vector was used, we can not split the vector,
11967         // since we'd need 3 inputs.
11968         if (UsesZeroVector || VecIn2.getNode())
11969           return SDValue();
11970
11971         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11972           return SDValue();
11973
11974         // Try to replace VecIn1 with two extract_subvectors
11975         // No need to update the masks, they should still be correct.
11976         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11977           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11978         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11979           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11980       } else
11981         return SDValue();
11982     }
11983
11984     if (UsesZeroVector)
11985       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11986                                 DAG.getConstantFP(0.0, dl, VT);
11987     else
11988       // If VecIn2 is unused then change it to undef.
11989       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11990
11991     // Check that we were able to transform all incoming values to the same
11992     // type.
11993     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11994         VecIn1.getValueType() != VT)
11995           return SDValue();
11996
11997     // Return the new VECTOR_SHUFFLE node.
11998     SDValue Ops[2];
11999     Ops[0] = VecIn1;
12000     Ops[1] = VecIn2;
12001     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12002   }
12003
12004   return SDValue();
12005 }
12006
12007 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12009   EVT OpVT = N->getOperand(0).getValueType();
12010
12011   // If the operands are legal vectors, leave them alone.
12012   if (TLI.isTypeLegal(OpVT))
12013     return SDValue();
12014
12015   SDLoc DL(N);
12016   EVT VT = N->getValueType(0);
12017   SmallVector<SDValue, 8> Ops;
12018
12019   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12020   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12021
12022   // Keep track of what we encounter.
12023   bool AnyInteger = false;
12024   bool AnyFP = false;
12025   for (const SDValue &Op : N->ops()) {
12026     if (ISD::BITCAST == Op.getOpcode() &&
12027         !Op.getOperand(0).getValueType().isVector())
12028       Ops.push_back(Op.getOperand(0));
12029     else if (ISD::UNDEF == Op.getOpcode())
12030       Ops.push_back(ScalarUndef);
12031     else
12032       return SDValue();
12033
12034     // Note whether we encounter an integer or floating point scalar.
12035     // If it's neither, bail out, it could be something weird like x86mmx.
12036     EVT LastOpVT = Ops.back().getValueType();
12037     if (LastOpVT.isFloatingPoint())
12038       AnyFP = true;
12039     else if (LastOpVT.isInteger())
12040       AnyInteger = true;
12041     else
12042       return SDValue();
12043   }
12044
12045   // If any of the operands is a floating point scalar bitcast to a vector,
12046   // use floating point types throughout, and bitcast everything.  
12047   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12048   if (AnyFP) {
12049     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12050     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12051     if (AnyInteger) {
12052       for (SDValue &Op : Ops) {
12053         if (Op.getValueType() == SVT)
12054           continue;
12055         if (Op.getOpcode() == ISD::UNDEF)
12056           Op = ScalarUndef;
12057         else
12058           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12059       }
12060     }
12061   }
12062
12063   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12064                                VT.getSizeInBits() / SVT.getSizeInBits());
12065   return DAG.getNode(ISD::BITCAST, DL, VT,
12066                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12067 }
12068
12069 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12070   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12071   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12072   // inputs come from at most two distinct vectors, turn this into a shuffle
12073   // node.
12074
12075   // If we only have one input vector, we don't need to do any concatenation.
12076   if (N->getNumOperands() == 1)
12077     return N->getOperand(0);
12078
12079   // Check if all of the operands are undefs.
12080   EVT VT = N->getValueType(0);
12081   if (ISD::allOperandsUndef(N))
12082     return DAG.getUNDEF(VT);
12083
12084   // Optimize concat_vectors where all but the first of the vectors are undef.
12085   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12086         return Op.getOpcode() == ISD::UNDEF;
12087       })) {
12088     SDValue In = N->getOperand(0);
12089     assert(In.getValueType().isVector() && "Must concat vectors");
12090
12091     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12092     if (In->getOpcode() == ISD::BITCAST &&
12093         !In->getOperand(0)->getValueType(0).isVector()) {
12094       SDValue Scalar = In->getOperand(0);
12095
12096       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12097       // look through the trunc so we can still do the transform:
12098       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12099       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12100           !TLI.isTypeLegal(Scalar.getValueType()) &&
12101           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12102         Scalar = Scalar->getOperand(0);
12103
12104       EVT SclTy = Scalar->getValueType(0);
12105
12106       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12107         return SDValue();
12108
12109       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12110                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12111       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12112         return SDValue();
12113
12114       SDLoc dl = SDLoc(N);
12115       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12116       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12117     }
12118   }
12119
12120   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12121   // We have already tested above for an UNDEF only concatenation.
12122   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12123   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12124   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12125     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12126   };
12127   bool AllBuildVectorsOrUndefs =
12128       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12129   if (AllBuildVectorsOrUndefs) {
12130     SmallVector<SDValue, 8> Opnds;
12131     EVT SVT = VT.getScalarType();
12132
12133     EVT MinVT = SVT;
12134     if (!SVT.isFloatingPoint()) {
12135       // If BUILD_VECTOR are from built from integer, they may have different
12136       // operand types. Get the smallest type and truncate all operands to it.
12137       bool FoundMinVT = false;
12138       for (const SDValue &Op : N->ops())
12139         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12140           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12141           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12142           FoundMinVT = true;
12143         }
12144       assert(FoundMinVT && "Concat vector type mismatch");
12145     }
12146
12147     for (const SDValue &Op : N->ops()) {
12148       EVT OpVT = Op.getValueType();
12149       unsigned NumElts = OpVT.getVectorNumElements();
12150
12151       if (ISD::UNDEF == Op.getOpcode())
12152         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12153
12154       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12155         if (SVT.isFloatingPoint()) {
12156           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12157           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12158         } else {
12159           for (unsigned i = 0; i != NumElts; ++i)
12160             Opnds.push_back(
12161                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12162         }
12163       }
12164     }
12165
12166     assert(VT.getVectorNumElements() == Opnds.size() &&
12167            "Concat vector type mismatch");
12168     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12169   }
12170
12171   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12172   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12173     return V;
12174
12175   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12176   // nodes often generate nop CONCAT_VECTOR nodes.
12177   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12178   // place the incoming vectors at the exact same location.
12179   SDValue SingleSource = SDValue();
12180   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12181
12182   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12183     SDValue Op = N->getOperand(i);
12184
12185     if (Op.getOpcode() == ISD::UNDEF)
12186       continue;
12187
12188     // Check if this is the identity extract:
12189     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12190       return SDValue();
12191
12192     // Find the single incoming vector for the extract_subvector.
12193     if (SingleSource.getNode()) {
12194       if (Op.getOperand(0) != SingleSource)
12195         return SDValue();
12196     } else {
12197       SingleSource = Op.getOperand(0);
12198
12199       // Check the source type is the same as the type of the result.
12200       // If not, this concat may extend the vector, so we can not
12201       // optimize it away.
12202       if (SingleSource.getValueType() != N->getValueType(0))
12203         return SDValue();
12204     }
12205
12206     unsigned IdentityIndex = i * PartNumElem;
12207     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12208     // The extract index must be constant.
12209     if (!CS)
12210       return SDValue();
12211
12212     // Check that we are reading from the identity index.
12213     if (CS->getZExtValue() != IdentityIndex)
12214       return SDValue();
12215   }
12216
12217   if (SingleSource.getNode())
12218     return SingleSource;
12219
12220   return SDValue();
12221 }
12222
12223 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12224   EVT NVT = N->getValueType(0);
12225   SDValue V = N->getOperand(0);
12226
12227   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12228     // Combine:
12229     //    (extract_subvec (concat V1, V2, ...), i)
12230     // Into:
12231     //    Vi if possible
12232     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12233     // type.
12234     if (V->getOperand(0).getValueType() != NVT)
12235       return SDValue();
12236     unsigned Idx = N->getConstantOperandVal(1);
12237     unsigned NumElems = NVT.getVectorNumElements();
12238     assert((Idx % NumElems) == 0 &&
12239            "IDX in concat is not a multiple of the result vector length.");
12240     return V->getOperand(Idx / NumElems);
12241   }
12242
12243   // Skip bitcasting
12244   if (V->getOpcode() == ISD::BITCAST)
12245     V = V.getOperand(0);
12246
12247   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12248     SDLoc dl(N);
12249     // Handle only simple case where vector being inserted and vector
12250     // being extracted are of same type, and are half size of larger vectors.
12251     EVT BigVT = V->getOperand(0).getValueType();
12252     EVT SmallVT = V->getOperand(1).getValueType();
12253     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12254       return SDValue();
12255
12256     // Only handle cases where both indexes are constants with the same type.
12257     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12258     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12259
12260     if (InsIdx && ExtIdx &&
12261         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12262         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12263       // Combine:
12264       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12265       // Into:
12266       //    indices are equal or bit offsets are equal => V1
12267       //    otherwise => (extract_subvec V1, ExtIdx)
12268       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12269           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12270         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12271       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12272                          DAG.getNode(ISD::BITCAST, dl,
12273                                      N->getOperand(0).getValueType(),
12274                                      V->getOperand(0)), N->getOperand(1));
12275     }
12276   }
12277
12278   return SDValue();
12279 }
12280
12281 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12282                                                  SDValue V, SelectionDAG &DAG) {
12283   SDLoc DL(V);
12284   EVT VT = V.getValueType();
12285
12286   switch (V.getOpcode()) {
12287   default:
12288     return V;
12289
12290   case ISD::CONCAT_VECTORS: {
12291     EVT OpVT = V->getOperand(0).getValueType();
12292     int OpSize = OpVT.getVectorNumElements();
12293     SmallBitVector OpUsedElements(OpSize, false);
12294     bool FoundSimplification = false;
12295     SmallVector<SDValue, 4> NewOps;
12296     NewOps.reserve(V->getNumOperands());
12297     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12298       SDValue Op = V->getOperand(i);
12299       bool OpUsed = false;
12300       for (int j = 0; j < OpSize; ++j)
12301         if (UsedElements[i * OpSize + j]) {
12302           OpUsedElements[j] = true;
12303           OpUsed = true;
12304         }
12305       NewOps.push_back(
12306           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12307                  : DAG.getUNDEF(OpVT));
12308       FoundSimplification |= Op == NewOps.back();
12309       OpUsedElements.reset();
12310     }
12311     if (FoundSimplification)
12312       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12313     return V;
12314   }
12315
12316   case ISD::INSERT_SUBVECTOR: {
12317     SDValue BaseV = V->getOperand(0);
12318     SDValue SubV = V->getOperand(1);
12319     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12320     if (!IdxN)
12321       return V;
12322
12323     int SubSize = SubV.getValueType().getVectorNumElements();
12324     int Idx = IdxN->getZExtValue();
12325     bool SubVectorUsed = false;
12326     SmallBitVector SubUsedElements(SubSize, false);
12327     for (int i = 0; i < SubSize; ++i)
12328       if (UsedElements[i + Idx]) {
12329         SubVectorUsed = true;
12330         SubUsedElements[i] = true;
12331         UsedElements[i + Idx] = false;
12332       }
12333
12334     // Now recurse on both the base and sub vectors.
12335     SDValue SimplifiedSubV =
12336         SubVectorUsed
12337             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12338             : DAG.getUNDEF(SubV.getValueType());
12339     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12340     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12341       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12342                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12343     return V;
12344   }
12345   }
12346 }
12347
12348 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12349                                        SDValue N1, SelectionDAG &DAG) {
12350   EVT VT = SVN->getValueType(0);
12351   int NumElts = VT.getVectorNumElements();
12352   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12353   for (int M : SVN->getMask())
12354     if (M >= 0 && M < NumElts)
12355       N0UsedElements[M] = true;
12356     else if (M >= NumElts)
12357       N1UsedElements[M - NumElts] = true;
12358
12359   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12360   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12361   if (S0 == N0 && S1 == N1)
12362     return SDValue();
12363
12364   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12365 }
12366
12367 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12368 // or turn a shuffle of a single concat into simpler shuffle then concat.
12369 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12370   EVT VT = N->getValueType(0);
12371   unsigned NumElts = VT.getVectorNumElements();
12372
12373   SDValue N0 = N->getOperand(0);
12374   SDValue N1 = N->getOperand(1);
12375   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12376
12377   SmallVector<SDValue, 4> Ops;
12378   EVT ConcatVT = N0.getOperand(0).getValueType();
12379   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12380   unsigned NumConcats = NumElts / NumElemsPerConcat;
12381
12382   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12383   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12384   // half vector elements.
12385   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12386       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12387                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12388     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12389                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12390     N1 = DAG.getUNDEF(ConcatVT);
12391     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12392   }
12393
12394   // Look at every vector that's inserted. We're looking for exact
12395   // subvector-sized copies from a concatenated vector
12396   for (unsigned I = 0; I != NumConcats; ++I) {
12397     // Make sure we're dealing with a copy.
12398     unsigned Begin = I * NumElemsPerConcat;
12399     bool AllUndef = true, NoUndef = true;
12400     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12401       if (SVN->getMaskElt(J) >= 0)
12402         AllUndef = false;
12403       else
12404         NoUndef = false;
12405     }
12406
12407     if (NoUndef) {
12408       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12409         return SDValue();
12410
12411       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12412         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12413           return SDValue();
12414
12415       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12416       if (FirstElt < N0.getNumOperands())
12417         Ops.push_back(N0.getOperand(FirstElt));
12418       else
12419         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12420
12421     } else if (AllUndef) {
12422       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12423     } else { // Mixed with general masks and undefs, can't do optimization.
12424       return SDValue();
12425     }
12426   }
12427
12428   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12429 }
12430
12431 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12432   EVT VT = N->getValueType(0);
12433   unsigned NumElts = VT.getVectorNumElements();
12434
12435   SDValue N0 = N->getOperand(0);
12436   SDValue N1 = N->getOperand(1);
12437
12438   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12439
12440   // Canonicalize shuffle undef, undef -> undef
12441   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12442     return DAG.getUNDEF(VT);
12443
12444   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12445
12446   // Canonicalize shuffle v, v -> v, undef
12447   if (N0 == N1) {
12448     SmallVector<int, 8> NewMask;
12449     for (unsigned i = 0; i != NumElts; ++i) {
12450       int Idx = SVN->getMaskElt(i);
12451       if (Idx >= (int)NumElts) Idx -= NumElts;
12452       NewMask.push_back(Idx);
12453     }
12454     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12455                                 &NewMask[0]);
12456   }
12457
12458   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12459   if (N0.getOpcode() == ISD::UNDEF) {
12460     SmallVector<int, 8> NewMask;
12461     for (unsigned i = 0; i != NumElts; ++i) {
12462       int Idx = SVN->getMaskElt(i);
12463       if (Idx >= 0) {
12464         if (Idx >= (int)NumElts)
12465           Idx -= NumElts;
12466         else
12467           Idx = -1; // remove reference to lhs
12468       }
12469       NewMask.push_back(Idx);
12470     }
12471     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12472                                 &NewMask[0]);
12473   }
12474
12475   // Remove references to rhs if it is undef
12476   if (N1.getOpcode() == ISD::UNDEF) {
12477     bool Changed = false;
12478     SmallVector<int, 8> NewMask;
12479     for (unsigned i = 0; i != NumElts; ++i) {
12480       int Idx = SVN->getMaskElt(i);
12481       if (Idx >= (int)NumElts) {
12482         Idx = -1;
12483         Changed = true;
12484       }
12485       NewMask.push_back(Idx);
12486     }
12487     if (Changed)
12488       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12489   }
12490
12491   // If it is a splat, check if the argument vector is another splat or a
12492   // build_vector.
12493   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12494     SDNode *V = N0.getNode();
12495
12496     // If this is a bit convert that changes the element type of the vector but
12497     // not the number of vector elements, look through it.  Be careful not to
12498     // look though conversions that change things like v4f32 to v2f64.
12499     if (V->getOpcode() == ISD::BITCAST) {
12500       SDValue ConvInput = V->getOperand(0);
12501       if (ConvInput.getValueType().isVector() &&
12502           ConvInput.getValueType().getVectorNumElements() == NumElts)
12503         V = ConvInput.getNode();
12504     }
12505
12506     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12507       assert(V->getNumOperands() == NumElts &&
12508              "BUILD_VECTOR has wrong number of operands");
12509       SDValue Base;
12510       bool AllSame = true;
12511       for (unsigned i = 0; i != NumElts; ++i) {
12512         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12513           Base = V->getOperand(i);
12514           break;
12515         }
12516       }
12517       // Splat of <u, u, u, u>, return <u, u, u, u>
12518       if (!Base.getNode())
12519         return N0;
12520       for (unsigned i = 0; i != NumElts; ++i) {
12521         if (V->getOperand(i) != Base) {
12522           AllSame = false;
12523           break;
12524         }
12525       }
12526       // Splat of <x, x, x, x>, return <x, x, x, x>
12527       if (AllSame)
12528         return N0;
12529
12530       // Canonicalize any other splat as a build_vector.
12531       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12532       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12533       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12534                                   V->getValueType(0), Ops);
12535
12536       // We may have jumped through bitcasts, so the type of the
12537       // BUILD_VECTOR may not match the type of the shuffle.
12538       if (V->getValueType(0) != VT)
12539         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12540       return NewBV;
12541     }
12542   }
12543
12544   // There are various patterns used to build up a vector from smaller vectors,
12545   // subvectors, or elements. Scan chains of these and replace unused insertions
12546   // or components with undef.
12547   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12548     return S;
12549
12550   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12551       Level < AfterLegalizeVectorOps &&
12552       (N1.getOpcode() == ISD::UNDEF ||
12553       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12554        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12555     SDValue V = partitionShuffleOfConcats(N, DAG);
12556
12557     if (V.getNode())
12558       return V;
12559   }
12560
12561   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12562   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12563   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12564     SmallVector<SDValue, 8> Ops;
12565     for (int M : SVN->getMask()) {
12566       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12567       if (M >= 0) {
12568         int Idx = M % NumElts;
12569         SDValue &S = (M < (int)NumElts ? N0 : N1);
12570         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12571           Op = S.getOperand(Idx);
12572         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12573           if (Idx == 0)
12574             Op = S.getOperand(0);
12575         } else {
12576           // Operand can't be combined - bail out.
12577           break;
12578         }
12579       }
12580       Ops.push_back(Op);
12581     }
12582     if (Ops.size() == VT.getVectorNumElements()) {
12583       // BUILD_VECTOR requires all inputs to be of the same type, find the
12584       // maximum type and extend them all.
12585       EVT SVT = VT.getScalarType();
12586       if (SVT.isInteger())
12587         for (SDValue &Op : Ops)
12588           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12589       if (SVT != VT.getScalarType())
12590         for (SDValue &Op : Ops)
12591           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12592                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12593                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12594       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12595     }
12596   }
12597
12598   // If this shuffle only has a single input that is a bitcasted shuffle,
12599   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12600   // back to their original types.
12601   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12602       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12603       TLI.isTypeLegal(VT)) {
12604
12605     // Peek through the bitcast only if there is one user.
12606     SDValue BC0 = N0;
12607     while (BC0.getOpcode() == ISD::BITCAST) {
12608       if (!BC0.hasOneUse())
12609         break;
12610       BC0 = BC0.getOperand(0);
12611     }
12612
12613     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12614       if (Scale == 1)
12615         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12616
12617       SmallVector<int, 8> NewMask;
12618       for (int M : Mask)
12619         for (int s = 0; s != Scale; ++s)
12620           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12621       return NewMask;
12622     };
12623
12624     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12625       EVT SVT = VT.getScalarType();
12626       EVT InnerVT = BC0->getValueType(0);
12627       EVT InnerSVT = InnerVT.getScalarType();
12628
12629       // Determine which shuffle works with the smaller scalar type.
12630       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12631       EVT ScaleSVT = ScaleVT.getScalarType();
12632
12633       if (TLI.isTypeLegal(ScaleVT) &&
12634           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12635           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12636
12637         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12638         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12639
12640         // Scale the shuffle masks to the smaller scalar type.
12641         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12642         SmallVector<int, 8> InnerMask =
12643             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12644         SmallVector<int, 8> OuterMask =
12645             ScaleShuffleMask(SVN->getMask(), OuterScale);
12646
12647         // Merge the shuffle masks.
12648         SmallVector<int, 8> NewMask;
12649         for (int M : OuterMask)
12650           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12651
12652         // Test for shuffle mask legality over both commutations.
12653         SDValue SV0 = BC0->getOperand(0);
12654         SDValue SV1 = BC0->getOperand(1);
12655         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12656         if (!LegalMask) {
12657           std::swap(SV0, SV1);
12658           ShuffleVectorSDNode::commuteMask(NewMask);
12659           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12660         }
12661
12662         if (LegalMask) {
12663           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12664           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12665           return DAG.getNode(
12666               ISD::BITCAST, SDLoc(N), VT,
12667               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12668         }
12669       }
12670     }
12671   }
12672
12673   // Canonicalize shuffles according to rules:
12674   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12675   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12676   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12677   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12678       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12679       TLI.isTypeLegal(VT)) {
12680     // The incoming shuffle must be of the same type as the result of the
12681     // current shuffle.
12682     assert(N1->getOperand(0).getValueType() == VT &&
12683            "Shuffle types don't match");
12684
12685     SDValue SV0 = N1->getOperand(0);
12686     SDValue SV1 = N1->getOperand(1);
12687     bool HasSameOp0 = N0 == SV0;
12688     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12689     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12690       // Commute the operands of this shuffle so that next rule
12691       // will trigger.
12692       return DAG.getCommutedVectorShuffle(*SVN);
12693   }
12694
12695   // Try to fold according to rules:
12696   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12697   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12698   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12699   // Don't try to fold shuffles with illegal type.
12700   // Only fold if this shuffle is the only user of the other shuffle.
12701   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12702       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12703     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12704
12705     // The incoming shuffle must be of the same type as the result of the
12706     // current shuffle.
12707     assert(OtherSV->getOperand(0).getValueType() == VT &&
12708            "Shuffle types don't match");
12709
12710     SDValue SV0, SV1;
12711     SmallVector<int, 4> Mask;
12712     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12713     // operand, and SV1 as the second operand.
12714     for (unsigned i = 0; i != NumElts; ++i) {
12715       int Idx = SVN->getMaskElt(i);
12716       if (Idx < 0) {
12717         // Propagate Undef.
12718         Mask.push_back(Idx);
12719         continue;
12720       }
12721
12722       SDValue CurrentVec;
12723       if (Idx < (int)NumElts) {
12724         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12725         // shuffle mask to identify which vector is actually referenced.
12726         Idx = OtherSV->getMaskElt(Idx);
12727         if (Idx < 0) {
12728           // Propagate Undef.
12729           Mask.push_back(Idx);
12730           continue;
12731         }
12732
12733         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12734                                            : OtherSV->getOperand(1);
12735       } else {
12736         // This shuffle index references an element within N1.
12737         CurrentVec = N1;
12738       }
12739
12740       // Simple case where 'CurrentVec' is UNDEF.
12741       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12742         Mask.push_back(-1);
12743         continue;
12744       }
12745
12746       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12747       // will be the first or second operand of the combined shuffle.
12748       Idx = Idx % NumElts;
12749       if (!SV0.getNode() || SV0 == CurrentVec) {
12750         // Ok. CurrentVec is the left hand side.
12751         // Update the mask accordingly.
12752         SV0 = CurrentVec;
12753         Mask.push_back(Idx);
12754         continue;
12755       }
12756
12757       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12758       if (SV1.getNode() && SV1 != CurrentVec)
12759         return SDValue();
12760
12761       // Ok. CurrentVec is the right hand side.
12762       // Update the mask accordingly.
12763       SV1 = CurrentVec;
12764       Mask.push_back(Idx + NumElts);
12765     }
12766
12767     // Check if all indices in Mask are Undef. In case, propagate Undef.
12768     bool isUndefMask = true;
12769     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12770       isUndefMask &= Mask[i] < 0;
12771
12772     if (isUndefMask)
12773       return DAG.getUNDEF(VT);
12774
12775     if (!SV0.getNode())
12776       SV0 = DAG.getUNDEF(VT);
12777     if (!SV1.getNode())
12778       SV1 = DAG.getUNDEF(VT);
12779
12780     // Avoid introducing shuffles with illegal mask.
12781     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12782       ShuffleVectorSDNode::commuteMask(Mask);
12783
12784       if (!TLI.isShuffleMaskLegal(Mask, VT))
12785         return SDValue();
12786
12787       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12788       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12789       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12790       std::swap(SV0, SV1);
12791     }
12792
12793     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12794     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12795     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12796     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12797   }
12798
12799   return SDValue();
12800 }
12801
12802 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12803   SDValue InVal = N->getOperand(0);
12804   EVT VT = N->getValueType(0);
12805
12806   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12807   // with a VECTOR_SHUFFLE.
12808   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12809     SDValue InVec = InVal->getOperand(0);
12810     SDValue EltNo = InVal->getOperand(1);
12811
12812     // FIXME: We could support implicit truncation if the shuffle can be
12813     // scaled to a smaller vector scalar type.
12814     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12815     if (C0 && VT == InVec.getValueType() &&
12816         VT.getScalarType() == InVal.getValueType()) {
12817       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12818       int Elt = C0->getZExtValue();
12819       NewMask[0] = Elt;
12820
12821       if (TLI.isShuffleMaskLegal(NewMask, VT))
12822         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12823                                     NewMask);
12824     }
12825   }
12826
12827   return SDValue();
12828 }
12829
12830 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12831   SDValue N0 = N->getOperand(0);
12832   SDValue N2 = N->getOperand(2);
12833
12834   // If the input vector is a concatenation, and the insert replaces
12835   // one of the halves, we can optimize into a single concat_vectors.
12836   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12837       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12838     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12839     EVT VT = N->getValueType(0);
12840
12841     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12842     // (concat_vectors Z, Y)
12843     if (InsIdx == 0)
12844       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12845                          N->getOperand(1), N0.getOperand(1));
12846
12847     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12848     // (concat_vectors X, Z)
12849     if (InsIdx == VT.getVectorNumElements()/2)
12850       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12851                          N0.getOperand(0), N->getOperand(1));
12852   }
12853
12854   return SDValue();
12855 }
12856
12857 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12858   SDValue N0 = N->getOperand(0);
12859
12860   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12861   if (N0->getOpcode() == ISD::FP16_TO_FP)
12862     return N0->getOperand(0);
12863
12864   return SDValue();
12865 }
12866
12867 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12868 /// with the destination vector and a zero vector.
12869 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12870 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12871 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12872   EVT VT = N->getValueType(0);
12873   SDValue LHS = N->getOperand(0);
12874   SDValue RHS = N->getOperand(1);
12875   SDLoc dl(N);
12876
12877   // Make sure we're not running after operation legalization where it 
12878   // may have custom lowered the vector shuffles.
12879   if (LegalOperations)
12880     return SDValue();
12881
12882   if (N->getOpcode() != ISD::AND)
12883     return SDValue();
12884
12885   if (RHS.getOpcode() == ISD::BITCAST)
12886     RHS = RHS.getOperand(0);
12887
12888   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12889     SmallVector<int, 8> Indices;
12890     unsigned NumElts = RHS.getNumOperands();
12891
12892     for (unsigned i = 0; i != NumElts; ++i) {
12893       SDValue Elt = RHS.getOperand(i);
12894       if (!isa<ConstantSDNode>(Elt))
12895         return SDValue();
12896
12897       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12898         Indices.push_back(i);
12899       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12900         Indices.push_back(NumElts+i);
12901       else
12902         return SDValue();
12903     }
12904
12905     // Let's see if the target supports this vector_shuffle.
12906     EVT RVT = RHS.getValueType();
12907     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12908       return SDValue();
12909
12910     // Return the new VECTOR_SHUFFLE node.
12911     EVT EltVT = RVT.getVectorElementType();
12912     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12913                                    DAG.getConstant(0, dl, EltVT));
12914     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12915     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12916     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12917     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12918   }
12919
12920   return SDValue();
12921 }
12922
12923 /// Visit a binary vector operation, like ADD.
12924 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12925   assert(N->getValueType(0).isVector() &&
12926          "SimplifyVBinOp only works on vectors!");
12927
12928   SDValue LHS = N->getOperand(0);
12929   SDValue RHS = N->getOperand(1);
12930
12931   if (SDValue Shuffle = XformToShuffleWithZero(N))
12932     return Shuffle;
12933
12934   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12935   // this operation.
12936   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12937       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12938     // Check if both vectors are constants. If not bail out.
12939     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12940           cast<BuildVectorSDNode>(RHS)->isConstant()))
12941       return SDValue();
12942
12943     SmallVector<SDValue, 8> Ops;
12944     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12945       SDValue LHSOp = LHS.getOperand(i);
12946       SDValue RHSOp = RHS.getOperand(i);
12947
12948       // Can't fold divide by zero.
12949       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12950           N->getOpcode() == ISD::FDIV) {
12951         if ((RHSOp.getOpcode() == ISD::Constant &&
12952              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12953             (RHSOp.getOpcode() == ISD::ConstantFP &&
12954              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12955           break;
12956       }
12957
12958       EVT VT = LHSOp.getValueType();
12959       EVT RVT = RHSOp.getValueType();
12960       if (RVT != VT) {
12961         // Integer BUILD_VECTOR operands may have types larger than the element
12962         // size (e.g., when the element type is not legal).  Prior to type
12963         // legalization, the types may not match between the two BUILD_VECTORS.
12964         // Truncate one of the operands to make them match.
12965         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12966           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12967         } else {
12968           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12969           VT = RVT;
12970         }
12971       }
12972       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12973                                    LHSOp, RHSOp);
12974       if (FoldOp.getOpcode() != ISD::UNDEF &&
12975           FoldOp.getOpcode() != ISD::Constant &&
12976           FoldOp.getOpcode() != ISD::ConstantFP)
12977         break;
12978       Ops.push_back(FoldOp);
12979       AddToWorklist(FoldOp.getNode());
12980     }
12981
12982     if (Ops.size() == LHS.getNumOperands())
12983       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12984   }
12985
12986   // Type legalization might introduce new shuffles in the DAG.
12987   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12988   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12989   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12990       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12991       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12992       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12993     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12994     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12995
12996     if (SVN0->getMask().equals(SVN1->getMask())) {
12997       EVT VT = N->getValueType(0);
12998       SDValue UndefVector = LHS.getOperand(1);
12999       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13000                                      LHS.getOperand(0), RHS.getOperand(0));
13001       AddUsersToWorklist(N);
13002       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13003                                   &SVN0->getMask()[0]);
13004     }
13005   }
13006
13007   return SDValue();
13008 }
13009
13010 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13011                                     SDValue N1, SDValue N2){
13012   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13013
13014   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13015                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13016
13017   // If we got a simplified select_cc node back from SimplifySelectCC, then
13018   // break it down into a new SETCC node, and a new SELECT node, and then return
13019   // the SELECT node, since we were called with a SELECT node.
13020   if (SCC.getNode()) {
13021     // Check to see if we got a select_cc back (to turn into setcc/select).
13022     // Otherwise, just return whatever node we got back, like fabs.
13023     if (SCC.getOpcode() == ISD::SELECT_CC) {
13024       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13025                                   N0.getValueType(),
13026                                   SCC.getOperand(0), SCC.getOperand(1),
13027                                   SCC.getOperand(4));
13028       AddToWorklist(SETCC.getNode());
13029       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13030                            SCC.getOperand(2), SCC.getOperand(3));
13031     }
13032
13033     return SCC;
13034   }
13035   return SDValue();
13036 }
13037
13038 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13039 /// being selected between, see if we can simplify the select.  Callers of this
13040 /// should assume that TheSelect is deleted if this returns true.  As such, they
13041 /// should return the appropriate thing (e.g. the node) back to the top-level of
13042 /// the DAG combiner loop to avoid it being looked at.
13043 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13044                                     SDValue RHS) {
13045
13046   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13047   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13048   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13049     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13050       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13051       SDValue Sqrt = RHS;
13052       ISD::CondCode CC;
13053       SDValue CmpLHS;
13054       const ConstantFPSDNode *NegZero = nullptr;
13055
13056       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13057         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13058         CmpLHS = TheSelect->getOperand(0);
13059         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13060       } else {
13061         // SELECT or VSELECT
13062         SDValue Cmp = TheSelect->getOperand(0);
13063         if (Cmp.getOpcode() == ISD::SETCC) {
13064           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13065           CmpLHS = Cmp.getOperand(0);
13066           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13067         }
13068       }
13069       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13070           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13071           CC == ISD::SETULT || CC == ISD::SETLT)) {
13072         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13073         CombineTo(TheSelect, Sqrt);
13074         return true;
13075       }
13076     }
13077   }
13078   // Cannot simplify select with vector condition
13079   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13080
13081   // If this is a select from two identical things, try to pull the operation
13082   // through the select.
13083   if (LHS.getOpcode() != RHS.getOpcode() ||
13084       !LHS.hasOneUse() || !RHS.hasOneUse())
13085     return false;
13086
13087   // If this is a load and the token chain is identical, replace the select
13088   // of two loads with a load through a select of the address to load from.
13089   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13090   // constants have been dropped into the constant pool.
13091   if (LHS.getOpcode() == ISD::LOAD) {
13092     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13093     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13094
13095     // Token chains must be identical.
13096     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13097         // Do not let this transformation reduce the number of volatile loads.
13098         LLD->isVolatile() || RLD->isVolatile() ||
13099         // FIXME: If either is a pre/post inc/dec load,
13100         // we'd need to split out the address adjustment.
13101         LLD->isIndexed() || RLD->isIndexed() ||
13102         // If this is an EXTLOAD, the VT's must match.
13103         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13104         // If this is an EXTLOAD, the kind of extension must match.
13105         (LLD->getExtensionType() != RLD->getExtensionType() &&
13106          // The only exception is if one of the extensions is anyext.
13107          LLD->getExtensionType() != ISD::EXTLOAD &&
13108          RLD->getExtensionType() != ISD::EXTLOAD) ||
13109         // FIXME: this discards src value information.  This is
13110         // over-conservative. It would be beneficial to be able to remember
13111         // both potential memory locations.  Since we are discarding
13112         // src value info, don't do the transformation if the memory
13113         // locations are not in the default address space.
13114         LLD->getPointerInfo().getAddrSpace() != 0 ||
13115         RLD->getPointerInfo().getAddrSpace() != 0 ||
13116         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13117                                       LLD->getBasePtr().getValueType()))
13118       return false;
13119
13120     // Check that the select condition doesn't reach either load.  If so,
13121     // folding this will induce a cycle into the DAG.  If not, this is safe to
13122     // xform, so create a select of the addresses.
13123     SDValue Addr;
13124     if (TheSelect->getOpcode() == ISD::SELECT) {
13125       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13126       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13127           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13128         return false;
13129       // The loads must not depend on one another.
13130       if (LLD->isPredecessorOf(RLD) ||
13131           RLD->isPredecessorOf(LLD))
13132         return false;
13133       Addr = DAG.getSelect(SDLoc(TheSelect),
13134                            LLD->getBasePtr().getValueType(),
13135                            TheSelect->getOperand(0), LLD->getBasePtr(),
13136                            RLD->getBasePtr());
13137     } else {  // Otherwise SELECT_CC
13138       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13139       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13140
13141       if ((LLD->hasAnyUseOfValue(1) &&
13142            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13143           (RLD->hasAnyUseOfValue(1) &&
13144            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13145         return false;
13146
13147       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13148                          LLD->getBasePtr().getValueType(),
13149                          TheSelect->getOperand(0),
13150                          TheSelect->getOperand(1),
13151                          LLD->getBasePtr(), RLD->getBasePtr(),
13152                          TheSelect->getOperand(4));
13153     }
13154
13155     SDValue Load;
13156     // It is safe to replace the two loads if they have different alignments,
13157     // but the new load must be the minimum (most restrictive) alignment of the
13158     // inputs.
13159     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13160     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13161     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13162       Load = DAG.getLoad(TheSelect->getValueType(0),
13163                          SDLoc(TheSelect),
13164                          // FIXME: Discards pointer and AA info.
13165                          LLD->getChain(), Addr, MachinePointerInfo(),
13166                          LLD->isVolatile(), LLD->isNonTemporal(),
13167                          isInvariant, Alignment);
13168     } else {
13169       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13170                             RLD->getExtensionType() : LLD->getExtensionType(),
13171                             SDLoc(TheSelect),
13172                             TheSelect->getValueType(0),
13173                             // FIXME: Discards pointer and AA info.
13174                             LLD->getChain(), Addr, MachinePointerInfo(),
13175                             LLD->getMemoryVT(), LLD->isVolatile(),
13176                             LLD->isNonTemporal(), isInvariant, Alignment);
13177     }
13178
13179     // Users of the select now use the result of the load.
13180     CombineTo(TheSelect, Load);
13181
13182     // Users of the old loads now use the new load's chain.  We know the
13183     // old-load value is dead now.
13184     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13185     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13186     return true;
13187   }
13188
13189   return false;
13190 }
13191
13192 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13193 /// where 'cond' is the comparison specified by CC.
13194 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13195                                       SDValue N2, SDValue N3,
13196                                       ISD::CondCode CC, bool NotExtCompare) {
13197   // (x ? y : y) -> y.
13198   if (N2 == N3) return N2;
13199
13200   EVT VT = N2.getValueType();
13201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13202   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13203   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13204
13205   // Determine if the condition we're dealing with is constant
13206   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13207                               N0, N1, CC, DL, false);
13208   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13209   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13210
13211   // fold select_cc true, x, y -> x
13212   if (SCCC && !SCCC->isNullValue())
13213     return N2;
13214   // fold select_cc false, x, y -> y
13215   if (SCCC && SCCC->isNullValue())
13216     return N3;
13217
13218   // Check to see if we can simplify the select into an fabs node
13219   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13220     // Allow either -0.0 or 0.0
13221     if (CFP->getValueAPF().isZero()) {
13222       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13223       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13224           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13225           N2 == N3.getOperand(0))
13226         return DAG.getNode(ISD::FABS, DL, VT, N0);
13227
13228       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13229       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13230           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13231           N2.getOperand(0) == N3)
13232         return DAG.getNode(ISD::FABS, DL, VT, N3);
13233     }
13234   }
13235
13236   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13237   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13238   // in it.  This is a win when the constant is not otherwise available because
13239   // it replaces two constant pool loads with one.  We only do this if the FP
13240   // type is known to be legal, because if it isn't, then we are before legalize
13241   // types an we want the other legalization to happen first (e.g. to avoid
13242   // messing with soft float) and if the ConstantFP is not legal, because if
13243   // it is legal, we may not need to store the FP constant in a constant pool.
13244   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13245     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13246       if (TLI.isTypeLegal(N2.getValueType()) &&
13247           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13248                TargetLowering::Legal &&
13249            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13250            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13251           // If both constants have multiple uses, then we won't need to do an
13252           // extra load, they are likely around in registers for other users.
13253           (TV->hasOneUse() || FV->hasOneUse())) {
13254         Constant *Elts[] = {
13255           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13256           const_cast<ConstantFP*>(TV->getConstantFPValue())
13257         };
13258         Type *FPTy = Elts[0]->getType();
13259         const DataLayout &TD = *TLI.getDataLayout();
13260
13261         // Create a ConstantArray of the two constants.
13262         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13263         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13264                                             TD.getPrefTypeAlignment(FPTy));
13265         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13266
13267         // Get the offsets to the 0 and 1 element of the array so that we can
13268         // select between them.
13269         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13270         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13271         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13272
13273         SDValue Cond = DAG.getSetCC(DL,
13274                                     getSetCCResultType(N0.getValueType()),
13275                                     N0, N1, CC);
13276         AddToWorklist(Cond.getNode());
13277         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13278                                           Cond, One, Zero);
13279         AddToWorklist(CstOffset.getNode());
13280         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13281                             CstOffset);
13282         AddToWorklist(CPIdx.getNode());
13283         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13284                            MachinePointerInfo::getConstantPool(), false,
13285                            false, false, Alignment);
13286       }
13287     }
13288
13289   // Check to see if we can perform the "gzip trick", transforming
13290   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13291   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13292       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13293        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13294     EVT XType = N0.getValueType();
13295     EVT AType = N2.getValueType();
13296     if (XType.bitsGE(AType)) {
13297       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13298       // single-bit constant.
13299       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13300         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13301         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13302         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13303                                        getShiftAmountTy(N0.getValueType()));
13304         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13305                                     XType, N0, ShCt);
13306         AddToWorklist(Shift.getNode());
13307
13308         if (XType.bitsGT(AType)) {
13309           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13310           AddToWorklist(Shift.getNode());
13311         }
13312
13313         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13314       }
13315
13316       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13317                                   XType, N0,
13318                                   DAG.getConstant(XType.getSizeInBits() - 1,
13319                                                   SDLoc(N0),
13320                                          getShiftAmountTy(N0.getValueType())));
13321       AddToWorklist(Shift.getNode());
13322
13323       if (XType.bitsGT(AType)) {
13324         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13325         AddToWorklist(Shift.getNode());
13326       }
13327
13328       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13329     }
13330   }
13331
13332   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13333   // where y is has a single bit set.
13334   // A plaintext description would be, we can turn the SELECT_CC into an AND
13335   // when the condition can be materialized as an all-ones register.  Any
13336   // single bit-test can be materialized as an all-ones register with
13337   // shift-left and shift-right-arith.
13338   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13339       N0->getValueType(0) == VT &&
13340       N1C && N1C->isNullValue() &&
13341       N2C && N2C->isNullValue()) {
13342     SDValue AndLHS = N0->getOperand(0);
13343     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13344     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13345       // Shift the tested bit over the sign bit.
13346       APInt AndMask = ConstAndRHS->getAPIntValue();
13347       SDValue ShlAmt =
13348         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13349                         getShiftAmountTy(AndLHS.getValueType()));
13350       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13351
13352       // Now arithmetic right shift it all the way over, so the result is either
13353       // all-ones, or zero.
13354       SDValue ShrAmt =
13355         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13356                         getShiftAmountTy(Shl.getValueType()));
13357       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13358
13359       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13360     }
13361   }
13362
13363   // fold select C, 16, 0 -> shl C, 4
13364   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13365       TLI.getBooleanContents(N0.getValueType()) ==
13366           TargetLowering::ZeroOrOneBooleanContent) {
13367
13368     // If the caller doesn't want us to simplify this into a zext of a compare,
13369     // don't do it.
13370     if (NotExtCompare && N2C->getAPIntValue() == 1)
13371       return SDValue();
13372
13373     // Get a SetCC of the condition
13374     // NOTE: Don't create a SETCC if it's not legal on this target.
13375     if (!LegalOperations ||
13376         TLI.isOperationLegal(ISD::SETCC,
13377           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13378       SDValue Temp, SCC;
13379       // cast from setcc result type to select result type
13380       if (LegalTypes) {
13381         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13382                             N0, N1, CC);
13383         if (N2.getValueType().bitsLT(SCC.getValueType()))
13384           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13385                                         N2.getValueType());
13386         else
13387           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13388                              N2.getValueType(), SCC);
13389       } else {
13390         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13391         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13392                            N2.getValueType(), SCC);
13393       }
13394
13395       AddToWorklist(SCC.getNode());
13396       AddToWorklist(Temp.getNode());
13397
13398       if (N2C->getAPIntValue() == 1)
13399         return Temp;
13400
13401       // shl setcc result by log2 n2c
13402       return DAG.getNode(
13403           ISD::SHL, DL, N2.getValueType(), Temp,
13404           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13405                           getShiftAmountTy(Temp.getValueType())));
13406     }
13407   }
13408
13409   // Check to see if this is the equivalent of setcc
13410   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13411   // otherwise, go ahead with the folds.
13412   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13413     EVT XType = N0.getValueType();
13414     if (!LegalOperations ||
13415         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13416       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13417       if (Res.getValueType() != VT)
13418         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13419       return Res;
13420     }
13421
13422     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13423     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13424         (!LegalOperations ||
13425          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13426       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13427       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13428                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13429                                          SDLoc(Ctlz),
13430                                        getShiftAmountTy(Ctlz.getValueType())));
13431     }
13432     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13433     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13434       SDLoc DL(N0);
13435       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13436                                   XType, DAG.getConstant(0, DL, XType), N0);
13437       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13438       return DAG.getNode(ISD::SRL, DL, XType,
13439                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13440                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13441                                          getShiftAmountTy(XType)));
13442     }
13443     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13444     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13445       SDLoc DL(N0);
13446       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13447                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13448                                          getShiftAmountTy(N0.getValueType())));
13449       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13450                                                                     XType));
13451     }
13452   }
13453
13454   // Check to see if this is an integer abs.
13455   // select_cc setg[te] X,  0,  X, -X ->
13456   // select_cc setgt    X, -1,  X, -X ->
13457   // select_cc setl[te] X,  0, -X,  X ->
13458   // select_cc setlt    X,  1, -X,  X ->
13459   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13460   if (N1C) {
13461     ConstantSDNode *SubC = nullptr;
13462     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13463          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13464         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13465       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13466     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13467               (N1C->isOne() && CC == ISD::SETLT)) &&
13468              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13469       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13470
13471     EVT XType = N0.getValueType();
13472     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13473       SDLoc DL(N0);
13474       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13475                                   N0,
13476                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13477                                          getShiftAmountTy(N0.getValueType())));
13478       SDValue Add = DAG.getNode(ISD::ADD, DL,
13479                                 XType, N0, Shift);
13480       AddToWorklist(Shift.getNode());
13481       AddToWorklist(Add.getNode());
13482       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13483     }
13484   }
13485
13486   return SDValue();
13487 }
13488
13489 /// This is a stub for TargetLowering::SimplifySetCC.
13490 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13491                                    SDValue N1, ISD::CondCode Cond,
13492                                    SDLoc DL, bool foldBooleans) {
13493   TargetLowering::DAGCombinerInfo
13494     DagCombineInfo(DAG, Level, false, this);
13495   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13496 }
13497
13498 /// Given an ISD::SDIV node expressing a divide by constant, return
13499 /// a DAG expression to select that will generate the same value by multiplying
13500 /// by a magic number.
13501 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13502 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13503   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13504   if (!C)
13505     return SDValue();
13506
13507   // Avoid division by zero.
13508   if (!C->getAPIntValue())
13509     return SDValue();
13510
13511   std::vector<SDNode*> Built;
13512   SDValue S =
13513       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13514
13515   for (SDNode *N : Built)
13516     AddToWorklist(N);
13517   return S;
13518 }
13519
13520 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13521 /// DAG expression that will generate the same value by right shifting.
13522 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13523   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13524   if (!C)
13525     return SDValue();
13526
13527   // Avoid division by zero.
13528   if (!C->getAPIntValue())
13529     return SDValue();
13530
13531   std::vector<SDNode *> Built;
13532   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13533
13534   for (SDNode *N : Built)
13535     AddToWorklist(N);
13536   return S;
13537 }
13538
13539 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13540 /// expression that will generate the same value by multiplying by a magic
13541 /// number.
13542 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13543 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13544   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13545   if (!C)
13546     return SDValue();
13547
13548   // Avoid division by zero.
13549   if (!C->getAPIntValue())
13550     return SDValue();
13551
13552   std::vector<SDNode*> Built;
13553   SDValue S =
13554       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13555
13556   for (SDNode *N : Built)
13557     AddToWorklist(N);
13558   return S;
13559 }
13560
13561 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13562   if (Level >= AfterLegalizeDAG)
13563     return SDValue();
13564
13565   // Expose the DAG combiner to the target combiner implementations.
13566   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13567
13568   unsigned Iterations = 0;
13569   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13570     if (Iterations) {
13571       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13572       // For the reciprocal, we need to find the zero of the function:
13573       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13574       //     =>
13575       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13576       //     does not require additional intermediate precision]
13577       EVT VT = Op.getValueType();
13578       SDLoc DL(Op);
13579       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13580
13581       AddToWorklist(Est.getNode());
13582
13583       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13584       for (unsigned i = 0; i < Iterations; ++i) {
13585         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13586         AddToWorklist(NewEst.getNode());
13587
13588         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13589         AddToWorklist(NewEst.getNode());
13590
13591         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13592         AddToWorklist(NewEst.getNode());
13593
13594         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13595         AddToWorklist(Est.getNode());
13596       }
13597     }
13598     return Est;
13599   }
13600
13601   return SDValue();
13602 }
13603
13604 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13605 /// For the reciprocal sqrt, we need to find the zero of the function:
13606 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13607 ///     =>
13608 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13609 /// As a result, we precompute A/2 prior to the iteration loop.
13610 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13611                                           unsigned Iterations) {
13612   EVT VT = Arg.getValueType();
13613   SDLoc DL(Arg);
13614   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13615
13616   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13617   // this entire sequence requires only one FP constant.
13618   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13619   AddToWorklist(HalfArg.getNode());
13620
13621   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13622   AddToWorklist(HalfArg.getNode());
13623
13624   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13625   for (unsigned i = 0; i < Iterations; ++i) {
13626     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13627     AddToWorklist(NewEst.getNode());
13628
13629     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13630     AddToWorklist(NewEst.getNode());
13631
13632     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13633     AddToWorklist(NewEst.getNode());
13634
13635     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13636     AddToWorklist(Est.getNode());
13637   }
13638   return Est;
13639 }
13640
13641 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13642 /// For the reciprocal sqrt, we need to find the zero of the function:
13643 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13644 ///     =>
13645 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13646 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13647                                           unsigned Iterations) {
13648   EVT VT = Arg.getValueType();
13649   SDLoc DL(Arg);
13650   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13651   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13652
13653   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13654   for (unsigned i = 0; i < Iterations; ++i) {
13655     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13656     AddToWorklist(HalfEst.getNode());
13657
13658     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13659     AddToWorklist(Est.getNode());
13660
13661     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13662     AddToWorklist(Est.getNode());
13663
13664     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13665     AddToWorklist(Est.getNode());
13666
13667     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13668     AddToWorklist(Est.getNode());
13669   }
13670   return Est;
13671 }
13672
13673 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13674   if (Level >= AfterLegalizeDAG)
13675     return SDValue();
13676
13677   // Expose the DAG combiner to the target combiner implementations.
13678   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13679   unsigned Iterations = 0;
13680   bool UseOneConstNR = false;
13681   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13682     AddToWorklist(Est.getNode());
13683     if (Iterations) {
13684       Est = UseOneConstNR ?
13685         BuildRsqrtNROneConst(Op, Est, Iterations) :
13686         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13687     }
13688     return Est;
13689   }
13690
13691   return SDValue();
13692 }
13693
13694 /// Return true if base is a frame index, which is known not to alias with
13695 /// anything but itself.  Provides base object and offset as results.
13696 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13697                            const GlobalValue *&GV, const void *&CV) {
13698   // Assume it is a primitive operation.
13699   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13700
13701   // If it's an adding a simple constant then integrate the offset.
13702   if (Base.getOpcode() == ISD::ADD) {
13703     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13704       Base = Base.getOperand(0);
13705       Offset += C->getZExtValue();
13706     }
13707   }
13708
13709   // Return the underlying GlobalValue, and update the Offset.  Return false
13710   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13711   // by multiple nodes with different offsets.
13712   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13713     GV = G->getGlobal();
13714     Offset += G->getOffset();
13715     return false;
13716   }
13717
13718   // Return the underlying Constant value, and update the Offset.  Return false
13719   // for ConstantSDNodes since the same constant pool entry may be represented
13720   // by multiple nodes with different offsets.
13721   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13722     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13723                                          : (const void *)C->getConstVal();
13724     Offset += C->getOffset();
13725     return false;
13726   }
13727   // If it's any of the following then it can't alias with anything but itself.
13728   return isa<FrameIndexSDNode>(Base);
13729 }
13730
13731 /// Return true if there is any possibility that the two addresses overlap.
13732 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13733   // If they are the same then they must be aliases.
13734   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13735
13736   // If they are both volatile then they cannot be reordered.
13737   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13738
13739   // Gather base node and offset information.
13740   SDValue Base1, Base2;
13741   int64_t Offset1, Offset2;
13742   const GlobalValue *GV1, *GV2;
13743   const void *CV1, *CV2;
13744   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13745                                       Base1, Offset1, GV1, CV1);
13746   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13747                                       Base2, Offset2, GV2, CV2);
13748
13749   // If they have a same base address then check to see if they overlap.
13750   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13751     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13752              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13753
13754   // It is possible for different frame indices to alias each other, mostly
13755   // when tail call optimization reuses return address slots for arguments.
13756   // To catch this case, look up the actual index of frame indices to compute
13757   // the real alias relationship.
13758   if (isFrameIndex1 && isFrameIndex2) {
13759     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13760     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13761     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13762     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13763              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13764   }
13765
13766   // Otherwise, if we know what the bases are, and they aren't identical, then
13767   // we know they cannot alias.
13768   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13769     return false;
13770
13771   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13772   // compared to the size and offset of the access, we may be able to prove they
13773   // do not alias.  This check is conservative for now to catch cases created by
13774   // splitting vector types.
13775   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13776       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13777       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13778        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13779       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13780     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13781     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13782
13783     // There is no overlap between these relatively aligned accesses of similar
13784     // size, return no alias.
13785     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13786         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13787       return false;
13788   }
13789
13790   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13791                    ? CombinerGlobalAA
13792                    : DAG.getSubtarget().useAA();
13793 #ifndef NDEBUG
13794   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13795       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13796     UseAA = false;
13797 #endif
13798   if (UseAA &&
13799       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13800     // Use alias analysis information.
13801     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13802                                  Op1->getSrcValueOffset());
13803     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13804         Op0->getSrcValueOffset() - MinOffset;
13805     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13806         Op1->getSrcValueOffset() - MinOffset;
13807     AliasAnalysis::AliasResult AAResult =
13808         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13809                                          Overlap1,
13810                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13811                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13812                                          Overlap2,
13813                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13814     if (AAResult == AliasAnalysis::NoAlias)
13815       return false;
13816   }
13817
13818   // Otherwise we have to assume they alias.
13819   return true;
13820 }
13821
13822 /// Walk up chain skipping non-aliasing memory nodes,
13823 /// looking for aliasing nodes and adding them to the Aliases vector.
13824 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13825                                    SmallVectorImpl<SDValue> &Aliases) {
13826   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13827   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13828
13829   // Get alias information for node.
13830   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13831
13832   // Starting off.
13833   Chains.push_back(OriginalChain);
13834   unsigned Depth = 0;
13835
13836   // Look at each chain and determine if it is an alias.  If so, add it to the
13837   // aliases list.  If not, then continue up the chain looking for the next
13838   // candidate.
13839   while (!Chains.empty()) {
13840     SDValue Chain = Chains.back();
13841     Chains.pop_back();
13842
13843     // For TokenFactor nodes, look at each operand and only continue up the
13844     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13845     // find more and revert to original chain since the xform is unlikely to be
13846     // profitable.
13847     //
13848     // FIXME: The depth check could be made to return the last non-aliasing
13849     // chain we found before we hit a tokenfactor rather than the original
13850     // chain.
13851     if (Depth > 6 || Aliases.size() == 2) {
13852       Aliases.clear();
13853       Aliases.push_back(OriginalChain);
13854       return;
13855     }
13856
13857     // Don't bother if we've been before.
13858     if (!Visited.insert(Chain.getNode()).second)
13859       continue;
13860
13861     switch (Chain.getOpcode()) {
13862     case ISD::EntryToken:
13863       // Entry token is ideal chain operand, but handled in FindBetterChain.
13864       break;
13865
13866     case ISD::LOAD:
13867     case ISD::STORE: {
13868       // Get alias information for Chain.
13869       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13870           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13871
13872       // If chain is alias then stop here.
13873       if (!(IsLoad && IsOpLoad) &&
13874           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13875         Aliases.push_back(Chain);
13876       } else {
13877         // Look further up the chain.
13878         Chains.push_back(Chain.getOperand(0));
13879         ++Depth;
13880       }
13881       break;
13882     }
13883
13884     case ISD::TokenFactor:
13885       // We have to check each of the operands of the token factor for "small"
13886       // token factors, so we queue them up.  Adding the operands to the queue
13887       // (stack) in reverse order maintains the original order and increases the
13888       // likelihood that getNode will find a matching token factor (CSE.)
13889       if (Chain.getNumOperands() > 16) {
13890         Aliases.push_back(Chain);
13891         break;
13892       }
13893       for (unsigned n = Chain.getNumOperands(); n;)
13894         Chains.push_back(Chain.getOperand(--n));
13895       ++Depth;
13896       break;
13897
13898     default:
13899       // For all other instructions we will just have to take what we can get.
13900       Aliases.push_back(Chain);
13901       break;
13902     }
13903   }
13904
13905   // We need to be careful here to also search for aliases through the
13906   // value operand of a store, etc. Consider the following situation:
13907   //   Token1 = ...
13908   //   L1 = load Token1, %52
13909   //   S1 = store Token1, L1, %51
13910   //   L2 = load Token1, %52+8
13911   //   S2 = store Token1, L2, %51+8
13912   //   Token2 = Token(S1, S2)
13913   //   L3 = load Token2, %53
13914   //   S3 = store Token2, L3, %52
13915   //   L4 = load Token2, %53+8
13916   //   S4 = store Token2, L4, %52+8
13917   // If we search for aliases of S3 (which loads address %52), and we look
13918   // only through the chain, then we'll miss the trivial dependence on L1
13919   // (which also loads from %52). We then might change all loads and
13920   // stores to use Token1 as their chain operand, which could result in
13921   // copying %53 into %52 before copying %52 into %51 (which should
13922   // happen first).
13923   //
13924   // The problem is, however, that searching for such data dependencies
13925   // can become expensive, and the cost is not directly related to the
13926   // chain depth. Instead, we'll rule out such configurations here by
13927   // insisting that we've visited all chain users (except for users
13928   // of the original chain, which is not necessary). When doing this,
13929   // we need to look through nodes we don't care about (otherwise, things
13930   // like register copies will interfere with trivial cases).
13931
13932   SmallVector<const SDNode *, 16> Worklist;
13933   for (const SDNode *N : Visited)
13934     if (N != OriginalChain.getNode())
13935       Worklist.push_back(N);
13936
13937   while (!Worklist.empty()) {
13938     const SDNode *M = Worklist.pop_back_val();
13939
13940     // We have already visited M, and want to make sure we've visited any uses
13941     // of M that we care about. For uses that we've not visisted, and don't
13942     // care about, queue them to the worklist.
13943
13944     for (SDNode::use_iterator UI = M->use_begin(),
13945          UIE = M->use_end(); UI != UIE; ++UI)
13946       if (UI.getUse().getValueType() == MVT::Other &&
13947           Visited.insert(*UI).second) {
13948         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13949           // We've not visited this use, and we care about it (it could have an
13950           // ordering dependency with the original node).
13951           Aliases.clear();
13952           Aliases.push_back(OriginalChain);
13953           return;
13954         }
13955
13956         // We've not visited this use, but we don't care about it. Mark it as
13957         // visited and enqueue it to the worklist.
13958         Worklist.push_back(*UI);
13959       }
13960   }
13961 }
13962
13963 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13964 /// (aliasing node.)
13965 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13966   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13967
13968   // Accumulate all the aliases to this node.
13969   GatherAllAliases(N, OldChain, Aliases);
13970
13971   // If no operands then chain to entry token.
13972   if (Aliases.size() == 0)
13973     return DAG.getEntryNode();
13974
13975   // If a single operand then chain to it.  We don't need to revisit it.
13976   if (Aliases.size() == 1)
13977     return Aliases[0];
13978
13979   // Construct a custom tailored token factor.
13980   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13981 }
13982
13983 /// This is the entry point for the file.
13984 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13985                            CodeGenOpt::Level OptLevel) {
13986   /// This is the main entry point to this class.
13987   DAGCombiner(*this, AA, OptLevel).Run(Level);
13988 }