df721e2d3b5e3fa27bac77e682faae04c7b6f306
[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 visitFP_TO_FP16(SDNode *N);
311
312     SDValue visitFADDForFMACombine(SDNode *N);
313     SDValue visitFSUBForFMACombine(SDNode *N);
314
315     SDValue XformToShuffleWithZero(SDNode *N);
316     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
317
318     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
319
320     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
322     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
324                              SDValue N3, ISD::CondCode CC,
325                              bool NotExtCompare = false);
326     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
327                           SDLoc DL, bool foldBooleans = true);
328
329     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
330                            SDValue &CC) const;
331     bool isOneUseSetCC(SDValue N) const;
332
333     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
334                                          unsigned HiOp);
335     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
336     SDValue CombineExtLoad(SDNode *N);
337     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
338     SDValue BuildSDIV(SDNode *N);
339     SDValue BuildSDIVPow2(SDNode *N);
340     SDValue BuildUDIV(SDNode *N);
341     SDValue BuildReciprocalEstimate(SDValue Op);
342     SDValue BuildRsqrtEstimate(SDValue Op);
343     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
345     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346                                bool DemandHighBits = true);
347     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
348     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349                               SDValue InnerPos, SDValue InnerNeg,
350                               unsigned PosOpcode, unsigned NegOpcode,
351                               SDLoc DL);
352     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
353     SDValue ReduceLoadWidth(SDNode *N);
354     SDValue ReduceLoadOpStoreWidth(SDNode *N);
355     SDValue TransformFPLoadStorePair(SDNode *N);
356     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
357     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
358
359     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
360
361     /// Walk up chain skipping non-aliasing memory nodes,
362     /// looking for aliasing nodes and adding them to the Aliases vector.
363     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
364                           SmallVectorImpl<SDValue> &Aliases);
365
366     /// Return true if there is any possibility that the two addresses overlap.
367     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
368
369     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370     /// chain (aliasing node.)
371     SDValue FindBetterChain(SDNode *N, SDValue Chain);
372
373     /// Holds a pointer to an LSBaseSDNode as well as information on where it
374     /// is located in a sequence of memory operations connected by a chain.
375     struct MemOpLink {
376       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378       // Ptr to the mem node.
379       LSBaseSDNode *MemNode;
380       // Offset from the base ptr.
381       int64_t OffsetFromBase;
382       // What is the sequence number of this mem node.
383       // Lowest mem operand in the DAG starts at zero.
384       unsigned SequenceNum;
385     };
386
387     /// This is a helper function for MergeConsecutiveStores. When the source
388     /// elements of the consecutive stores are all constants or all extracted
389     /// vector elements, try to merge them into one larger store.
390     /// \return True if a merged store was created.
391     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
392                                          EVT MemVT, unsigned NumElem,
393                                          bool IsConstantSrc, bool UseVector);
394
395     /// Merge consecutive store operations into a wide store.
396     /// This optimization uses wide integers or vectors when possible.
397     /// \return True if some memory operations were changed.
398     bool MergeConsecutiveStores(StoreSDNode *N);
399
400     /// \brief Try to transform a truncation where C is a constant:
401     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
402     ///
403     /// \p N needs to be a truncation and its first operand an AND. Other
404     /// requirements are checked by the function (e.g. that trunc is
405     /// single-use) and if missed an empty SDValue is returned.
406     SDValue distributeTruncateThroughAnd(SDNode *N);
407
408   public:
409     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
410         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
412       auto *F = DAG.getMachineFunction().getFunction();
413       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414                     F->hasFnAttribute(Attribute::MinSize);
415     }
416
417     /// Runs the dag combiner on all nodes in the work list
418     void Run(CombineLevel AtLevel);
419
420     SelectionDAG &getDAG() const { return DAG; }
421
422     /// Returns a type large enough to hold any valid shift amount - before type
423     /// legalization these can be huge.
424     EVT getShiftAmountTy(EVT LHSTy) {
425       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426       if (LHSTy.isVector())
427         return LHSTy;
428       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429                         : TLI.getPointerTy();
430     }
431
432     /// This method returns true if we are running before type legalization or
433     /// if the specified VT is legal.
434     bool isTypeLegal(const EVT &VT) {
435       if (!LegalTypes) return true;
436       return TLI.isTypeLegal(VT);
437     }
438
439     /// Convenience wrapper around TargetLowering::getSetCCResultType
440     EVT getSetCCResultType(EVT VT) const {
441       return TLI.getSetCCResultType(*DAG.getContext(), VT);
442     }
443   };
444 }
445
446
447 namespace {
448 /// This class is a DAGUpdateListener that removes any deleted
449 /// nodes from the worklist.
450 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
451   DAGCombiner &DC;
452 public:
453   explicit WorklistRemover(DAGCombiner &dc)
454     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
455
456   void NodeDeleted(SDNode *N, SDNode *E) override {
457     DC.removeFromWorklist(N);
458   }
459 };
460 }
461
462 //===----------------------------------------------------------------------===//
463 //  TargetLowering::DAGCombinerInfo implementation
464 //===----------------------------------------------------------------------===//
465
466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
467   ((DAGCombiner*)DC)->AddToWorklist(N);
468 }
469
470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
471   ((DAGCombiner*)DC)->removeFromWorklist(N);
472 }
473
474 SDValue TargetLowering::DAGCombinerInfo::
475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
476   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
477 }
478
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
482 }
483
484
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
488 }
489
490 void TargetLowering::DAGCombinerInfo::
491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
493 }
494
495 //===----------------------------------------------------------------------===//
496 // Helper Functions
497 //===----------------------------------------------------------------------===//
498
499 void DAGCombiner::deleteAndRecombine(SDNode *N) {
500   removeFromWorklist(N);
501
502   // If the operands of this node are only used by the node, they will now be
503   // dead. Make sure to re-visit them and recursively delete dead nodes.
504   for (const SDValue &Op : N->ops())
505     // For an operand generating multiple values, one of the values may
506     // become dead allowing further simplification (e.g. split index
507     // arithmetic from an indexed load).
508     if (Op->hasOneUse() || Op->getNumValues() > 1)
509       AddToWorklist(Op.getNode());
510
511   DAG.DeleteNode(N);
512 }
513
514 /// Return 1 if we can compute the negated form of the specified expression for
515 /// the same cost as the expression itself, or 2 if we can compute the negated
516 /// form more cheaply than the expression itself.
517 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
518                                const TargetLowering &TLI,
519                                const TargetOptions *Options,
520                                unsigned Depth = 0) {
521   // fneg is removable even if it has multiple uses.
522   if (Op.getOpcode() == ISD::FNEG) return 2;
523
524   // Don't allow anything with multiple uses.
525   if (!Op.hasOneUse()) return 0;
526
527   // Don't recurse exponentially.
528   if (Depth > 6) return 0;
529
530   switch (Op.getOpcode()) {
531   default: return false;
532   case ISD::ConstantFP:
533     // Don't invert constant FP values after legalize.  The negated constant
534     // isn't necessarily legal.
535     return LegalOperations ? 0 : 1;
536   case ISD::FADD:
537     // FIXME: determine better conditions for this xform.
538     if (!Options->UnsafeFPMath) return 0;
539
540     // After operation legalization, it might not be legal to create new FSUBs.
541     if (LegalOperations &&
542         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
543       return 0;
544
545     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
546     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
547                                     Options, Depth + 1))
548       return V;
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
551                               Depth + 1);
552   case ISD::FSUB:
553     // We can't turn -(A-B) into B-A when we honor signed zeros.
554     if (!Options->UnsafeFPMath) return 0;
555
556     // fold (fneg (fsub A, B)) -> (fsub B, A)
557     return 1;
558
559   case ISD::FMUL:
560   case ISD::FDIV:
561     if (Options->HonorSignDependentRoundingFPMath()) return 0;
562
563     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
564     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565                                     Options, Depth + 1))
566       return V;
567
568     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
569                               Depth + 1);
570
571   case ISD::FP_EXTEND:
572   case ISD::FP_ROUND:
573   case ISD::FSIN:
574     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575                               Depth + 1);
576   }
577 }
578
579 /// If isNegatibleForFree returns true, return the newly negated expression.
580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
581                                     bool LegalOperations, unsigned Depth = 0) {
582   const TargetOptions &Options = DAG.getTarget().Options;
583   // fneg is removable even if it has multiple uses.
584   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
585
586   // Don't allow anything with multiple uses.
587   assert(Op.hasOneUse() && "Unknown reuse!");
588
589   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
590   switch (Op.getOpcode()) {
591   default: llvm_unreachable("Unknown code");
592   case ISD::ConstantFP: {
593     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
594     V.changeSign();
595     return DAG.getConstantFP(V, Op.getValueType());
596   }
597   case ISD::FADD:
598     // FIXME: determine better conditions for this xform.
599     assert(Options.UnsafeFPMath);
600
601     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
602     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
603                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
604       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
605                          GetNegatedExpression(Op.getOperand(0), DAG,
606                                               LegalOperations, Depth+1),
607                          Op.getOperand(1));
608     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
609     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
610                        GetNegatedExpression(Op.getOperand(1), DAG,
611                                             LegalOperations, Depth+1),
612                        Op.getOperand(0));
613   case ISD::FSUB:
614     // We can't turn -(A-B) into B-A when we honor signed zeros.
615     assert(Options.UnsafeFPMath);
616
617     // fold (fneg (fsub 0, B)) -> B
618     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
619       if (N0CFP->getValueAPF().isZero())
620         return Op.getOperand(1);
621
622     // fold (fneg (fsub A, B)) -> (fsub B, A)
623     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624                        Op.getOperand(1), Op.getOperand(0));
625
626   case ISD::FMUL:
627   case ISD::FDIV:
628     assert(!Options.HonorSignDependentRoundingFPMath());
629
630     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
631     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
632                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
633       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
634                          GetNegatedExpression(Op.getOperand(0), DAG,
635                                               LegalOperations, Depth+1),
636                          Op.getOperand(1));
637
638     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
639     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
640                        Op.getOperand(0),
641                        GetNegatedExpression(Op.getOperand(1), DAG,
642                                             LegalOperations, Depth+1));
643
644   case ISD::FP_EXTEND:
645   case ISD::FSIN:
646     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
647                        GetNegatedExpression(Op.getOperand(0), DAG,
648                                             LegalOperations, Depth+1));
649   case ISD::FP_ROUND:
650       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
651                          GetNegatedExpression(Op.getOperand(0), DAG,
652                                               LegalOperations, Depth+1),
653                          Op.getOperand(1));
654   }
655 }
656
657 // Return true if this node is a setcc, or is a select_cc
658 // that selects between the target values used for true and false, making it
659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660 // the appropriate nodes based on the type of node we are checking. This
661 // simplifies life a bit for the callers.
662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
663                                     SDValue &CC) const {
664   if (N.getOpcode() == ISD::SETCC) {
665     LHS = N.getOperand(0);
666     RHS = N.getOperand(1);
667     CC  = N.getOperand(2);
668     return true;
669   }
670
671   if (N.getOpcode() != ISD::SELECT_CC ||
672       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
674     return false;
675
676   if (TLI.getBooleanContents(N.getValueType()) ==
677       TargetLowering::UndefinedBooleanContent)
678     return false;
679
680   LHS = N.getOperand(0);
681   RHS = N.getOperand(1);
682   CC  = N.getOperand(4);
683   return true;
684 }
685
686 /// Return true if this is a SetCC-equivalent operation with only one use.
687 /// If this is true, it allows the users to invert the operation for free when
688 /// it is profitable to do so.
689 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
690   SDValue N0, N1, N2;
691   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692     return true;
693   return false;
694 }
695
696 /// Returns true if N is a BUILD_VECTOR node whose
697 /// elements are all the same constant or undefined.
698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700   if (!C)
701     return false;
702
703   APInt SplatUndef;
704   unsigned SplatBitSize;
705   bool HasAnyUndefs;
706   EVT EltVT = N->getValueType(0).getVectorElementType();
707   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
708                              HasAnyUndefs) &&
709           EltVT.getSizeInBits() >= SplatBitSize);
710 }
711
712 // \brief Returns the SDNode if it is a constant integer BuildVector
713 // or constant integer.
714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715   if (isa<ConstantSDNode>(N))
716     return N.getNode();
717   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
718     return N.getNode();
719   return nullptr;
720 }
721
722 // \brief Returns the SDNode if it is a constant float BuildVector
723 // or constant float.
724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725   if (isa<ConstantFPSDNode>(N))
726     return N.getNode();
727   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
728     return N.getNode();
729   return nullptr;
730 }
731
732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
733 // int.
734 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
736     return CN;
737
738   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
739     BitVector UndefElements;
740     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
741
742     // BuildVectors can truncate their operands. Ignore that case here.
743     // FIXME: We blindly ignore splats which include undef which is overly
744     // pessimistic.
745     if (CN && UndefElements.none() &&
746         CN->getValueType(0) == N.getValueType().getScalarType())
747       return CN;
748   }
749
750   return nullptr;
751 }
752
753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
754 // float.
755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
757     return CN;
758
759   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760     BitVector UndefElements;
761     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
762
763     if (CN && UndefElements.none())
764       return CN;
765   }
766
767   return nullptr;
768 }
769
770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
771                                     SDValue N0, SDValue N1) {
772   EVT VT = N0.getValueType();
773   if (N0.getOpcode() == Opc) {
774     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
776         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
777         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
778           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
779         return SDValue();
780       }
781       if (N0.hasOneUse()) {
782         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
783         // use
784         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785         if (!OpNode.getNode())
786           return SDValue();
787         AddToWorklist(OpNode.getNode());
788         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
789       }
790     }
791   }
792
793   if (N1.getOpcode() == Opc) {
794     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
796         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
797         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
798           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
799         return SDValue();
800       }
801       if (N1.hasOneUse()) {
802         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
803         // use
804         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805         if (!OpNode.getNode())
806           return SDValue();
807         AddToWorklist(OpNode.getNode());
808         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
809       }
810     }
811   }
812
813   return SDValue();
814 }
815
816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
817                                bool AddTo) {
818   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
819   ++NodesCombined;
820   DEBUG(dbgs() << "\nReplacing.1 ";
821         N->dump(&DAG);
822         dbgs() << "\nWith: ";
823         To[0].getNode()->dump(&DAG);
824         dbgs() << " and " << NumTo-1 << " other values\n");
825   for (unsigned i = 0, e = NumTo; i != e; ++i)
826     assert((!To[i].getNode() ||
827             N->getValueType(i) == To[i].getValueType()) &&
828            "Cannot combine value to value of different type!");
829
830   WorklistRemover DeadNodes(*this);
831   DAG.ReplaceAllUsesWith(N, To);
832   if (AddTo) {
833     // Push the new nodes and any users onto the worklist
834     for (unsigned i = 0, e = NumTo; i != e; ++i) {
835       if (To[i].getNode()) {
836         AddToWorklist(To[i].getNode());
837         AddUsersToWorklist(To[i].getNode());
838       }
839     }
840   }
841
842   // Finally, if the node is now dead, remove it from the graph.  The node
843   // may not be dead if the replacement process recursively simplified to
844   // something else needing this node.
845   if (N->use_empty())
846     deleteAndRecombine(N);
847   return SDValue(N, 0);
848 }
849
850 void DAGCombiner::
851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
852   // Replace all uses.  If any nodes become isomorphic to other nodes and
853   // are deleted, make sure to remove them from our worklist.
854   WorklistRemover DeadNodes(*this);
855   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
856
857   // Push the new node and any (possibly new) users onto the worklist.
858   AddToWorklist(TLO.New.getNode());
859   AddUsersToWorklist(TLO.New.getNode());
860
861   // Finally, if the node is now dead, remove it from the graph.  The node
862   // may not be dead if the replacement process recursively simplified to
863   // something else needing this node.
864   if (TLO.Old.getNode()->use_empty())
865     deleteAndRecombine(TLO.Old.getNode());
866 }
867
868 /// Check the specified integer node value to see if it can be simplified or if
869 /// things it uses can be simplified by bit propagation. If so, return true.
870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
871   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
872   APInt KnownZero, KnownOne;
873   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
874     return false;
875
876   // Revisit the node.
877   AddToWorklist(Op.getNode());
878
879   // Replace the old value with the new one.
880   ++NodesCombined;
881   DEBUG(dbgs() << "\nReplacing.2 ";
882         TLO.Old.getNode()->dump(&DAG);
883         dbgs() << "\nWith: ";
884         TLO.New.getNode()->dump(&DAG);
885         dbgs() << '\n');
886
887   CommitTargetLoweringOpt(TLO);
888   return true;
889 }
890
891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
892   SDLoc dl(Load);
893   EVT VT = Load->getValueType(0);
894   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
895
896   DEBUG(dbgs() << "\nReplacing.9 ";
897         Load->dump(&DAG);
898         dbgs() << "\nWith: ";
899         Trunc.getNode()->dump(&DAG);
900         dbgs() << '\n');
901   WorklistRemover DeadNodes(*this);
902   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
904   deleteAndRecombine(Load);
905   AddToWorklist(Trunc.getNode());
906 }
907
908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
909   Replace = false;
910   SDLoc dl(Op);
911   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
912     EVT MemVT = LD->getMemoryVT();
913     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
914       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
915                                                        : ISD::EXTLOAD)
916       : LD->getExtensionType();
917     Replace = true;
918     return DAG.getExtLoad(ExtType, dl, PVT,
919                           LD->getChain(), LD->getBasePtr(),
920                           MemVT, LD->getMemOperand());
921   }
922
923   unsigned Opc = Op.getOpcode();
924   switch (Opc) {
925   default: break;
926   case ISD::AssertSext:
927     return DAG.getNode(ISD::AssertSext, dl, PVT,
928                        SExtPromoteOperand(Op.getOperand(0), PVT),
929                        Op.getOperand(1));
930   case ISD::AssertZext:
931     return DAG.getNode(ISD::AssertZext, dl, PVT,
932                        ZExtPromoteOperand(Op.getOperand(0), PVT),
933                        Op.getOperand(1));
934   case ISD::Constant: {
935     unsigned ExtOpc =
936       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
937     return DAG.getNode(ExtOpc, dl, PVT, Op);
938   }
939   }
940
941   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
942     return SDValue();
943   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
944 }
945
946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
947   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
948     return SDValue();
949   EVT OldVT = Op.getValueType();
950   SDLoc dl(Op);
951   bool Replace = false;
952   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
953   if (!NewOp.getNode())
954     return SDValue();
955   AddToWorklist(NewOp.getNode());
956
957   if (Replace)
958     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
960                      DAG.getValueType(OldVT));
961 }
962
963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
964   EVT OldVT = Op.getValueType();
965   SDLoc dl(Op);
966   bool Replace = false;
967   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
968   if (!NewOp.getNode())
969     return SDValue();
970   AddToWorklist(NewOp.getNode());
971
972   if (Replace)
973     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
975 }
976
977 /// Promote the specified integer binary operation if the target indicates it is
978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979 /// i32 since i16 instructions are longer.
980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981   if (!LegalOperations)
982     return SDValue();
983
984   EVT VT = Op.getValueType();
985   if (VT.isVector() || !VT.isInteger())
986     return SDValue();
987
988   // If operation type is 'undesirable', e.g. i16 on x86, consider
989   // promoting it.
990   unsigned Opc = Op.getOpcode();
991   if (TLI.isTypeDesirableForOp(Opc, VT))
992     return SDValue();
993
994   EVT PVT = VT;
995   // Consult target whether it is a good idea to promote this operation and
996   // what's the right type to promote it to.
997   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
998     assert(PVT != VT && "Don't know what type to promote to!");
999
1000     bool Replace0 = false;
1001     SDValue N0 = Op.getOperand(0);
1002     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1003     if (!NN0.getNode())
1004       return SDValue();
1005
1006     bool Replace1 = false;
1007     SDValue N1 = Op.getOperand(1);
1008     SDValue NN1;
1009     if (N0 == N1)
1010       NN1 = NN0;
1011     else {
1012       NN1 = PromoteOperand(N1, PVT, Replace1);
1013       if (!NN1.getNode())
1014         return SDValue();
1015     }
1016
1017     AddToWorklist(NN0.getNode());
1018     if (NN1.getNode())
1019       AddToWorklist(NN1.getNode());
1020
1021     if (Replace0)
1022       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1023     if (Replace1)
1024       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1025
1026     DEBUG(dbgs() << "\nPromoting ";
1027           Op.getNode()->dump(&DAG));
1028     SDLoc dl(Op);
1029     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1031   }
1032   return SDValue();
1033 }
1034
1035 /// Promote the specified integer shift operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057
1058     bool Replace = false;
1059     SDValue N0 = Op.getOperand(0);
1060     if (Opc == ISD::SRA)
1061       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1062     else if (Opc == ISD::SRL)
1063       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1064     else
1065       N0 = PromoteOperand(N0, PVT, Replace);
1066     if (!N0.getNode())
1067       return SDValue();
1068
1069     AddToWorklist(N0.getNode());
1070     if (Replace)
1071       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           Op.getNode()->dump(&DAG));
1075     SDLoc dl(Op);
1076     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1078   }
1079   return SDValue();
1080 }
1081
1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083   if (!LegalOperations)
1084     return SDValue();
1085
1086   EVT VT = Op.getValueType();
1087   if (VT.isVector() || !VT.isInteger())
1088     return SDValue();
1089
1090   // If operation type is 'undesirable', e.g. i16 on x86, consider
1091   // promoting it.
1092   unsigned Opc = Op.getOpcode();
1093   if (TLI.isTypeDesirableForOp(Opc, VT))
1094     return SDValue();
1095
1096   EVT PVT = VT;
1097   // Consult target whether it is a good idea to promote this operation and
1098   // what's the right type to promote it to.
1099   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100     assert(PVT != VT && "Don't know what type to promote to!");
1101     // fold (aext (aext x)) -> (aext x)
1102     // fold (aext (zext x)) -> (zext x)
1103     // fold (aext (sext x)) -> (sext x)
1104     DEBUG(dbgs() << "\nPromoting ";
1105           Op.getNode()->dump(&DAG));
1106     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1107   }
1108   return SDValue();
1109 }
1110
1111 bool DAGCombiner::PromoteLoad(SDValue Op) {
1112   if (!LegalOperations)
1113     return false;
1114
1115   EVT VT = Op.getValueType();
1116   if (VT.isVector() || !VT.isInteger())
1117     return false;
1118
1119   // If operation type is 'undesirable', e.g. i16 on x86, consider
1120   // promoting it.
1121   unsigned Opc = Op.getOpcode();
1122   if (TLI.isTypeDesirableForOp(Opc, VT))
1123     return false;
1124
1125   EVT PVT = VT;
1126   // Consult target whether it is a good idea to promote this operation and
1127   // what's the right type to promote it to.
1128   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129     assert(PVT != VT && "Don't know what type to promote to!");
1130
1131     SDLoc dl(Op);
1132     SDNode *N = Op.getNode();
1133     LoadSDNode *LD = cast<LoadSDNode>(N);
1134     EVT MemVT = LD->getMemoryVT();
1135     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1136       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1137                                                        : ISD::EXTLOAD)
1138       : LD->getExtensionType();
1139     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1140                                    LD->getChain(), LD->getBasePtr(),
1141                                    MemVT, LD->getMemOperand());
1142     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1143
1144     DEBUG(dbgs() << "\nPromoting ";
1145           N->dump(&DAG);
1146           dbgs() << "\nTo: ";
1147           Result.getNode()->dump(&DAG);
1148           dbgs() << '\n');
1149     WorklistRemover DeadNodes(*this);
1150     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1152     deleteAndRecombine(N);
1153     AddToWorklist(Result.getNode());
1154     return true;
1155   }
1156   return false;
1157 }
1158
1159 /// \brief Recursively delete a node which has no uses and any operands for
1160 /// which it is the only use.
1161 ///
1162 /// Note that this both deletes the nodes and removes them from the worklist.
1163 /// It also adds any nodes who have had a user deleted to the worklist as they
1164 /// may now have only one use and subject to other combines.
1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166   if (!N->use_empty())
1167     return false;
1168
1169   SmallSetVector<SDNode *, 16> Nodes;
1170   Nodes.insert(N);
1171   do {
1172     N = Nodes.pop_back_val();
1173     if (!N)
1174       continue;
1175
1176     if (N->use_empty()) {
1177       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178         Nodes.insert(N->getOperand(i).getNode());
1179
1180       removeFromWorklist(N);
1181       DAG.DeleteNode(N);
1182     } else {
1183       AddToWorklist(N);
1184     }
1185   } while (!Nodes.empty());
1186   return true;
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 //  Main DAG Combiner implementation
1191 //===----------------------------------------------------------------------===//
1192
1193 void DAGCombiner::Run(CombineLevel AtLevel) {
1194   // set the instance variables, so that the various visit routines may use it.
1195   Level = AtLevel;
1196   LegalOperations = Level >= AfterLegalizeVectorOps;
1197   LegalTypes = Level >= AfterLegalizeTypes;
1198
1199   // Add all the dag nodes to the worklist.
1200   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201        E = DAG.allnodes_end(); I != E; ++I)
1202     AddToWorklist(I);
1203
1204   // Create a dummy node (which is not added to allnodes), that adds a reference
1205   // to the root node, preventing it from being deleted, and tracking any
1206   // changes of the root.
1207   HandleSDNode Dummy(DAG.getRoot());
1208
1209   // while the worklist isn't empty, find a node and
1210   // try and combine it.
1211   while (!WorklistMap.empty()) {
1212     SDNode *N;
1213     // The Worklist holds the SDNodes in order, but it may contain null entries.
1214     do {
1215       N = Worklist.pop_back_val();
1216     } while (!N);
1217
1218     bool GoodWorklistEntry = WorklistMap.erase(N);
1219     (void)GoodWorklistEntry;
1220     assert(GoodWorklistEntry &&
1221            "Found a worklist entry without a corresponding map entry!");
1222
1223     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1224     // N is deleted from the DAG, since they too may now be dead or may have a
1225     // reduced number of uses, allowing other xforms.
1226     if (recursivelyDeleteUnusedNodes(N))
1227       continue;
1228
1229     WorklistRemover DeadNodes(*this);
1230
1231     // If this combine is running after legalizing the DAG, re-legalize any
1232     // nodes pulled off the worklist.
1233     if (Level == AfterLegalizeDAG) {
1234       SmallSetVector<SDNode *, 16> UpdatedNodes;
1235       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1236
1237       for (SDNode *LN : UpdatedNodes) {
1238         AddToWorklist(LN);
1239         AddUsersToWorklist(LN);
1240       }
1241       if (!NIsValid)
1242         continue;
1243     }
1244
1245     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1246
1247     // Add any operands of the new node which have not yet been combined to the
1248     // worklist as well. Because the worklist uniques things already, this
1249     // won't repeatedly process the same operand.
1250     CombinedNodes.insert(N);
1251     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253         AddToWorklist(N->getOperand(i).getNode());
1254
1255     SDValue RV = combine(N);
1256
1257     if (!RV.getNode())
1258       continue;
1259
1260     ++NodesCombined;
1261
1262     // If we get back the same node we passed in, rather than a new node or
1263     // zero, we know that the node must have defined multiple values and
1264     // CombineTo was used.  Since CombineTo takes care of the worklist
1265     // mechanics for us, we have no work to do in this case.
1266     if (RV.getNode() == N)
1267       continue;
1268
1269     assert(N->getOpcode() != ISD::DELETED_NODE &&
1270            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271            "Node was deleted but visit returned new node!");
1272
1273     DEBUG(dbgs() << " ... into: ";
1274           RV.getNode()->dump(&DAG));
1275
1276     // Transfer debug value.
1277     DAG.TransferDbgValues(SDValue(N, 0), RV);
1278     if (N->getNumValues() == RV.getNode()->getNumValues())
1279       DAG.ReplaceAllUsesWith(N, RV.getNode());
1280     else {
1281       assert(N->getValueType(0) == RV.getValueType() &&
1282              N->getNumValues() == 1 && "Type mismatch");
1283       SDValue OpV = RV;
1284       DAG.ReplaceAllUsesWith(N, &OpV);
1285     }
1286
1287     // Push the new node and any users onto the worklist
1288     AddToWorklist(RV.getNode());
1289     AddUsersToWorklist(RV.getNode());
1290
1291     // Finally, if the node is now dead, remove it from the graph.  The node
1292     // may not be dead if the replacement process recursively simplified to
1293     // something else needing this node. This will also take care of adding any
1294     // operands which have lost a user to the worklist.
1295     recursivelyDeleteUnusedNodes(N);
1296   }
1297
1298   // If the root changed (e.g. it was a dead load, update the root).
1299   DAG.setRoot(Dummy.getValue());
1300   DAG.RemoveDeadNodes();
1301 }
1302
1303 SDValue DAGCombiner::visit(SDNode *N) {
1304   switch (N->getOpcode()) {
1305   default: break;
1306   case ISD::TokenFactor:        return visitTokenFactor(N);
1307   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1308   case ISD::ADD:                return visitADD(N);
1309   case ISD::SUB:                return visitSUB(N);
1310   case ISD::ADDC:               return visitADDC(N);
1311   case ISD::SUBC:               return visitSUBC(N);
1312   case ISD::ADDE:               return visitADDE(N);
1313   case ISD::SUBE:               return visitSUBE(N);
1314   case ISD::MUL:                return visitMUL(N);
1315   case ISD::SDIV:               return visitSDIV(N);
1316   case ISD::UDIV:               return visitUDIV(N);
1317   case ISD::SREM:               return visitSREM(N);
1318   case ISD::UREM:               return visitUREM(N);
1319   case ISD::MULHU:              return visitMULHU(N);
1320   case ISD::MULHS:              return visitMULHS(N);
1321   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1322   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1323   case ISD::SMULO:              return visitSMULO(N);
1324   case ISD::UMULO:              return visitUMULO(N);
1325   case ISD::SDIVREM:            return visitSDIVREM(N);
1326   case ISD::UDIVREM:            return visitUDIVREM(N);
1327   case ISD::AND:                return visitAND(N);
1328   case ISD::OR:                 return visitOR(N);
1329   case ISD::XOR:                return visitXOR(N);
1330   case ISD::SHL:                return visitSHL(N);
1331   case ISD::SRA:                return visitSRA(N);
1332   case ISD::SRL:                return visitSRL(N);
1333   case ISD::ROTR:
1334   case ISD::ROTL:               return visitRotate(N);
1335   case ISD::CTLZ:               return visitCTLZ(N);
1336   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1337   case ISD::CTTZ:               return visitCTTZ(N);
1338   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1339   case ISD::CTPOP:              return visitCTPOP(N);
1340   case ISD::SELECT:             return visitSELECT(N);
1341   case ISD::VSELECT:            return visitVSELECT(N);
1342   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1343   case ISD::SETCC:              return visitSETCC(N);
1344   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1345   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1346   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1347   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1348   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1349   case ISD::BITCAST:            return visitBITCAST(N);
1350   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1351   case ISD::FADD:               return visitFADD(N);
1352   case ISD::FSUB:               return visitFSUB(N);
1353   case ISD::FMUL:               return visitFMUL(N);
1354   case ISD::FMA:                return visitFMA(N);
1355   case ISD::FDIV:               return visitFDIV(N);
1356   case ISD::FREM:               return visitFREM(N);
1357   case ISD::FSQRT:              return visitFSQRT(N);
1358   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1359   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1360   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1361   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1362   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1363   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1364   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1365   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1366   case ISD::FNEG:               return visitFNEG(N);
1367   case ISD::FABS:               return visitFABS(N);
1368   case ISD::FFLOOR:             return visitFFLOOR(N);
1369   case ISD::FMINNUM:            return visitFMINNUM(N);
1370   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1371   case ISD::FCEIL:              return visitFCEIL(N);
1372   case ISD::FTRUNC:             return visitFTRUNC(N);
1373   case ISD::BRCOND:             return visitBRCOND(N);
1374   case ISD::BR_CC:              return visitBR_CC(N);
1375   case ISD::LOAD:               return visitLOAD(N);
1376   case ISD::STORE:              return visitSTORE(N);
1377   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1378   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1379   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1380   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1381   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1382   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1383   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1384   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1385   case ISD::MLOAD:              return visitMLOAD(N);
1386   case ISD::MSTORE:             return visitMSTORE(N);
1387   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1388   }
1389   return SDValue();
1390 }
1391
1392 SDValue DAGCombiner::combine(SDNode *N) {
1393   SDValue RV = visit(N);
1394
1395   // If nothing happened, try a target-specific DAG combine.
1396   if (!RV.getNode()) {
1397     assert(N->getOpcode() != ISD::DELETED_NODE &&
1398            "Node was deleted but visit returned NULL!");
1399
1400     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1402
1403       // Expose the DAG combiner to the target combiner impls.
1404       TargetLowering::DAGCombinerInfo
1405         DagCombineInfo(DAG, Level, false, this);
1406
1407       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1408     }
1409   }
1410
1411   // If nothing happened still, try promoting the operation.
1412   if (!RV.getNode()) {
1413     switch (N->getOpcode()) {
1414     default: break;
1415     case ISD::ADD:
1416     case ISD::SUB:
1417     case ISD::MUL:
1418     case ISD::AND:
1419     case ISD::OR:
1420     case ISD::XOR:
1421       RV = PromoteIntBinOp(SDValue(N, 0));
1422       break;
1423     case ISD::SHL:
1424     case ISD::SRA:
1425     case ISD::SRL:
1426       RV = PromoteIntShiftOp(SDValue(N, 0));
1427       break;
1428     case ISD::SIGN_EXTEND:
1429     case ISD::ZERO_EXTEND:
1430     case ISD::ANY_EXTEND:
1431       RV = PromoteExtend(SDValue(N, 0));
1432       break;
1433     case ISD::LOAD:
1434       if (PromoteLoad(SDValue(N, 0)))
1435         RV = SDValue(N, 0);
1436       break;
1437     }
1438   }
1439
1440   // If N is a commutative binary node, try commuting it to enable more
1441   // sdisel CSE.
1442   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1443       N->getNumValues() == 1) {
1444     SDValue N0 = N->getOperand(0);
1445     SDValue N1 = N->getOperand(1);
1446
1447     // Constant operands are canonicalized to RHS.
1448     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1449       SDValue Ops[] = {N1, N0};
1450       SDNode *CSENode;
1451       if (const BinaryWithFlagsSDNode *BinNode =
1452               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453         CSENode = DAG.getNodeIfExists(
1454             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1455             BinNode->hasNoSignedWrap(), BinNode->isExact());
1456       } else {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1458       }
1459       if (CSENode)
1460         return SDValue(CSENode, 0);
1461     }
1462   }
1463
1464   return RV;
1465 }
1466
1467 /// Given a node, return its input chain if it has one, otherwise return a null
1468 /// sd operand.
1469 static SDValue getInputChainForNode(SDNode *N) {
1470   if (unsigned NumOps = N->getNumOperands()) {
1471     if (N->getOperand(0).getValueType() == MVT::Other)
1472       return N->getOperand(0);
1473     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1474       return N->getOperand(NumOps-1);
1475     for (unsigned i = 1; i < NumOps-1; ++i)
1476       if (N->getOperand(i).getValueType() == MVT::Other)
1477         return N->getOperand(i);
1478   }
1479   return SDValue();
1480 }
1481
1482 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1483   // If N has two operands, where one has an input chain equal to the other,
1484   // the 'other' chain is redundant.
1485   if (N->getNumOperands() == 2) {
1486     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1487       return N->getOperand(0);
1488     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1489       return N->getOperand(1);
1490   }
1491
1492   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1493   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1494   SmallPtrSet<SDNode*, 16> SeenOps;
1495   bool Changed = false;             // If we should replace this token factor.
1496
1497   // Start out with this token factor.
1498   TFs.push_back(N);
1499
1500   // Iterate through token factors.  The TFs grows when new token factors are
1501   // encountered.
1502   for (unsigned i = 0; i < TFs.size(); ++i) {
1503     SDNode *TF = TFs[i];
1504
1505     // Check each of the operands.
1506     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1507       SDValue Op = TF->getOperand(i);
1508
1509       switch (Op.getOpcode()) {
1510       case ISD::EntryToken:
1511         // Entry tokens don't need to be added to the list. They are
1512         // redundant.
1513         Changed = true;
1514         break;
1515
1516       case ISD::TokenFactor:
1517         if (Op.hasOneUse() &&
1518             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1519           // Queue up for processing.
1520           TFs.push_back(Op.getNode());
1521           // Clean up in case the token factor is removed.
1522           AddToWorklist(Op.getNode());
1523           Changed = true;
1524           break;
1525         }
1526         // Fall thru
1527
1528       default:
1529         // Only add if it isn't already in the list.
1530         if (SeenOps.insert(Op.getNode()).second)
1531           Ops.push_back(Op);
1532         else
1533           Changed = true;
1534         break;
1535       }
1536     }
1537   }
1538
1539   SDValue Result;
1540
1541   // If we've changed things around then replace token factor.
1542   if (Changed) {
1543     if (Ops.empty()) {
1544       // The entry token is the only possible outcome.
1545       Result = DAG.getEntryNode();
1546     } else {
1547       // New and improved token factor.
1548       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1549     }
1550
1551     // Add users to worklist if AA is enabled, since it may introduce
1552     // a lot of new chained token factors while removing memory deps.
1553     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1554       : DAG.getSubtarget().useAA();
1555     return CombineTo(N, Result, UseAA /*add to worklist*/);
1556   }
1557
1558   return Result;
1559 }
1560
1561 /// MERGE_VALUES can always be eliminated.
1562 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1563   WorklistRemover DeadNodes(*this);
1564   // Replacing results may cause a different MERGE_VALUES to suddenly
1565   // be CSE'd with N, and carry its uses with it. Iterate until no
1566   // uses remain, to ensure that the node can be safely deleted.
1567   // First add the users of this node to the work list so that they
1568   // can be tried again once they have new operands.
1569   AddUsersToWorklist(N);
1570   do {
1571     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1572       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1573   } while (!N->use_empty());
1574   deleteAndRecombine(N);
1575   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1576 }
1577
1578 SDValue DAGCombiner::visitADD(SDNode *N) {
1579   SDValue N0 = N->getOperand(0);
1580   SDValue N1 = N->getOperand(1);
1581   EVT VT = N0.getValueType();
1582
1583   // fold vector ops
1584   if (VT.isVector()) {
1585     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1586       return FoldedVOp;
1587
1588     // fold (add x, 0) -> x, vector edition
1589     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1590       return N0;
1591     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1592       return N1;
1593   }
1594
1595   // fold (add x, undef) -> undef
1596   if (N0.getOpcode() == ISD::UNDEF)
1597     return N0;
1598   if (N1.getOpcode() == ISD::UNDEF)
1599     return N1;
1600   // fold (add c1, c2) -> c1+c2
1601   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1603   if (N0C && N1C)
1604     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1605   // canonicalize constant to RHS
1606   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1607      !isConstantIntBuildVectorOrConstantInt(N1))
1608     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1609   // fold (add x, 0) -> x
1610   if (N1C && N1C->isNullValue())
1611     return N0;
1612   // fold (add Sym, c) -> Sym+c
1613   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1614     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1615         GA->getOpcode() == ISD::GlobalAddress)
1616       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1617                                   GA->getOffset() +
1618                                     (uint64_t)N1C->getSExtValue());
1619   // fold ((c1-A)+c2) -> (c1+c2)-A
1620   if (N1C && N0.getOpcode() == ISD::SUB)
1621     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1622       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1623                          DAG.getConstant(N1C->getAPIntValue()+
1624                                          N0C->getAPIntValue(), VT),
1625                          N0.getOperand(1));
1626   // reassociate add
1627   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1628     return RADD;
1629   // fold ((0-A) + B) -> B-A
1630   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1631       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1632     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1633   // fold (A + (0-B)) -> A-B
1634   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1635       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1636     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1637   // fold (A+(B-A)) -> B
1638   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1639     return N1.getOperand(0);
1640   // fold ((B-A)+A) -> B
1641   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1642     return N0.getOperand(0);
1643   // fold (A+(B-(A+C))) to (B-C)
1644   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1645       N0 == N1.getOperand(1).getOperand(0))
1646     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1647                        N1.getOperand(1).getOperand(1));
1648   // fold (A+(B-(C+A))) to (B-C)
1649   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1650       N0 == N1.getOperand(1).getOperand(1))
1651     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1652                        N1.getOperand(1).getOperand(0));
1653   // fold (A+((B-A)+or-C)) to (B+or-C)
1654   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1655       N1.getOperand(0).getOpcode() == ISD::SUB &&
1656       N0 == N1.getOperand(0).getOperand(1))
1657     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1658                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1659
1660   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1661   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1662     SDValue N00 = N0.getOperand(0);
1663     SDValue N01 = N0.getOperand(1);
1664     SDValue N10 = N1.getOperand(0);
1665     SDValue N11 = N1.getOperand(1);
1666
1667     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1668       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1669                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1670                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1671   }
1672
1673   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1674     return SDValue(N, 0);
1675
1676   // fold (a+b) -> (a|b) iff a and b share no bits.
1677   if (VT.isInteger() && !VT.isVector()) {
1678     APInt LHSZero, LHSOne;
1679     APInt RHSZero, RHSOne;
1680     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1681
1682     if (LHSZero.getBoolValue()) {
1683       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1684
1685       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1686       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1687       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1688         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1689           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1690       }
1691     }
1692   }
1693
1694   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1695   if (N1.getOpcode() == ISD::SHL &&
1696       N1.getOperand(0).getOpcode() == ISD::SUB)
1697     if (ConstantSDNode *C =
1698           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1699       if (C->getAPIntValue() == 0)
1700         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1701                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1702                                        N1.getOperand(0).getOperand(1),
1703                                        N1.getOperand(1)));
1704   if (N0.getOpcode() == ISD::SHL &&
1705       N0.getOperand(0).getOpcode() == ISD::SUB)
1706     if (ConstantSDNode *C =
1707           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1708       if (C->getAPIntValue() == 0)
1709         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1710                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1711                                        N0.getOperand(0).getOperand(1),
1712                                        N0.getOperand(1)));
1713
1714   if (N1.getOpcode() == ISD::AND) {
1715     SDValue AndOp0 = N1.getOperand(0);
1716     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1717     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1718     unsigned DestBits = VT.getScalarType().getSizeInBits();
1719
1720     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1721     // and similar xforms where the inner op is either ~0 or 0.
1722     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1723       SDLoc DL(N);
1724       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1725     }
1726   }
1727
1728   // add (sext i1), X -> sub X, (zext i1)
1729   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1730       N0.getOperand(0).getValueType() == MVT::i1 &&
1731       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1732     SDLoc DL(N);
1733     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1734     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1735   }
1736
1737   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1738   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1739     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1740     if (TN->getVT() == MVT::i1) {
1741       SDLoc DL(N);
1742       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1743                                  DAG.getConstant(1, VT));
1744       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1745     }
1746   }
1747
1748   return SDValue();
1749 }
1750
1751 SDValue DAGCombiner::visitADDC(SDNode *N) {
1752   SDValue N0 = N->getOperand(0);
1753   SDValue N1 = N->getOperand(1);
1754   EVT VT = N0.getValueType();
1755
1756   // If the flag result is dead, turn this into an ADD.
1757   if (!N->hasAnyUseOfValue(1))
1758     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1759                      DAG.getNode(ISD::CARRY_FALSE,
1760                                  SDLoc(N), MVT::Glue));
1761
1762   // canonicalize constant to RHS.
1763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1765   if (N0C && !N1C)
1766     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1767
1768   // fold (addc x, 0) -> x + no carry out
1769   if (N1C && N1C->isNullValue())
1770     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1771                                         SDLoc(N), MVT::Glue));
1772
1773   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1774   APInt LHSZero, LHSOne;
1775   APInt RHSZero, RHSOne;
1776   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1777
1778   if (LHSZero.getBoolValue()) {
1779     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1780
1781     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1782     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1783     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1784       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1785                        DAG.getNode(ISD::CARRY_FALSE,
1786                                    SDLoc(N), MVT::Glue));
1787   }
1788
1789   return SDValue();
1790 }
1791
1792 SDValue DAGCombiner::visitADDE(SDNode *N) {
1793   SDValue N0 = N->getOperand(0);
1794   SDValue N1 = N->getOperand(1);
1795   SDValue CarryIn = N->getOperand(2);
1796
1797   // canonicalize constant to RHS
1798   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1799   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1800   if (N0C && !N1C)
1801     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1802                        N1, N0, CarryIn);
1803
1804   // fold (adde x, y, false) -> (addc x, y)
1805   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1806     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1807
1808   return SDValue();
1809 }
1810
1811 // Since it may not be valid to emit a fold to zero for vector initializers
1812 // check if we can before folding.
1813 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1814                              SelectionDAG &DAG,
1815                              bool LegalOperations, bool LegalTypes) {
1816   if (!VT.isVector())
1817     return DAG.getConstant(0, VT);
1818   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1819     return DAG.getConstant(0, VT);
1820   return SDValue();
1821 }
1822
1823 SDValue DAGCombiner::visitSUB(SDNode *N) {
1824   SDValue N0 = N->getOperand(0);
1825   SDValue N1 = N->getOperand(1);
1826   EVT VT = N0.getValueType();
1827
1828   // fold vector ops
1829   if (VT.isVector()) {
1830     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1831       return FoldedVOp;
1832
1833     // fold (sub x, 0) -> x, vector edition
1834     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1835       return N0;
1836   }
1837
1838   // fold (sub x, x) -> 0
1839   // FIXME: Refactor this and xor and other similar operations together.
1840   if (N0 == N1)
1841     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1842   // fold (sub c1, c2) -> c1-c2
1843   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1844   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1845   if (N0C && N1C)
1846     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1847   // fold (sub x, c) -> (add x, -c)
1848   if (N1C)
1849     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1850                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1851   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1852   if (N0C && N0C->isAllOnesValue())
1853     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1854   // fold A-(A-B) -> B
1855   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1856     return N1.getOperand(1);
1857   // fold (A+B)-A -> B
1858   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1859     return N0.getOperand(1);
1860   // fold (A+B)-B -> A
1861   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1862     return N0.getOperand(0);
1863   // fold C2-(A+C1) -> (C2-C1)-A
1864   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1865     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1866   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1867     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1868                                    VT);
1869     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1870                        N1.getOperand(0));
1871   }
1872   // fold ((A+(B+or-C))-B) -> A+or-C
1873   if (N0.getOpcode() == ISD::ADD &&
1874       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1875        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1876       N0.getOperand(1).getOperand(0) == N1)
1877     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1878                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1879   // fold ((A+(C+B))-B) -> A+C
1880   if (N0.getOpcode() == ISD::ADD &&
1881       N0.getOperand(1).getOpcode() == ISD::ADD &&
1882       N0.getOperand(1).getOperand(1) == N1)
1883     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1884                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1885   // fold ((A-(B-C))-C) -> A-B
1886   if (N0.getOpcode() == ISD::SUB &&
1887       N0.getOperand(1).getOpcode() == ISD::SUB &&
1888       N0.getOperand(1).getOperand(1) == N1)
1889     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1890                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1891
1892   // If either operand of a sub is undef, the result is undef
1893   if (N0.getOpcode() == ISD::UNDEF)
1894     return N0;
1895   if (N1.getOpcode() == ISD::UNDEF)
1896     return N1;
1897
1898   // If the relocation model supports it, consider symbol offsets.
1899   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1900     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1901       // fold (sub Sym, c) -> Sym-c
1902       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1903         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1904                                     GA->getOffset() -
1905                                       (uint64_t)N1C->getSExtValue());
1906       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1907       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1908         if (GA->getGlobal() == GB->getGlobal())
1909           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1910                                  VT);
1911     }
1912
1913   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1914   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1915     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1916     if (TN->getVT() == MVT::i1) {
1917       SDLoc DL(N);
1918       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1919                                  DAG.getConstant(1, VT));
1920       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1921     }
1922   }
1923
1924   return SDValue();
1925 }
1926
1927 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1928   SDValue N0 = N->getOperand(0);
1929   SDValue N1 = N->getOperand(1);
1930   EVT VT = N0.getValueType();
1931
1932   // If the flag result is dead, turn this into an SUB.
1933   if (!N->hasAnyUseOfValue(1))
1934     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1935                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1936                                  MVT::Glue));
1937
1938   // fold (subc x, x) -> 0 + no borrow
1939   if (N0 == N1)
1940     return CombineTo(N, DAG.getConstant(0, VT),
1941                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1942                                  MVT::Glue));
1943
1944   // fold (subc x, 0) -> x + no borrow
1945   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1946   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1947   if (N1C && N1C->isNullValue())
1948     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1949                                         MVT::Glue));
1950
1951   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1952   if (N0C && N0C->isAllOnesValue())
1953     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1954                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1955                                  MVT::Glue));
1956
1957   return SDValue();
1958 }
1959
1960 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1961   SDValue N0 = N->getOperand(0);
1962   SDValue N1 = N->getOperand(1);
1963   SDValue CarryIn = N->getOperand(2);
1964
1965   // fold (sube x, y, false) -> (subc x, y)
1966   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1967     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1968
1969   return SDValue();
1970 }
1971
1972 SDValue DAGCombiner::visitMUL(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   EVT VT = N0.getValueType();
1976
1977   // fold (mul x, undef) -> 0
1978   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1979     return DAG.getConstant(0, VT);
1980
1981   bool N0IsConst = false;
1982   bool N1IsConst = false;
1983   APInt ConstValue0, ConstValue1;
1984   // fold vector ops
1985   if (VT.isVector()) {
1986     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1987       return FoldedVOp;
1988
1989     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1990     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1991   } else {
1992     N0IsConst = isa<ConstantSDNode>(N0);
1993     if (N0IsConst)
1994       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
1995     N1IsConst = isa<ConstantSDNode>(N1);
1996     if (N1IsConst)
1997       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
1998   }
1999
2000   // fold (mul c1, c2) -> c1*c2
2001   if (N0IsConst && N1IsConst)
2002     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
2003
2004   // canonicalize constant to RHS (vector doesn't have to splat)
2005   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2006      !isConstantIntBuildVectorOrConstantInt(N1))
2007     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2008   // fold (mul x, 0) -> 0
2009   if (N1IsConst && ConstValue1 == 0)
2010     return N1;
2011   // We require a splat of the entire scalar bit width for non-contiguous
2012   // bit patterns.
2013   bool IsFullSplat =
2014     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2015   // fold (mul x, 1) -> x
2016   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2017     return N0;
2018   // fold (mul x, -1) -> 0-x
2019   if (N1IsConst && ConstValue1.isAllOnesValue())
2020     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021                        DAG.getConstant(0, VT), N0);
2022   // fold (mul x, (1 << c)) -> x << c
2023   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2024     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025                        DAG.getConstant(ConstValue1.logBase2(),
2026                                        getShiftAmountTy(N0.getValueType())));
2027   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2028   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2029     unsigned Log2Val = (-ConstValue1).logBase2();
2030     // FIXME: If the input is something that is easily negated (e.g. a
2031     // single-use add), we should put the negate there.
2032     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2033                        DAG.getConstant(0, VT),
2034                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2035                             DAG.getConstant(Log2Val,
2036                                       getShiftAmountTy(N0.getValueType()))));
2037   }
2038
2039   APInt Val;
2040   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2041   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2042       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2044     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2045                              N1, N0.getOperand(1));
2046     AddToWorklist(C3.getNode());
2047     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2048                        N0.getOperand(0), C3);
2049   }
2050
2051   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2052   // use.
2053   {
2054     SDValue Sh(nullptr,0), Y(nullptr,0);
2055     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2056     if (N0.getOpcode() == ISD::SHL &&
2057         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2059         N0.getNode()->hasOneUse()) {
2060       Sh = N0; Y = N1;
2061     } else if (N1.getOpcode() == ISD::SHL &&
2062                isa<ConstantSDNode>(N1.getOperand(1)) &&
2063                N1.getNode()->hasOneUse()) {
2064       Sh = N1; Y = N0;
2065     }
2066
2067     if (Sh.getNode()) {
2068       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2069                                 Sh.getOperand(0), Y);
2070       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2071                          Mul, Sh.getOperand(1));
2072     }
2073   }
2074
2075   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2076   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2077       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2078                      isa<ConstantSDNode>(N0.getOperand(1))))
2079     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2080                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2081                                    N0.getOperand(0), N1),
2082                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2083                                    N0.getOperand(1), N1));
2084
2085   // reassociate mul
2086   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2087     return RMUL;
2088
2089   return SDValue();
2090 }
2091
2092 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2093   SDValue N0 = N->getOperand(0);
2094   SDValue N1 = N->getOperand(1);
2095   EVT VT = N->getValueType(0);
2096
2097   // fold vector ops
2098   if (VT.isVector())
2099     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2100       return FoldedVOp;
2101
2102   // fold (sdiv c1, c2) -> c1/c2
2103   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2104   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2105   if (N0C && N1C && !N1C->isNullValue())
2106     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2107   // fold (sdiv X, 1) -> X
2108   if (N1C && N1C->getAPIntValue() == 1LL)
2109     return N0;
2110   // fold (sdiv X, -1) -> 0-X
2111   if (N1C && N1C->isAllOnesValue())
2112     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2113                        DAG.getConstant(0, VT), N0);
2114   // If we know the sign bits of both operands are zero, strength reduce to a
2115   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2116   if (!VT.isVector()) {
2117     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2118       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2119                          N0, N1);
2120   }
2121
2122   // fold (sdiv X, pow2) -> simple ops after legalize
2123   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2124                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2125     // If dividing by powers of two is cheap, then don't perform the following
2126     // fold.
2127     if (TLI.isPow2SDivCheap())
2128       return SDValue();
2129
2130     // Target-specific implementation of sdiv x, pow2.
2131     SDValue Res = BuildSDIVPow2(N);
2132     if (Res.getNode())
2133       return Res;
2134
2135     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2136
2137     // Splat the sign bit into the register
2138     SDValue SGN =
2139         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2140                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2141                                     getShiftAmountTy(N0.getValueType())));
2142     AddToWorklist(SGN.getNode());
2143
2144     // Add (N0 < 0) ? abs2 - 1 : 0;
2145     SDValue SRL =
2146         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2147                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2148                                     getShiftAmountTy(SGN.getValueType())));
2149     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2150     AddToWorklist(SRL.getNode());
2151     AddToWorklist(ADD.getNode());    // Divide by pow2
2152     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2153                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2154
2155     // If we're dividing by a positive value, we're done.  Otherwise, we must
2156     // negate the result.
2157     if (N1C->getAPIntValue().isNonNegative())
2158       return SRA;
2159
2160     AddToWorklist(SRA.getNode());
2161     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2162   }
2163
2164   // If integer divide is expensive and we satisfy the requirements, emit an
2165   // alternate sequence.
2166   if (N1C && !TLI.isIntDivCheap()) {
2167     SDValue Op = BuildSDIV(N);
2168     if (Op.getNode()) return Op;
2169   }
2170
2171   // undef / X -> 0
2172   if (N0.getOpcode() == ISD::UNDEF)
2173     return DAG.getConstant(0, VT);
2174   // X / undef -> undef
2175   if (N1.getOpcode() == ISD::UNDEF)
2176     return N1;
2177
2178   return SDValue();
2179 }
2180
2181 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2182   SDValue N0 = N->getOperand(0);
2183   SDValue N1 = N->getOperand(1);
2184   EVT VT = N->getValueType(0);
2185
2186   // fold vector ops
2187   if (VT.isVector())
2188     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2189       return FoldedVOp;
2190
2191   // fold (udiv c1, c2) -> c1/c2
2192   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2193   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2194   if (N0C && N1C && !N1C->isNullValue())
2195     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2196   // fold (udiv x, (1 << c)) -> x >>u c
2197   if (N1C && N1C->getAPIntValue().isPowerOf2())
2198     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2199                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2200                                        getShiftAmountTy(N0.getValueType())));
2201   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2202   if (N1.getOpcode() == ISD::SHL) {
2203     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2204       if (SHC->getAPIntValue().isPowerOf2()) {
2205         EVT ADDVT = N1.getOperand(1).getValueType();
2206         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2207                                   N1.getOperand(1),
2208                                   DAG.getConstant(SHC->getAPIntValue()
2209                                                                   .logBase2(),
2210                                                   ADDVT));
2211         AddToWorklist(Add.getNode());
2212         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2213       }
2214     }
2215   }
2216   // fold (udiv x, c) -> alternate
2217   if (N1C && !TLI.isIntDivCheap()) {
2218     SDValue Op = BuildUDIV(N);
2219     if (Op.getNode()) return Op;
2220   }
2221
2222   // undef / X -> 0
2223   if (N0.getOpcode() == ISD::UNDEF)
2224     return DAG.getConstant(0, VT);
2225   // X / undef -> undef
2226   if (N1.getOpcode() == ISD::UNDEF)
2227     return N1;
2228
2229   return SDValue();
2230 }
2231
2232 SDValue DAGCombiner::visitSREM(SDNode *N) {
2233   SDValue N0 = N->getOperand(0);
2234   SDValue N1 = N->getOperand(1);
2235   EVT VT = N->getValueType(0);
2236
2237   // fold (srem c1, c2) -> c1%c2
2238   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2240   if (N0C && N1C && !N1C->isNullValue())
2241     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2242   // If we know the sign bits of both operands are zero, strength reduce to a
2243   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2244   if (!VT.isVector()) {
2245     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2246       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2247   }
2248
2249   // If X/C can be simplified by the division-by-constant logic, lower
2250   // X%C to the equivalent of X-X/C*C.
2251   if (N1C && !N1C->isNullValue()) {
2252     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2253     AddToWorklist(Div.getNode());
2254     SDValue OptimizedDiv = combine(Div.getNode());
2255     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2256       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2257                                 OptimizedDiv, N1);
2258       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2259       AddToWorklist(Mul.getNode());
2260       return Sub;
2261     }
2262   }
2263
2264   // undef % X -> 0
2265   if (N0.getOpcode() == ISD::UNDEF)
2266     return DAG.getConstant(0, VT);
2267   // X % undef -> undef
2268   if (N1.getOpcode() == ISD::UNDEF)
2269     return N1;
2270
2271   return SDValue();
2272 }
2273
2274 SDValue DAGCombiner::visitUREM(SDNode *N) {
2275   SDValue N0 = N->getOperand(0);
2276   SDValue N1 = N->getOperand(1);
2277   EVT VT = N->getValueType(0);
2278
2279   // fold (urem c1, c2) -> c1%c2
2280   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2281   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2282   if (N0C && N1C && !N1C->isNullValue())
2283     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2284   // fold (urem x, pow2) -> (and x, pow2-1)
2285   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2286     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2287                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2288   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2289   if (N1.getOpcode() == ISD::SHL) {
2290     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2291       if (SHC->getAPIntValue().isPowerOf2()) {
2292         SDValue Add =
2293           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2294                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2295                                  VT));
2296         AddToWorklist(Add.getNode());
2297         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2298       }
2299     }
2300   }
2301
2302   // If X/C can be simplified by the division-by-constant logic, lower
2303   // X%C to the equivalent of X-X/C*C.
2304   if (N1C && !N1C->isNullValue()) {
2305     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2306     AddToWorklist(Div.getNode());
2307     SDValue OptimizedDiv = combine(Div.getNode());
2308     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2309       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2310                                 OptimizedDiv, N1);
2311       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2312       AddToWorklist(Mul.getNode());
2313       return Sub;
2314     }
2315   }
2316
2317   // undef % X -> 0
2318   if (N0.getOpcode() == ISD::UNDEF)
2319     return DAG.getConstant(0, VT);
2320   // X % undef -> undef
2321   if (N1.getOpcode() == ISD::UNDEF)
2322     return N1;
2323
2324   return SDValue();
2325 }
2326
2327 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2328   SDValue N0 = N->getOperand(0);
2329   SDValue N1 = N->getOperand(1);
2330   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2331   EVT VT = N->getValueType(0);
2332   SDLoc DL(N);
2333
2334   // fold (mulhs x, 0) -> 0
2335   if (N1C && N1C->isNullValue())
2336     return N1;
2337   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2338   if (N1C && N1C->getAPIntValue() == 1)
2339     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2340                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2341                                        getShiftAmountTy(N0.getValueType())));
2342   // fold (mulhs x, undef) -> 0
2343   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2344     return DAG.getConstant(0, VT);
2345
2346   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2347   // plus a shift.
2348   if (VT.isSimple() && !VT.isVector()) {
2349     MVT Simple = VT.getSimpleVT();
2350     unsigned SimpleSize = Simple.getSizeInBits();
2351     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2352     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2353       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2354       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2355       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2356       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2357             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2358       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2359     }
2360   }
2361
2362   return SDValue();
2363 }
2364
2365 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2366   SDValue N0 = N->getOperand(0);
2367   SDValue N1 = N->getOperand(1);
2368   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2369   EVT VT = N->getValueType(0);
2370   SDLoc DL(N);
2371
2372   // fold (mulhu x, 0) -> 0
2373   if (N1C && N1C->isNullValue())
2374     return N1;
2375   // fold (mulhu x, 1) -> 0
2376   if (N1C && N1C->getAPIntValue() == 1)
2377     return DAG.getConstant(0, N0.getValueType());
2378   // fold (mulhu x, undef) -> 0
2379   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2380     return DAG.getConstant(0, VT);
2381
2382   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2383   // plus a shift.
2384   if (VT.isSimple() && !VT.isVector()) {
2385     MVT Simple = VT.getSimpleVT();
2386     unsigned SimpleSize = Simple.getSizeInBits();
2387     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2390       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2391       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2392       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2393             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2394       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2395     }
2396   }
2397
2398   return SDValue();
2399 }
2400
2401 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2402 /// give the opcodes for the two computations that are being performed. Return
2403 /// true if a simplification was made.
2404 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2405                                                 unsigned HiOp) {
2406   // If the high half is not needed, just compute the low half.
2407   bool HiExists = N->hasAnyUseOfValue(1);
2408   if (!HiExists &&
2409       (!LegalOperations ||
2410        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2411     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2412     return CombineTo(N, Res, Res);
2413   }
2414
2415   // If the low half is not needed, just compute the high half.
2416   bool LoExists = N->hasAnyUseOfValue(0);
2417   if (!LoExists &&
2418       (!LegalOperations ||
2419        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2420     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2421     return CombineTo(N, Res, Res);
2422   }
2423
2424   // If both halves are used, return as it is.
2425   if (LoExists && HiExists)
2426     return SDValue();
2427
2428   // If the two computed results can be simplified separately, separate them.
2429   if (LoExists) {
2430     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2431     AddToWorklist(Lo.getNode());
2432     SDValue LoOpt = combine(Lo.getNode());
2433     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2434         (!LegalOperations ||
2435          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2436       return CombineTo(N, LoOpt, LoOpt);
2437   }
2438
2439   if (HiExists) {
2440     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2441     AddToWorklist(Hi.getNode());
2442     SDValue HiOpt = combine(Hi.getNode());
2443     if (HiOpt.getNode() && HiOpt != Hi &&
2444         (!LegalOperations ||
2445          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2446       return CombineTo(N, HiOpt, HiOpt);
2447   }
2448
2449   return SDValue();
2450 }
2451
2452 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2453   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2454   if (Res.getNode()) return Res;
2455
2456   EVT VT = N->getValueType(0);
2457   SDLoc DL(N);
2458
2459   // If the type is twice as wide is legal, transform the mulhu to a wider
2460   // multiply plus a shift.
2461   if (VT.isSimple() && !VT.isVector()) {
2462     MVT Simple = VT.getSimpleVT();
2463     unsigned SimpleSize = Simple.getSizeInBits();
2464     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2467       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2468       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469       // Compute the high part as N1.
2470       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2471             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2472       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473       // Compute the low part as N0.
2474       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475       return CombineTo(N, Lo, Hi);
2476     }
2477   }
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2483   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2484   if (Res.getNode()) return Res;
2485
2486   EVT VT = N->getValueType(0);
2487   SDLoc DL(N);
2488
2489   // If the type is twice as wide is legal, transform the mulhu to a wider
2490   // multiply plus a shift.
2491   if (VT.isSimple() && !VT.isVector()) {
2492     MVT Simple = VT.getSimpleVT();
2493     unsigned SimpleSize = Simple.getSizeInBits();
2494     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2495     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2496       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2497       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2498       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2499       // Compute the high part as N1.
2500       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2501             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2502       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503       // Compute the low part as N0.
2504       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505       return CombineTo(N, Lo, Hi);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2513   // (smulo x, 2) -> (saddo x, x)
2514   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2515     if (C2->getAPIntValue() == 2)
2516       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2517                          N->getOperand(0), N->getOperand(0));
2518
2519   return SDValue();
2520 }
2521
2522 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2523   // (umulo x, 2) -> (uaddo x, x)
2524   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2525     if (C2->getAPIntValue() == 2)
2526       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2527                          N->getOperand(0), N->getOperand(0));
2528
2529   return SDValue();
2530 }
2531
2532 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2533   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2534   if (Res.getNode()) return Res;
2535
2536   return SDValue();
2537 }
2538
2539 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2540   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2541   if (Res.getNode()) return Res;
2542
2543   return SDValue();
2544 }
2545
2546 /// If this is a binary operator with two operands of the same opcode, try to
2547 /// simplify it.
2548 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2549   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2550   EVT VT = N0.getValueType();
2551   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2552
2553   // Bail early if none of these transforms apply.
2554   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2555
2556   // For each of OP in AND/OR/XOR:
2557   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2558   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2559   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2560   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2561   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2562   //
2563   // do not sink logical op inside of a vector extend, since it may combine
2564   // into a vsetcc.
2565   EVT Op0VT = N0.getOperand(0).getValueType();
2566   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2567        N0.getOpcode() == ISD::SIGN_EXTEND ||
2568        N0.getOpcode() == ISD::BSWAP ||
2569        // Avoid infinite looping with PromoteIntBinOp.
2570        (N0.getOpcode() == ISD::ANY_EXTEND &&
2571         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2572        (N0.getOpcode() == ISD::TRUNCATE &&
2573         (!TLI.isZExtFree(VT, Op0VT) ||
2574          !TLI.isTruncateFree(Op0VT, VT)) &&
2575         TLI.isTypeLegal(Op0VT))) &&
2576       !VT.isVector() &&
2577       Op0VT == N1.getOperand(0).getValueType() &&
2578       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2579     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2580                                  N0.getOperand(0).getValueType(),
2581                                  N0.getOperand(0), N1.getOperand(0));
2582     AddToWorklist(ORNode.getNode());
2583     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2584   }
2585
2586   // For each of OP in SHL/SRL/SRA/AND...
2587   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2588   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2589   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2590   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2591        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2592       N0.getOperand(1) == N1.getOperand(1)) {
2593     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2594                                  N0.getOperand(0).getValueType(),
2595                                  N0.getOperand(0), N1.getOperand(0));
2596     AddToWorklist(ORNode.getNode());
2597     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2598                        ORNode, N0.getOperand(1));
2599   }
2600
2601   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2602   // Only perform this optimization after type legalization and before
2603   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2604   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2605   // we don't want to undo this promotion.
2606   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2607   // on scalars.
2608   if ((N0.getOpcode() == ISD::BITCAST ||
2609        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2610       Level == AfterLegalizeTypes) {
2611     SDValue In0 = N0.getOperand(0);
2612     SDValue In1 = N1.getOperand(0);
2613     EVT In0Ty = In0.getValueType();
2614     EVT In1Ty = In1.getValueType();
2615     SDLoc DL(N);
2616     // If both incoming values are integers, and the original types are the
2617     // same.
2618     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2619       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2620       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2621       AddToWorklist(Op.getNode());
2622       return BC;
2623     }
2624   }
2625
2626   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2627   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2628   // If both shuffles use the same mask, and both shuffle within a single
2629   // vector, then it is worthwhile to move the swizzle after the operation.
2630   // The type-legalizer generates this pattern when loading illegal
2631   // vector types from memory. In many cases this allows additional shuffle
2632   // optimizations.
2633   // There are other cases where moving the shuffle after the xor/and/or
2634   // is profitable even if shuffles don't perform a swizzle.
2635   // If both shuffles use the same mask, and both shuffles have the same first
2636   // or second operand, then it might still be profitable to move the shuffle
2637   // after the xor/and/or operation.
2638   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2639     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2640     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2641
2642     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2643            "Inputs to shuffles are not the same type");
2644
2645     // Check that both shuffles use the same mask. The masks are known to be of
2646     // the same length because the result vector type is the same.
2647     // Check also that shuffles have only one use to avoid introducing extra
2648     // instructions.
2649     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2650         SVN0->getMask().equals(SVN1->getMask())) {
2651       SDValue ShOp = N0->getOperand(1);
2652
2653       // Don't try to fold this node if it requires introducing a
2654       // build vector of all zeros that might be illegal at this stage.
2655       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2656         if (!LegalTypes)
2657           ShOp = DAG.getConstant(0, VT);
2658         else
2659           ShOp = SDValue();
2660       }
2661
2662       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2663       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2664       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2665       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2666         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2667                                       N0->getOperand(0), N1->getOperand(0));
2668         AddToWorklist(NewNode.getNode());
2669         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2670                                     &SVN0->getMask()[0]);
2671       }
2672
2673       // Don't try to fold this node if it requires introducing a
2674       // build vector of all zeros that might be illegal at this stage.
2675       ShOp = N0->getOperand(0);
2676       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2677         if (!LegalTypes)
2678           ShOp = DAG.getConstant(0, VT);
2679         else
2680           ShOp = SDValue();
2681       }
2682
2683       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2684       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2685       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2686       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2687         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2688                                       N0->getOperand(1), N1->getOperand(1));
2689         AddToWorklist(NewNode.getNode());
2690         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2691                                     &SVN0->getMask()[0]);
2692       }
2693     }
2694   }
2695
2696   return SDValue();
2697 }
2698
2699 /// This contains all DAGCombine rules which reduce two values combined by
2700 /// an And operation to a single value. This makes them reusable in the context
2701 /// of visitSELECT(). Rules involving constants are not included as
2702 /// visitSELECT() already handles those cases.
2703 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2704                                   SDNode *LocReference) {
2705   EVT VT = N1.getValueType();
2706
2707   // fold (and x, undef) -> 0
2708   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2709     return DAG.getConstant(0, VT);
2710   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2711   SDValue LL, LR, RL, RR, CC0, CC1;
2712   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2715
2716     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2717         LL.getValueType().isInteger()) {
2718       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2719       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2720         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2721                                      LR.getValueType(), LL, RL);
2722         AddToWorklist(ORNode.getNode());
2723         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2724       }
2725       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2726       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2727         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2728                                       LR.getValueType(), LL, RL);
2729         AddToWorklist(ANDNode.getNode());
2730         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2731       }
2732       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2733       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2734         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2735                                      LR.getValueType(), LL, RL);
2736         AddToWorklist(ORNode.getNode());
2737         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2738       }
2739     }
2740     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742         Op0 == Op1 && LL.getValueType().isInteger() &&
2743       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2747       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748                                     LL, DAG.getConstant(1, LL.getValueType()));
2749       AddToWorklist(ADDNode.getNode());
2750       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2751                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2752     }
2753     // canonicalize equivalent to ll == rl
2754     if (LL == RR && LR == RL) {
2755       Op1 = ISD::getSetCCSwappedOperands(Op1);
2756       std::swap(RL, RR);
2757     }
2758     if (LL == RL && LR == RR) {
2759       bool isInteger = LL.getValueType().isInteger();
2760       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2761       if (Result != ISD::SETCC_INVALID &&
2762           (!LegalOperations ||
2763            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764             TLI.isOperationLegal(ISD::SETCC,
2765                             getSetCCResultType(N0.getSimpleValueType())))))
2766         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2767                             LL, LR, Result);
2768     }
2769   }
2770
2771   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2772       VT.getSizeInBits() <= 64) {
2773     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2774       APInt ADDC = ADDI->getAPIntValue();
2775       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2776         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2777         // immediate for an add, but it is legal if its top c2 bits are set,
2778         // transform the ADD so the immediate doesn't need to be materialized
2779         // in a register.
2780         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2781           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2782                                              SRLI->getZExtValue());
2783           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2784             ADDC |= Mask;
2785             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2786               SDValue NewAdd =
2787                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2788                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2789               CombineTo(N0.getNode(), NewAdd);
2790               // Return N so it doesn't get rechecked!
2791               return SDValue(LocReference, 0);
2792             }
2793           }
2794         }
2795       }
2796     }
2797   }
2798
2799   return SDValue();
2800 }
2801
2802 SDValue DAGCombiner::visitAND(SDNode *N) {
2803   SDValue N0 = N->getOperand(0);
2804   SDValue N1 = N->getOperand(1);
2805   EVT VT = N1.getValueType();
2806
2807   // fold vector ops
2808   if (VT.isVector()) {
2809     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2810       return FoldedVOp;
2811
2812     // fold (and x, 0) -> 0, vector edition
2813     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2814       // do not return N0, because undef node may exist in N0
2815       return DAG.getConstant(
2816           APInt::getNullValue(
2817               N0.getValueType().getScalarType().getSizeInBits()),
2818           N0.getValueType());
2819     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2820       // do not return N1, because undef node may exist in N1
2821       return DAG.getConstant(
2822           APInt::getNullValue(
2823               N1.getValueType().getScalarType().getSizeInBits()),
2824           N1.getValueType());
2825
2826     // fold (and x, -1) -> x, vector edition
2827     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2828       return N1;
2829     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2830       return N0;
2831   }
2832
2833   // fold (and c1, c2) -> c1&c2
2834   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2835   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2836   if (N0C && N1C)
2837     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2838   // canonicalize constant to RHS
2839   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2840      !isConstantIntBuildVectorOrConstantInt(N1))
2841     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2842   // fold (and x, -1) -> x
2843   if (N1C && N1C->isAllOnesValue())
2844     return N0;
2845   // if (and x, c) is known to be zero, return 0
2846   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2847   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2848                                    APInt::getAllOnesValue(BitWidth)))
2849     return DAG.getConstant(0, VT);
2850   // reassociate and
2851   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2852     return RAND;
2853   // fold (and (or x, C), D) -> D if (C & D) == D
2854   if (N1C && N0.getOpcode() == ISD::OR)
2855     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2856       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2857         return N1;
2858   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2859   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2860     SDValue N0Op0 = N0.getOperand(0);
2861     APInt Mask = ~N1C->getAPIntValue();
2862     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2863     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2864       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2865                                  N0.getValueType(), N0Op0);
2866
2867       // Replace uses of the AND with uses of the Zero extend node.
2868       CombineTo(N, Zext);
2869
2870       // We actually want to replace all uses of the any_extend with the
2871       // zero_extend, to avoid duplicating things.  This will later cause this
2872       // AND to be folded.
2873       CombineTo(N0.getNode(), Zext);
2874       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2875     }
2876   }
2877   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2878   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2879   // already be zero by virtue of the width of the base type of the load.
2880   //
2881   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2882   // more cases.
2883   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2884        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2885       N0.getOpcode() == ISD::LOAD) {
2886     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2887                                          N0 : N0.getOperand(0) );
2888
2889     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2890     // This can be a pure constant or a vector splat, in which case we treat the
2891     // vector as a scalar and use the splat value.
2892     APInt Constant = APInt::getNullValue(1);
2893     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2894       Constant = C->getAPIntValue();
2895     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2896       APInt SplatValue, SplatUndef;
2897       unsigned SplatBitSize;
2898       bool HasAnyUndefs;
2899       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2900                                              SplatBitSize, HasAnyUndefs);
2901       if (IsSplat) {
2902         // Undef bits can contribute to a possible optimisation if set, so
2903         // set them.
2904         SplatValue |= SplatUndef;
2905
2906         // The splat value may be something like "0x00FFFFFF", which means 0 for
2907         // the first vector value and FF for the rest, repeating. We need a mask
2908         // that will apply equally to all members of the vector, so AND all the
2909         // lanes of the constant together.
2910         EVT VT = Vector->getValueType(0);
2911         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2912
2913         // If the splat value has been compressed to a bitlength lower
2914         // than the size of the vector lane, we need to re-expand it to
2915         // the lane size.
2916         if (BitWidth > SplatBitSize)
2917           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2918                SplatBitSize < BitWidth;
2919                SplatBitSize = SplatBitSize * 2)
2920             SplatValue |= SplatValue.shl(SplatBitSize);
2921
2922         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2923         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2924         if (SplatBitSize % BitWidth == 0) {
2925           Constant = APInt::getAllOnesValue(BitWidth);
2926           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2927             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2928         }
2929       }
2930     }
2931
2932     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2933     // actually legal and isn't going to get expanded, else this is a false
2934     // optimisation.
2935     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2936                                                     Load->getValueType(0),
2937                                                     Load->getMemoryVT());
2938
2939     // Resize the constant to the same size as the original memory access before
2940     // extension. If it is still the AllOnesValue then this AND is completely
2941     // unneeded.
2942     Constant =
2943       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2944
2945     bool B;
2946     switch (Load->getExtensionType()) {
2947     default: B = false; break;
2948     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2949     case ISD::ZEXTLOAD:
2950     case ISD::NON_EXTLOAD: B = true; break;
2951     }
2952
2953     if (B && Constant.isAllOnesValue()) {
2954       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2955       // preserve semantics once we get rid of the AND.
2956       SDValue NewLoad(Load, 0);
2957       if (Load->getExtensionType() == ISD::EXTLOAD) {
2958         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2959                               Load->getValueType(0), SDLoc(Load),
2960                               Load->getChain(), Load->getBasePtr(),
2961                               Load->getOffset(), Load->getMemoryVT(),
2962                               Load->getMemOperand());
2963         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2964         if (Load->getNumValues() == 3) {
2965           // PRE/POST_INC loads have 3 values.
2966           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2967                            NewLoad.getValue(2) };
2968           CombineTo(Load, To, 3, true);
2969         } else {
2970           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2971         }
2972       }
2973
2974       // Fold the AND away, taking care not to fold to the old load node if we
2975       // replaced it.
2976       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2977
2978       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2979     }
2980   }
2981
2982   // fold (and (load x), 255) -> (zextload x, i8)
2983   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2984   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2985   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2986               (N0.getOpcode() == ISD::ANY_EXTEND &&
2987                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2988     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2989     LoadSDNode *LN0 = HasAnyExt
2990       ? cast<LoadSDNode>(N0.getOperand(0))
2991       : cast<LoadSDNode>(N0);
2992     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2993         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2994       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2995       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2996         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2997         EVT LoadedVT = LN0->getMemoryVT();
2998         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2999
3000         if (ExtVT == LoadedVT &&
3001             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3002                                                     ExtVT))) {
3003
3004           SDValue NewLoad =
3005             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3006                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3007                            LN0->getMemOperand());
3008           AddToWorklist(N);
3009           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3010           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3011         }
3012
3013         // Do not change the width of a volatile load.
3014         // Do not generate loads of non-round integer types since these can
3015         // be expensive (and would be wrong if the type is not byte sized).
3016         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3017             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3018                                                     ExtVT))) {
3019           EVT PtrType = LN0->getOperand(1).getValueType();
3020
3021           unsigned Alignment = LN0->getAlignment();
3022           SDValue NewPtr = LN0->getBasePtr();
3023
3024           // For big endian targets, we need to add an offset to the pointer
3025           // to load the correct bytes.  For little endian systems, we merely
3026           // need to read fewer bytes from the same pointer.
3027           if (TLI.isBigEndian()) {
3028             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3029             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3030             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3031             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3032                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3033             Alignment = MinAlign(Alignment, PtrOff);
3034           }
3035
3036           AddToWorklist(NewPtr.getNode());
3037
3038           SDValue Load =
3039             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3040                            LN0->getChain(), NewPtr,
3041                            LN0->getPointerInfo(),
3042                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3043                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3044           AddToWorklist(N);
3045           CombineTo(LN0, Load, Load.getValue(1));
3046           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3047         }
3048       }
3049     }
3050   }
3051
3052   if (SDValue Combined = visitANDLike(N0, N1, N))
3053     return Combined;
3054
3055   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3056   if (N0.getOpcode() == N1.getOpcode()) {
3057     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3058     if (Tmp.getNode()) return Tmp;
3059   }
3060
3061   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3062   // fold (and (sra)) -> (and (srl)) when possible.
3063   if (!VT.isVector() &&
3064       SimplifyDemandedBits(SDValue(N, 0)))
3065     return SDValue(N, 0);
3066
3067   // fold (zext_inreg (extload x)) -> (zextload x)
3068   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3069     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3070     EVT MemVT = LN0->getMemoryVT();
3071     // If we zero all the possible extended bits, then we can turn this into
3072     // a zextload if we are running before legalize or the operation is legal.
3073     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3074     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3075                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3076         ((!LegalOperations && !LN0->isVolatile()) ||
3077          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3078       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3079                                        LN0->getChain(), LN0->getBasePtr(),
3080                                        MemVT, LN0->getMemOperand());
3081       AddToWorklist(N);
3082       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3083       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3084     }
3085   }
3086   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3087   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3088       N0.hasOneUse()) {
3089     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3090     EVT MemVT = LN0->getMemoryVT();
3091     // If we zero all the possible extended bits, then we can turn this into
3092     // a zextload if we are running before legalize or the operation is legal.
3093     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3094     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3095                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3096         ((!LegalOperations && !LN0->isVolatile()) ||
3097          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3098       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3099                                        LN0->getChain(), LN0->getBasePtr(),
3100                                        MemVT, LN0->getMemOperand());
3101       AddToWorklist(N);
3102       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3103       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3104     }
3105   }
3106   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3107   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3108     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3109                                        N0.getOperand(1), false);
3110     if (BSwap.getNode())
3111       return BSwap;
3112   }
3113
3114   return SDValue();
3115 }
3116
3117 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3118 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3119                                         bool DemandHighBits) {
3120   if (!LegalOperations)
3121     return SDValue();
3122
3123   EVT VT = N->getValueType(0);
3124   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3125     return SDValue();
3126   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3127     return SDValue();
3128
3129   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3130   bool LookPassAnd0 = false;
3131   bool LookPassAnd1 = false;
3132   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3133       std::swap(N0, N1);
3134   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3135       std::swap(N0, N1);
3136   if (N0.getOpcode() == ISD::AND) {
3137     if (!N0.getNode()->hasOneUse())
3138       return SDValue();
3139     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3140     if (!N01C || N01C->getZExtValue() != 0xFF00)
3141       return SDValue();
3142     N0 = N0.getOperand(0);
3143     LookPassAnd0 = true;
3144   }
3145
3146   if (N1.getOpcode() == ISD::AND) {
3147     if (!N1.getNode()->hasOneUse())
3148       return SDValue();
3149     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3150     if (!N11C || N11C->getZExtValue() != 0xFF)
3151       return SDValue();
3152     N1 = N1.getOperand(0);
3153     LookPassAnd1 = true;
3154   }
3155
3156   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3157     std::swap(N0, N1);
3158   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3159     return SDValue();
3160   if (!N0.getNode()->hasOneUse() ||
3161       !N1.getNode()->hasOneUse())
3162     return SDValue();
3163
3164   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3165   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3166   if (!N01C || !N11C)
3167     return SDValue();
3168   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3169     return SDValue();
3170
3171   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3172   SDValue N00 = N0->getOperand(0);
3173   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3174     if (!N00.getNode()->hasOneUse())
3175       return SDValue();
3176     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3177     if (!N001C || N001C->getZExtValue() != 0xFF)
3178       return SDValue();
3179     N00 = N00.getOperand(0);
3180     LookPassAnd0 = true;
3181   }
3182
3183   SDValue N10 = N1->getOperand(0);
3184   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3185     if (!N10.getNode()->hasOneUse())
3186       return SDValue();
3187     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3188     if (!N101C || N101C->getZExtValue() != 0xFF00)
3189       return SDValue();
3190     N10 = N10.getOperand(0);
3191     LookPassAnd1 = true;
3192   }
3193
3194   if (N00 != N10)
3195     return SDValue();
3196
3197   // Make sure everything beyond the low halfword gets set to zero since the SRL
3198   // 16 will clear the top bits.
3199   unsigned OpSizeInBits = VT.getSizeInBits();
3200   if (DemandHighBits && OpSizeInBits > 16) {
3201     // If the left-shift isn't masked out then the only way this is a bswap is
3202     // if all bits beyond the low 8 are 0. In that case the entire pattern
3203     // reduces to a left shift anyway: leave it for other parts of the combiner.
3204     if (!LookPassAnd0)
3205       return SDValue();
3206
3207     // However, if the right shift isn't masked out then it might be because
3208     // it's not needed. See if we can spot that too.
3209     if (!LookPassAnd1 &&
3210         !DAG.MaskedValueIsZero(
3211             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3212       return SDValue();
3213   }
3214
3215   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3216   if (OpSizeInBits > 16)
3217     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3218                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3219   return Res;
3220 }
3221
3222 /// Return true if the specified node is an element that makes up a 32-bit
3223 /// packed halfword byteswap.
3224 /// ((x & 0x000000ff) << 8) |
3225 /// ((x & 0x0000ff00) >> 8) |
3226 /// ((x & 0x00ff0000) << 8) |
3227 /// ((x & 0xff000000) >> 8)
3228 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3229   if (!N.getNode()->hasOneUse())
3230     return false;
3231
3232   unsigned Opc = N.getOpcode();
3233   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3234     return false;
3235
3236   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3237   if (!N1C)
3238     return false;
3239
3240   unsigned Num;
3241   switch (N1C->getZExtValue()) {
3242   default:
3243     return false;
3244   case 0xFF:       Num = 0; break;
3245   case 0xFF00:     Num = 1; break;
3246   case 0xFF0000:   Num = 2; break;
3247   case 0xFF000000: Num = 3; break;
3248   }
3249
3250   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3251   SDValue N0 = N.getOperand(0);
3252   if (Opc == ISD::AND) {
3253     if (Num == 0 || Num == 2) {
3254       // (x >> 8) & 0xff
3255       // (x >> 8) & 0xff0000
3256       if (N0.getOpcode() != ISD::SRL)
3257         return false;
3258       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259       if (!C || C->getZExtValue() != 8)
3260         return false;
3261     } else {
3262       // (x << 8) & 0xff00
3263       // (x << 8) & 0xff000000
3264       if (N0.getOpcode() != ISD::SHL)
3265         return false;
3266       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3267       if (!C || C->getZExtValue() != 8)
3268         return false;
3269     }
3270   } else if (Opc == ISD::SHL) {
3271     // (x & 0xff) << 8
3272     // (x & 0xff0000) << 8
3273     if (Num != 0 && Num != 2)
3274       return false;
3275     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276     if (!C || C->getZExtValue() != 8)
3277       return false;
3278   } else { // Opc == ISD::SRL
3279     // (x & 0xff00) >> 8
3280     // (x & 0xff000000) >> 8
3281     if (Num != 1 && Num != 3)
3282       return false;
3283     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3284     if (!C || C->getZExtValue() != 8)
3285       return false;
3286   }
3287
3288   if (Parts[Num])
3289     return false;
3290
3291   Parts[Num] = N0.getOperand(0).getNode();
3292   return true;
3293 }
3294
3295 /// Match a 32-bit packed halfword bswap. That is
3296 /// ((x & 0x000000ff) << 8) |
3297 /// ((x & 0x0000ff00) >> 8) |
3298 /// ((x & 0x00ff0000) << 8) |
3299 /// ((x & 0xff000000) >> 8)
3300 /// => (rotl (bswap x), 16)
3301 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3302   if (!LegalOperations)
3303     return SDValue();
3304
3305   EVT VT = N->getValueType(0);
3306   if (VT != MVT::i32)
3307     return SDValue();
3308   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3309     return SDValue();
3310
3311   // Look for either
3312   // (or (or (and), (and)), (or (and), (and)))
3313   // (or (or (or (and), (and)), (and)), (and))
3314   if (N0.getOpcode() != ISD::OR)
3315     return SDValue();
3316   SDValue N00 = N0.getOperand(0);
3317   SDValue N01 = N0.getOperand(1);
3318   SDNode *Parts[4] = {};
3319
3320   if (N1.getOpcode() == ISD::OR &&
3321       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3322     // (or (or (and), (and)), (or (and), (and)))
3323     SDValue N000 = N00.getOperand(0);
3324     if (!isBSwapHWordElement(N000, Parts))
3325       return SDValue();
3326
3327     SDValue N001 = N00.getOperand(1);
3328     if (!isBSwapHWordElement(N001, Parts))
3329       return SDValue();
3330     SDValue N010 = N01.getOperand(0);
3331     if (!isBSwapHWordElement(N010, Parts))
3332       return SDValue();
3333     SDValue N011 = N01.getOperand(1);
3334     if (!isBSwapHWordElement(N011, Parts))
3335       return SDValue();
3336   } else {
3337     // (or (or (or (and), (and)), (and)), (and))
3338     if (!isBSwapHWordElement(N1, Parts))
3339       return SDValue();
3340     if (!isBSwapHWordElement(N01, Parts))
3341       return SDValue();
3342     if (N00.getOpcode() != ISD::OR)
3343       return SDValue();
3344     SDValue N000 = N00.getOperand(0);
3345     if (!isBSwapHWordElement(N000, Parts))
3346       return SDValue();
3347     SDValue N001 = N00.getOperand(1);
3348     if (!isBSwapHWordElement(N001, Parts))
3349       return SDValue();
3350   }
3351
3352   // Make sure the parts are all coming from the same node.
3353   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3354     return SDValue();
3355
3356   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3357                               SDValue(Parts[0],0));
3358
3359   // Result of the bswap should be rotated by 16. If it's not legal, then
3360   // do  (x << 16) | (x >> 16).
3361   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3362   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3363     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3364   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3365     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3366   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3367                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3368                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3369 }
3370
3371 /// This contains all DAGCombine rules which reduce two values combined by
3372 /// an Or operation to a single value \see visitANDLike().
3373 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3374   EVT VT = N1.getValueType();
3375   // fold (or x, undef) -> -1
3376   if (!LegalOperations &&
3377       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3378     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3379     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3380   }
3381   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3382   SDValue LL, LR, RL, RR, CC0, CC1;
3383   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3384     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3385     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3386
3387     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3388         LL.getValueType().isInteger()) {
3389       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3390       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3391       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3392           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3393         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3394                                      LR.getValueType(), LL, RL);
3395         AddToWorklist(ORNode.getNode());
3396         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3397       }
3398       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3399       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3400       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3401           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3402         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3403                                       LR.getValueType(), LL, RL);
3404         AddToWorklist(ANDNode.getNode());
3405         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3406       }
3407     }
3408     // canonicalize equivalent to ll == rl
3409     if (LL == RR && LR == RL) {
3410       Op1 = ISD::getSetCCSwappedOperands(Op1);
3411       std::swap(RL, RR);
3412     }
3413     if (LL == RL && LR == RR) {
3414       bool isInteger = LL.getValueType().isInteger();
3415       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3416       if (Result != ISD::SETCC_INVALID &&
3417           (!LegalOperations ||
3418            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3419             TLI.isOperationLegal(ISD::SETCC,
3420               getSetCCResultType(N0.getValueType())))))
3421         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3422                             LL, LR, Result);
3423     }
3424   }
3425
3426   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3427   if (N0.getOpcode() == ISD::AND &&
3428       N1.getOpcode() == ISD::AND &&
3429       N0.getOperand(1).getOpcode() == ISD::Constant &&
3430       N1.getOperand(1).getOpcode() == ISD::Constant &&
3431       // Don't increase # computations.
3432       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3433     // We can only do this xform if we know that bits from X that are set in C2
3434     // but not in C1 are already zero.  Likewise for Y.
3435     const APInt &LHSMask =
3436       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3437     const APInt &RHSMask =
3438       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3439
3440     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3441         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3442       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3443                               N0.getOperand(0), N1.getOperand(0));
3444       return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3445                          DAG.getConstant(LHSMask | RHSMask, VT));
3446     }
3447   }
3448
3449   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3450   if (N0.getOpcode() == ISD::AND &&
3451       N1.getOpcode() == ISD::AND &&
3452       N0.getOperand(0) == N1.getOperand(0) &&
3453       // Don't increase # computations.
3454       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3455     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3456                             N0.getOperand(1), N1.getOperand(1));
3457     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3458   }
3459
3460   return SDValue();
3461 }
3462
3463 SDValue DAGCombiner::visitOR(SDNode *N) {
3464   SDValue N0 = N->getOperand(0);
3465   SDValue N1 = N->getOperand(1);
3466   EVT VT = N1.getValueType();
3467
3468   // fold vector ops
3469   if (VT.isVector()) {
3470     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3471       return FoldedVOp;
3472
3473     // fold (or x, 0) -> x, vector edition
3474     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3475       return N1;
3476     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3477       return N0;
3478
3479     // fold (or x, -1) -> -1, vector edition
3480     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3481       // do not return N0, because undef node may exist in N0
3482       return DAG.getConstant(
3483           APInt::getAllOnesValue(
3484               N0.getValueType().getScalarType().getSizeInBits()),
3485           N0.getValueType());
3486     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3487       // do not return N1, because undef node may exist in N1
3488       return DAG.getConstant(
3489           APInt::getAllOnesValue(
3490               N1.getValueType().getScalarType().getSizeInBits()),
3491           N1.getValueType());
3492
3493     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3494     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3495     // Do this only if the resulting shuffle is legal.
3496     if (isa<ShuffleVectorSDNode>(N0) &&
3497         isa<ShuffleVectorSDNode>(N1) &&
3498         // Avoid folding a node with illegal type.
3499         TLI.isTypeLegal(VT) &&
3500         N0->getOperand(1) == N1->getOperand(1) &&
3501         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3502       bool CanFold = true;
3503       unsigned NumElts = VT.getVectorNumElements();
3504       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3505       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3506       // We construct two shuffle masks:
3507       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3508       // and N1 as the second operand.
3509       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3510       // and N0 as the second operand.
3511       // We do this because OR is commutable and therefore there might be
3512       // two ways to fold this node into a shuffle.
3513       SmallVector<int,4> Mask1;
3514       SmallVector<int,4> Mask2;
3515
3516       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3517         int M0 = SV0->getMaskElt(i);
3518         int M1 = SV1->getMaskElt(i);
3519
3520         // Both shuffle indexes are undef. Propagate Undef.
3521         if (M0 < 0 && M1 < 0) {
3522           Mask1.push_back(M0);
3523           Mask2.push_back(M0);
3524           continue;
3525         }
3526
3527         if (M0 < 0 || M1 < 0 ||
3528             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3529             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3530           CanFold = false;
3531           break;
3532         }
3533
3534         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3535         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3536       }
3537
3538       if (CanFold) {
3539         // Fold this sequence only if the resulting shuffle is 'legal'.
3540         if (TLI.isShuffleMaskLegal(Mask1, VT))
3541           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3542                                       N1->getOperand(0), &Mask1[0]);
3543         if (TLI.isShuffleMaskLegal(Mask2, VT))
3544           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3545                                       N0->getOperand(0), &Mask2[0]);
3546       }
3547     }
3548   }
3549
3550   // fold (or c1, c2) -> c1|c2
3551   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3552   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3553   if (N0C && N1C)
3554     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3555   // canonicalize constant to RHS
3556   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3557      !isConstantIntBuildVectorOrConstantInt(N1))
3558     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3559   // fold (or x, 0) -> x
3560   if (N1C && N1C->isNullValue())
3561     return N0;
3562   // fold (or x, -1) -> -1
3563   if (N1C && N1C->isAllOnesValue())
3564     return N1;
3565   // fold (or x, c) -> c iff (x & ~c) == 0
3566   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3567     return N1;
3568
3569   if (SDValue Combined = visitORLike(N0, N1, N))
3570     return Combined;
3571
3572   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3573   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3574   if (BSwap.getNode())
3575     return BSwap;
3576   BSwap = MatchBSwapHWordLow(N, N0, N1);
3577   if (BSwap.getNode())
3578     return BSwap;
3579
3580   // reassociate or
3581   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3582     return ROR;
3583   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3584   // iff (c1 & c2) == 0.
3585   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3586              isa<ConstantSDNode>(N0.getOperand(1))) {
3587     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3588     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3589       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3590         return DAG.getNode(
3591             ISD::AND, SDLoc(N), VT,
3592             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3593       return SDValue();
3594     }
3595   }
3596   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3597   if (N0.getOpcode() == N1.getOpcode()) {
3598     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3599     if (Tmp.getNode()) return Tmp;
3600   }
3601
3602   // See if this is some rotate idiom.
3603   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3604     return SDValue(Rot, 0);
3605
3606   // Simplify the operands using demanded-bits information.
3607   if (!VT.isVector() &&
3608       SimplifyDemandedBits(SDValue(N, 0)))
3609     return SDValue(N, 0);
3610
3611   return SDValue();
3612 }
3613
3614 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3615 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3616   if (Op.getOpcode() == ISD::AND) {
3617     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3618       Mask = Op.getOperand(1);
3619       Op = Op.getOperand(0);
3620     } else {
3621       return false;
3622     }
3623   }
3624
3625   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3626     Shift = Op;
3627     return true;
3628   }
3629
3630   return false;
3631 }
3632
3633 // Return true if we can prove that, whenever Neg and Pos are both in the
3634 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3635 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3636 //
3637 //     (or (shift1 X, Neg), (shift2 X, Pos))
3638 //
3639 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3640 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3641 // to consider shift amounts with defined behavior.
3642 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3643   // If OpSize is a power of 2 then:
3644   //
3645   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3646   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3647   //
3648   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3649   // for the stronger condition:
3650   //
3651   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3652   //
3653   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3654   // we can just replace Neg with Neg' for the rest of the function.
3655   //
3656   // In other cases we check for the even stronger condition:
3657   //
3658   //     Neg == OpSize - Pos                                    [B]
3659   //
3660   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3661   // behavior if Pos == 0 (and consequently Neg == OpSize).
3662   //
3663   // We could actually use [A] whenever OpSize is a power of 2, but the
3664   // only extra cases that it would match are those uninteresting ones
3665   // where Neg and Pos are never in range at the same time.  E.g. for
3666   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3667   // as well as (sub 32, Pos), but:
3668   //
3669   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3670   //
3671   // always invokes undefined behavior for 32-bit X.
3672   //
3673   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3674   unsigned MaskLoBits = 0;
3675   if (Neg.getOpcode() == ISD::AND &&
3676       isPowerOf2_64(OpSize) &&
3677       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3678       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3679     Neg = Neg.getOperand(0);
3680     MaskLoBits = Log2_64(OpSize);
3681   }
3682
3683   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3684   if (Neg.getOpcode() != ISD::SUB)
3685     return 0;
3686   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3687   if (!NegC)
3688     return 0;
3689   SDValue NegOp1 = Neg.getOperand(1);
3690
3691   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3692   // Pos'.  The truncation is redundant for the purpose of the equality.
3693   if (MaskLoBits &&
3694       Pos.getOpcode() == ISD::AND &&
3695       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3696       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3697     Pos = Pos.getOperand(0);
3698
3699   // The condition we need is now:
3700   //
3701   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3702   //
3703   // If NegOp1 == Pos then we need:
3704   //
3705   //              OpSize & Mask == NegC & Mask
3706   //
3707   // (because "x & Mask" is a truncation and distributes through subtraction).
3708   APInt Width;
3709   if (Pos == NegOp1)
3710     Width = NegC->getAPIntValue();
3711   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3712   // Then the condition we want to prove becomes:
3713   //
3714   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3715   //
3716   // which, again because "x & Mask" is a truncation, becomes:
3717   //
3718   //                NegC & Mask == (OpSize - PosC) & Mask
3719   //              OpSize & Mask == (NegC + PosC) & Mask
3720   else if (Pos.getOpcode() == ISD::ADD &&
3721            Pos.getOperand(0) == NegOp1 &&
3722            Pos.getOperand(1).getOpcode() == ISD::Constant)
3723     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3724              NegC->getAPIntValue());
3725   else
3726     return false;
3727
3728   // Now we just need to check that OpSize & Mask == Width & Mask.
3729   if (MaskLoBits)
3730     // Opsize & Mask is 0 since Mask is Opsize - 1.
3731     return Width.getLoBits(MaskLoBits) == 0;
3732   return Width == OpSize;
3733 }
3734
3735 // A subroutine of MatchRotate used once we have found an OR of two opposite
3736 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3737 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3738 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3739 // Neg with outer conversions stripped away.
3740 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3741                                        SDValue Neg, SDValue InnerPos,
3742                                        SDValue InnerNeg, unsigned PosOpcode,
3743                                        unsigned NegOpcode, SDLoc DL) {
3744   // fold (or (shl x, (*ext y)),
3745   //          (srl x, (*ext (sub 32, y)))) ->
3746   //   (rotl x, y) or (rotr x, (sub 32, y))
3747   //
3748   // fold (or (shl x, (*ext (sub 32, y))),
3749   //          (srl x, (*ext y))) ->
3750   //   (rotr x, y) or (rotl x, (sub 32, y))
3751   EVT VT = Shifted.getValueType();
3752   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3753     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3754     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3755                        HasPos ? Pos : Neg).getNode();
3756   }
3757
3758   return nullptr;
3759 }
3760
3761 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3762 // idioms for rotate, and if the target supports rotation instructions, generate
3763 // a rot[lr].
3764 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3765   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3766   EVT VT = LHS.getValueType();
3767   if (!TLI.isTypeLegal(VT)) return nullptr;
3768
3769   // The target must have at least one rotate flavor.
3770   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3771   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3772   if (!HasROTL && !HasROTR) return nullptr;
3773
3774   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3775   SDValue LHSShift;   // The shift.
3776   SDValue LHSMask;    // AND value if any.
3777   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3778     return nullptr; // Not part of a rotate.
3779
3780   SDValue RHSShift;   // The shift.
3781   SDValue RHSMask;    // AND value if any.
3782   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3783     return nullptr; // Not part of a rotate.
3784
3785   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3786     return nullptr;   // Not shifting the same value.
3787
3788   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3789     return nullptr;   // Shifts must disagree.
3790
3791   // Canonicalize shl to left side in a shl/srl pair.
3792   if (RHSShift.getOpcode() == ISD::SHL) {
3793     std::swap(LHS, RHS);
3794     std::swap(LHSShift, RHSShift);
3795     std::swap(LHSMask , RHSMask );
3796   }
3797
3798   unsigned OpSizeInBits = VT.getSizeInBits();
3799   SDValue LHSShiftArg = LHSShift.getOperand(0);
3800   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3801   SDValue RHSShiftArg = RHSShift.getOperand(0);
3802   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3803
3804   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3805   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3806   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3807       RHSShiftAmt.getOpcode() == ISD::Constant) {
3808     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3809     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3810     if ((LShVal + RShVal) != OpSizeInBits)
3811       return nullptr;
3812
3813     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3814                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3815
3816     // If there is an AND of either shifted operand, apply it to the result.
3817     if (LHSMask.getNode() || RHSMask.getNode()) {
3818       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3819
3820       if (LHSMask.getNode()) {
3821         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3822         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3823       }
3824       if (RHSMask.getNode()) {
3825         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3826         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3827       }
3828
3829       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3830     }
3831
3832     return Rot.getNode();
3833   }
3834
3835   // If there is a mask here, and we have a variable shift, we can't be sure
3836   // that we're masking out the right stuff.
3837   if (LHSMask.getNode() || RHSMask.getNode())
3838     return nullptr;
3839
3840   // If the shift amount is sign/zext/any-extended just peel it off.
3841   SDValue LExtOp0 = LHSShiftAmt;
3842   SDValue RExtOp0 = RHSShiftAmt;
3843   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3844        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3845        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3846        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3847       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3848        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3849        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3850        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3851     LExtOp0 = LHSShiftAmt.getOperand(0);
3852     RExtOp0 = RHSShiftAmt.getOperand(0);
3853   }
3854
3855   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3856                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3857   if (TryL)
3858     return TryL;
3859
3860   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3861                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3862   if (TryR)
3863     return TryR;
3864
3865   return nullptr;
3866 }
3867
3868 SDValue DAGCombiner::visitXOR(SDNode *N) {
3869   SDValue N0 = N->getOperand(0);
3870   SDValue N1 = N->getOperand(1);
3871   EVT VT = N0.getValueType();
3872
3873   // fold vector ops
3874   if (VT.isVector()) {
3875     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3876       return FoldedVOp;
3877
3878     // fold (xor x, 0) -> x, vector edition
3879     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3880       return N1;
3881     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3882       return N0;
3883   }
3884
3885   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3886   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3887     return DAG.getConstant(0, VT);
3888   // fold (xor x, undef) -> undef
3889   if (N0.getOpcode() == ISD::UNDEF)
3890     return N0;
3891   if (N1.getOpcode() == ISD::UNDEF)
3892     return N1;
3893   // fold (xor c1, c2) -> c1^c2
3894   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3895   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3896   if (N0C && N1C)
3897     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3898   // canonicalize constant to RHS
3899   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3900      !isConstantIntBuildVectorOrConstantInt(N1))
3901     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3902   // fold (xor x, 0) -> x
3903   if (N1C && N1C->isNullValue())
3904     return N0;
3905   // reassociate xor
3906   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3907     return RXOR;
3908
3909   // fold !(x cc y) -> (x !cc y)
3910   SDValue LHS, RHS, CC;
3911   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3912     bool isInt = LHS.getValueType().isInteger();
3913     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3914                                                isInt);
3915
3916     if (!LegalOperations ||
3917         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3918       switch (N0.getOpcode()) {
3919       default:
3920         llvm_unreachable("Unhandled SetCC Equivalent!");
3921       case ISD::SETCC:
3922         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3923       case ISD::SELECT_CC:
3924         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3925                                N0.getOperand(3), NotCC);
3926       }
3927     }
3928   }
3929
3930   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3931   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3932       N0.getNode()->hasOneUse() &&
3933       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3934     SDValue V = N0.getOperand(0);
3935     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3936                     DAG.getConstant(1, V.getValueType()));
3937     AddToWorklist(V.getNode());
3938     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3939   }
3940
3941   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3942   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3943       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3944     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3945     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3946       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3947       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3948       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3949       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3950       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3951     }
3952   }
3953   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3954   if (N1C && N1C->isAllOnesValue() &&
3955       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3956     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3957     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3958       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3959       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3960       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3961       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3962       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3963     }
3964   }
3965   // fold (xor (and x, y), y) -> (and (not x), y)
3966   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3967       N0->getOperand(1) == N1) {
3968     SDValue X = N0->getOperand(0);
3969     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3970     AddToWorklist(NotX.getNode());
3971     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3972   }
3973   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3974   if (N1C && N0.getOpcode() == ISD::XOR) {
3975     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3976     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3977     if (N00C)
3978       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3979                          DAG.getConstant(N1C->getAPIntValue() ^
3980                                          N00C->getAPIntValue(), VT));
3981     if (N01C)
3982       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3983                          DAG.getConstant(N1C->getAPIntValue() ^
3984                                          N01C->getAPIntValue(), VT));
3985   }
3986   // fold (xor x, x) -> 0
3987   if (N0 == N1)
3988     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3989
3990   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3991   // Here is a concrete example of this equivalence:
3992   // i16   x ==  14
3993   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
3994   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3995   //
3996   // =>
3997   //
3998   // i16     ~1      == 0b1111111111111110
3999   // i16 rol(~1, 14) == 0b1011111111111111
4000   //
4001   // Some additional tips to help conceptualize this transform:
4002   // - Try to see the operation as placing a single zero in a value of all ones.
4003   // - There exists no value for x which would allow the result to contain zero.
4004   // - Values of x larger than the bitwidth are undefined and do not require a
4005   //   consistent result.
4006   // - Pushing the zero left requires shifting one bits in from the right.
4007   // A rotate left of ~1 is a nice way of achieving the desired result.
4008   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4009     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4010       if (N0.getOpcode() == ISD::SHL)
4011         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4012           if (N1C->isAllOnesValue() && ShlLHS->isOne())
4013             return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4014                                N0.getOperand(1));
4015
4016   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4017   if (N0.getOpcode() == N1.getOpcode()) {
4018     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4019     if (Tmp.getNode()) return Tmp;
4020   }
4021
4022   // Simplify the expression using non-local knowledge.
4023   if (!VT.isVector() &&
4024       SimplifyDemandedBits(SDValue(N, 0)))
4025     return SDValue(N, 0);
4026
4027   return SDValue();
4028 }
4029
4030 /// Handle transforms common to the three shifts, when the shift amount is a
4031 /// constant.
4032 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4033   // We can't and shouldn't fold opaque constants.
4034   if (Amt->isOpaque())
4035     return SDValue();
4036
4037   SDNode *LHS = N->getOperand(0).getNode();
4038   if (!LHS->hasOneUse()) return SDValue();
4039
4040   // We want to pull some binops through shifts, so that we have (and (shift))
4041   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4042   // thing happens with address calculations, so it's important to canonicalize
4043   // it.
4044   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4045
4046   switch (LHS->getOpcode()) {
4047   default: return SDValue();
4048   case ISD::OR:
4049   case ISD::XOR:
4050     HighBitSet = false; // We can only transform sra if the high bit is clear.
4051     break;
4052   case ISD::AND:
4053     HighBitSet = true;  // We can only transform sra if the high bit is set.
4054     break;
4055   case ISD::ADD:
4056     if (N->getOpcode() != ISD::SHL)
4057       return SDValue(); // only shl(add) not sr[al](add).
4058     HighBitSet = false; // We can only transform sra if the high bit is clear.
4059     break;
4060   }
4061
4062   // We require the RHS of the binop to be a constant and not opaque as well.
4063   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4064   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4065
4066   // FIXME: disable this unless the input to the binop is a shift by a constant.
4067   // If it is not a shift, it pessimizes some common cases like:
4068   //
4069   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4070   //    int bar(int *X, int i) { return X[i & 255]; }
4071   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4072   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4073        BinOpLHSVal->getOpcode() != ISD::SRA &&
4074        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4075       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4076     return SDValue();
4077
4078   EVT VT = N->getValueType(0);
4079
4080   // If this is a signed shift right, and the high bit is modified by the
4081   // logical operation, do not perform the transformation. The highBitSet
4082   // boolean indicates the value of the high bit of the constant which would
4083   // cause it to be modified for this operation.
4084   if (N->getOpcode() == ISD::SRA) {
4085     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4086     if (BinOpRHSSignSet != HighBitSet)
4087       return SDValue();
4088   }
4089
4090   if (!TLI.isDesirableToCommuteWithShift(LHS))
4091     return SDValue();
4092
4093   // Fold the constants, shifting the binop RHS by the shift amount.
4094   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4095                                N->getValueType(0),
4096                                LHS->getOperand(1), N->getOperand(1));
4097   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4098
4099   // Create the new shift.
4100   SDValue NewShift = DAG.getNode(N->getOpcode(),
4101                                  SDLoc(LHS->getOperand(0)),
4102                                  VT, LHS->getOperand(0), N->getOperand(1));
4103
4104   // Create the new binop.
4105   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4106 }
4107
4108 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4109   assert(N->getOpcode() == ISD::TRUNCATE);
4110   assert(N->getOperand(0).getOpcode() == ISD::AND);
4111
4112   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4113   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4114     SDValue N01 = N->getOperand(0).getOperand(1);
4115
4116     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4117       EVT TruncVT = N->getValueType(0);
4118       SDValue N00 = N->getOperand(0).getOperand(0);
4119       APInt TruncC = N01C->getAPIntValue();
4120       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4121
4122       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4123                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4124                          DAG.getConstant(TruncC, TruncVT));
4125     }
4126   }
4127
4128   return SDValue();
4129 }
4130
4131 SDValue DAGCombiner::visitRotate(SDNode *N) {
4132   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4133   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4134       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4135     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4136     if (NewOp1.getNode())
4137       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4138                          N->getOperand(0), NewOp1);
4139   }
4140   return SDValue();
4141 }
4142
4143 SDValue DAGCombiner::visitSHL(SDNode *N) {
4144   SDValue N0 = N->getOperand(0);
4145   SDValue N1 = N->getOperand(1);
4146   EVT VT = N0.getValueType();
4147   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4148
4149   // fold vector ops
4150   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4151   if (VT.isVector()) {
4152     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4153       return FoldedVOp;
4154
4155     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4156     // If setcc produces all-one true value then:
4157     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4158     if (N1CV && N1CV->isConstant()) {
4159       if (N0.getOpcode() == ISD::AND) {
4160         SDValue N00 = N0->getOperand(0);
4161         SDValue N01 = N0->getOperand(1);
4162         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4163
4164         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4165             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4166                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4167           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4168             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4169         }
4170       } else {
4171         N1C = isConstOrConstSplat(N1);
4172       }
4173     }
4174   }
4175
4176   // fold (shl c1, c2) -> c1<<c2
4177   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4178   if (N0C && N1C)
4179     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4180   // fold (shl 0, x) -> 0
4181   if (N0C && N0C->isNullValue())
4182     return N0;
4183   // fold (shl x, c >= size(x)) -> undef
4184   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4185     return DAG.getUNDEF(VT);
4186   // fold (shl x, 0) -> x
4187   if (N1C && N1C->isNullValue())
4188     return N0;
4189   // fold (shl undef, x) -> 0
4190   if (N0.getOpcode() == ISD::UNDEF)
4191     return DAG.getConstant(0, VT);
4192   // if (shl x, c) is known to be zero, return 0
4193   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4194                             APInt::getAllOnesValue(OpSizeInBits)))
4195     return DAG.getConstant(0, VT);
4196   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4197   if (N1.getOpcode() == ISD::TRUNCATE &&
4198       N1.getOperand(0).getOpcode() == ISD::AND) {
4199     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4200     if (NewOp1.getNode())
4201       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4202   }
4203
4204   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4205     return SDValue(N, 0);
4206
4207   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4208   if (N1C && N0.getOpcode() == ISD::SHL) {
4209     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4210       uint64_t c1 = N0C1->getZExtValue();
4211       uint64_t c2 = N1C->getZExtValue();
4212       if (c1 + c2 >= OpSizeInBits)
4213         return DAG.getConstant(0, VT);
4214       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4215                          DAG.getConstant(c1 + c2, N1.getValueType()));
4216     }
4217   }
4218
4219   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4220   // For this to be valid, the second form must not preserve any of the bits
4221   // that are shifted out by the inner shift in the first form.  This means
4222   // the outer shift size must be >= the number of bits added by the ext.
4223   // As a corollary, we don't care what kind of ext it is.
4224   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4225               N0.getOpcode() == ISD::ANY_EXTEND ||
4226               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4227       N0.getOperand(0).getOpcode() == ISD::SHL) {
4228     SDValue N0Op0 = N0.getOperand(0);
4229     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4230       uint64_t c1 = N0Op0C1->getZExtValue();
4231       uint64_t c2 = N1C->getZExtValue();
4232       EVT InnerShiftVT = N0Op0.getValueType();
4233       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4234       if (c2 >= OpSizeInBits - InnerShiftSize) {
4235         if (c1 + c2 >= OpSizeInBits)
4236           return DAG.getConstant(0, VT);
4237         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4238                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4239                                        N0Op0->getOperand(0)),
4240                            DAG.getConstant(c1 + c2, N1.getValueType()));
4241       }
4242     }
4243   }
4244
4245   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4246   // Only fold this if the inner zext has no other uses to avoid increasing
4247   // the total number of instructions.
4248   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4249       N0.getOperand(0).getOpcode() == ISD::SRL) {
4250     SDValue N0Op0 = N0.getOperand(0);
4251     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4252       uint64_t c1 = N0Op0C1->getZExtValue();
4253       if (c1 < VT.getScalarSizeInBits()) {
4254         uint64_t c2 = N1C->getZExtValue();
4255         if (c1 == c2) {
4256           SDValue NewOp0 = N0.getOperand(0);
4257           EVT CountVT = NewOp0.getOperand(1).getValueType();
4258           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4259                                        NewOp0, DAG.getConstant(c2, CountVT));
4260           AddToWorklist(NewSHL.getNode());
4261           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4262         }
4263       }
4264     }
4265   }
4266
4267   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4268   //                               (and (srl x, (sub c1, c2), MASK)
4269   // Only fold this if the inner shift has no other uses -- if it does, folding
4270   // this will increase the total number of instructions.
4271   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4272     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4273       uint64_t c1 = N0C1->getZExtValue();
4274       if (c1 < OpSizeInBits) {
4275         uint64_t c2 = N1C->getZExtValue();
4276         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4277         SDValue Shift;
4278         if (c2 > c1) {
4279           Mask = Mask.shl(c2 - c1);
4280           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4281                               DAG.getConstant(c2 - c1, N1.getValueType()));
4282         } else {
4283           Mask = Mask.lshr(c1 - c2);
4284           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4285                               DAG.getConstant(c1 - c2, N1.getValueType()));
4286         }
4287         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4288                            DAG.getConstant(Mask, VT));
4289       }
4290     }
4291   }
4292   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4293   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4294     unsigned BitSize = VT.getScalarSizeInBits();
4295     SDValue HiBitsMask =
4296       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4297                                             BitSize - N1C->getZExtValue()), VT);
4298     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4299                        HiBitsMask);
4300   }
4301
4302   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4303   // Variant of version done on multiply, except mul by a power of 2 is turned
4304   // into a shift.
4305   APInt Val;
4306   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4307       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4308        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4309     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4310     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4311     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4312   }
4313
4314   if (N1C) {
4315     SDValue NewSHL = visitShiftByConstant(N, N1C);
4316     if (NewSHL.getNode())
4317       return NewSHL;
4318   }
4319
4320   return SDValue();
4321 }
4322
4323 SDValue DAGCombiner::visitSRA(SDNode *N) {
4324   SDValue N0 = N->getOperand(0);
4325   SDValue N1 = N->getOperand(1);
4326   EVT VT = N0.getValueType();
4327   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4328
4329   // fold vector ops
4330   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4331   if (VT.isVector()) {
4332     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4333       return FoldedVOp;
4334
4335     N1C = isConstOrConstSplat(N1);
4336   }
4337
4338   // fold (sra c1, c2) -> (sra c1, c2)
4339   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4340   if (N0C && N1C)
4341     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4342   // fold (sra 0, x) -> 0
4343   if (N0C && N0C->isNullValue())
4344     return N0;
4345   // fold (sra -1, x) -> -1
4346   if (N0C && N0C->isAllOnesValue())
4347     return N0;
4348   // fold (sra x, (setge c, size(x))) -> undef
4349   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4350     return DAG.getUNDEF(VT);
4351   // fold (sra x, 0) -> x
4352   if (N1C && N1C->isNullValue())
4353     return N0;
4354   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4355   // sext_inreg.
4356   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4357     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4358     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4359     if (VT.isVector())
4360       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4361                                ExtVT, VT.getVectorNumElements());
4362     if ((!LegalOperations ||
4363          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4364       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4365                          N0.getOperand(0), DAG.getValueType(ExtVT));
4366   }
4367
4368   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4369   if (N1C && N0.getOpcode() == ISD::SRA) {
4370     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4371       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4372       if (Sum >= OpSizeInBits)
4373         Sum = OpSizeInBits - 1;
4374       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4375                          DAG.getConstant(Sum, N1.getValueType()));
4376     }
4377   }
4378
4379   // fold (sra (shl X, m), (sub result_size, n))
4380   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4381   // result_size - n != m.
4382   // If truncate is free for the target sext(shl) is likely to result in better
4383   // code.
4384   if (N0.getOpcode() == ISD::SHL && N1C) {
4385     // Get the two constanst of the shifts, CN0 = m, CN = n.
4386     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4387     if (N01C) {
4388       LLVMContext &Ctx = *DAG.getContext();
4389       // Determine what the truncate's result bitsize and type would be.
4390       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4391
4392       if (VT.isVector())
4393         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4394
4395       // Determine the residual right-shift amount.
4396       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4397
4398       // If the shift is not a no-op (in which case this should be just a sign
4399       // extend already), the truncated to type is legal, sign_extend is legal
4400       // on that type, and the truncate to that type is both legal and free,
4401       // perform the transform.
4402       if ((ShiftAmt > 0) &&
4403           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4404           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4405           TLI.isTruncateFree(VT, TruncVT)) {
4406
4407           SDValue Amt = DAG.getConstant(ShiftAmt,
4408               getShiftAmountTy(N0.getOperand(0).getValueType()));
4409           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4410                                       N0.getOperand(0), Amt);
4411           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4412                                       Shift);
4413           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4414                              N->getValueType(0), Trunc);
4415       }
4416     }
4417   }
4418
4419   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4420   if (N1.getOpcode() == ISD::TRUNCATE &&
4421       N1.getOperand(0).getOpcode() == ISD::AND) {
4422     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4423     if (NewOp1.getNode())
4424       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4425   }
4426
4427   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4428   //      if c1 is equal to the number of bits the trunc removes
4429   if (N0.getOpcode() == ISD::TRUNCATE &&
4430       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4431        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4432       N0.getOperand(0).hasOneUse() &&
4433       N0.getOperand(0).getOperand(1).hasOneUse() &&
4434       N1C) {
4435     SDValue N0Op0 = N0.getOperand(0);
4436     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4437       unsigned LargeShiftVal = LargeShift->getZExtValue();
4438       EVT LargeVT = N0Op0.getValueType();
4439
4440       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4441         SDValue Amt =
4442           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4443                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4444         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4445                                   N0Op0.getOperand(0), Amt);
4446         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4447       }
4448     }
4449   }
4450
4451   // Simplify, based on bits shifted out of the LHS.
4452   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4453     return SDValue(N, 0);
4454
4455
4456   // If the sign bit is known to be zero, switch this to a SRL.
4457   if (DAG.SignBitIsZero(N0))
4458     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4459
4460   if (N1C) {
4461     SDValue NewSRA = visitShiftByConstant(N, N1C);
4462     if (NewSRA.getNode())
4463       return NewSRA;
4464   }
4465
4466   return SDValue();
4467 }
4468
4469 SDValue DAGCombiner::visitSRL(SDNode *N) {
4470   SDValue N0 = N->getOperand(0);
4471   SDValue N1 = N->getOperand(1);
4472   EVT VT = N0.getValueType();
4473   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4474
4475   // fold vector ops
4476   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4477   if (VT.isVector()) {
4478     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4479       return FoldedVOp;
4480
4481     N1C = isConstOrConstSplat(N1);
4482   }
4483
4484   // fold (srl c1, c2) -> c1 >>u c2
4485   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4486   if (N0C && N1C)
4487     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4488   // fold (srl 0, x) -> 0
4489   if (N0C && N0C->isNullValue())
4490     return N0;
4491   // fold (srl x, c >= size(x)) -> undef
4492   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4493     return DAG.getUNDEF(VT);
4494   // fold (srl x, 0) -> x
4495   if (N1C && N1C->isNullValue())
4496     return N0;
4497   // if (srl x, c) is known to be zero, return 0
4498   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4499                                    APInt::getAllOnesValue(OpSizeInBits)))
4500     return DAG.getConstant(0, VT);
4501
4502   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4503   if (N1C && N0.getOpcode() == ISD::SRL) {
4504     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4505       uint64_t c1 = N01C->getZExtValue();
4506       uint64_t c2 = N1C->getZExtValue();
4507       if (c1 + c2 >= OpSizeInBits)
4508         return DAG.getConstant(0, VT);
4509       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4510                          DAG.getConstant(c1 + c2, N1.getValueType()));
4511     }
4512   }
4513
4514   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4515   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4516       N0.getOperand(0).getOpcode() == ISD::SRL &&
4517       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4518     uint64_t c1 =
4519       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4520     uint64_t c2 = N1C->getZExtValue();
4521     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4522     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4523     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4524     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4525     if (c1 + OpSizeInBits == InnerShiftSize) {
4526       if (c1 + c2 >= InnerShiftSize)
4527         return DAG.getConstant(0, VT);
4528       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4529                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4530                                      N0.getOperand(0)->getOperand(0),
4531                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4532     }
4533   }
4534
4535   // fold (srl (shl x, c), c) -> (and x, cst2)
4536   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4537     unsigned BitSize = N0.getScalarValueSizeInBits();
4538     if (BitSize <= 64) {
4539       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4540       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4541                          DAG.getConstant(~0ULL >> ShAmt, VT));
4542     }
4543   }
4544
4545   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4546   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4547     // Shifting in all undef bits?
4548     EVT SmallVT = N0.getOperand(0).getValueType();
4549     unsigned BitSize = SmallVT.getScalarSizeInBits();
4550     if (N1C->getZExtValue() >= BitSize)
4551       return DAG.getUNDEF(VT);
4552
4553     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4554       uint64_t ShiftAmt = N1C->getZExtValue();
4555       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4556                                        N0.getOperand(0),
4557                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4558       AddToWorklist(SmallShift.getNode());
4559       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4560       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4561                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4562                          DAG.getConstant(Mask, VT));
4563     }
4564   }
4565
4566   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4567   // bit, which is unmodified by sra.
4568   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4569     if (N0.getOpcode() == ISD::SRA)
4570       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4571   }
4572
4573   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4574   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4575       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4576     APInt KnownZero, KnownOne;
4577     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4578
4579     // If any of the input bits are KnownOne, then the input couldn't be all
4580     // zeros, thus the result of the srl will always be zero.
4581     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4582
4583     // If all of the bits input the to ctlz node are known to be zero, then
4584     // the result of the ctlz is "32" and the result of the shift is one.
4585     APInt UnknownBits = ~KnownZero;
4586     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4587
4588     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4589     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4590       // Okay, we know that only that the single bit specified by UnknownBits
4591       // could be set on input to the CTLZ node. If this bit is set, the SRL
4592       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4593       // to an SRL/XOR pair, which is likely to simplify more.
4594       unsigned ShAmt = UnknownBits.countTrailingZeros();
4595       SDValue Op = N0.getOperand(0);
4596
4597       if (ShAmt) {
4598         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4599                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4600         AddToWorklist(Op.getNode());
4601       }
4602
4603       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4604                          Op, DAG.getConstant(1, VT));
4605     }
4606   }
4607
4608   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4609   if (N1.getOpcode() == ISD::TRUNCATE &&
4610       N1.getOperand(0).getOpcode() == ISD::AND) {
4611     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4612     if (NewOp1.getNode())
4613       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4614   }
4615
4616   // fold operands of srl based on knowledge that the low bits are not
4617   // demanded.
4618   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4619     return SDValue(N, 0);
4620
4621   if (N1C) {
4622     SDValue NewSRL = visitShiftByConstant(N, N1C);
4623     if (NewSRL.getNode())
4624       return NewSRL;
4625   }
4626
4627   // Attempt to convert a srl of a load into a narrower zero-extending load.
4628   SDValue NarrowLoad = ReduceLoadWidth(N);
4629   if (NarrowLoad.getNode())
4630     return NarrowLoad;
4631
4632   // Here is a common situation. We want to optimize:
4633   //
4634   //   %a = ...
4635   //   %b = and i32 %a, 2
4636   //   %c = srl i32 %b, 1
4637   //   brcond i32 %c ...
4638   //
4639   // into
4640   //
4641   //   %a = ...
4642   //   %b = and %a, 2
4643   //   %c = setcc eq %b, 0
4644   //   brcond %c ...
4645   //
4646   // However when after the source operand of SRL is optimized into AND, the SRL
4647   // itself may not be optimized further. Look for it and add the BRCOND into
4648   // the worklist.
4649   if (N->hasOneUse()) {
4650     SDNode *Use = *N->use_begin();
4651     if (Use->getOpcode() == ISD::BRCOND)
4652       AddToWorklist(Use);
4653     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4654       // Also look pass the truncate.
4655       Use = *Use->use_begin();
4656       if (Use->getOpcode() == ISD::BRCOND)
4657         AddToWorklist(Use);
4658     }
4659   }
4660
4661   return SDValue();
4662 }
4663
4664 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4665   SDValue N0 = N->getOperand(0);
4666   EVT VT = N->getValueType(0);
4667
4668   // fold (ctlz c1) -> c2
4669   if (isa<ConstantSDNode>(N0))
4670     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4671   return SDValue();
4672 }
4673
4674 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4675   SDValue N0 = N->getOperand(0);
4676   EVT VT = N->getValueType(0);
4677
4678   // fold (ctlz_zero_undef c1) -> c2
4679   if (isa<ConstantSDNode>(N0))
4680     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4681   return SDValue();
4682 }
4683
4684 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4685   SDValue N0 = N->getOperand(0);
4686   EVT VT = N->getValueType(0);
4687
4688   // fold (cttz c1) -> c2
4689   if (isa<ConstantSDNode>(N0))
4690     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4691   return SDValue();
4692 }
4693
4694 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4695   SDValue N0 = N->getOperand(0);
4696   EVT VT = N->getValueType(0);
4697
4698   // fold (cttz_zero_undef c1) -> c2
4699   if (isa<ConstantSDNode>(N0))
4700     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4701   return SDValue();
4702 }
4703
4704 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4705   SDValue N0 = N->getOperand(0);
4706   EVT VT = N->getValueType(0);
4707
4708   // fold (ctpop c1) -> c2
4709   if (isa<ConstantSDNode>(N0))
4710     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4711   return SDValue();
4712 }
4713
4714
4715 /// \brief Generate Min/Max node
4716 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4717                                    SDValue True, SDValue False,
4718                                    ISD::CondCode CC, const TargetLowering &TLI,
4719                                    SelectionDAG &DAG) {
4720   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4721     return SDValue();
4722
4723   switch (CC) {
4724   case ISD::SETOLT:
4725   case ISD::SETOLE:
4726   case ISD::SETLT:
4727   case ISD::SETLE:
4728   case ISD::SETULT:
4729   case ISD::SETULE: {
4730     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4731     if (TLI.isOperationLegal(Opcode, VT))
4732       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4733     return SDValue();
4734   }
4735   case ISD::SETOGT:
4736   case ISD::SETOGE:
4737   case ISD::SETGT:
4738   case ISD::SETGE:
4739   case ISD::SETUGT:
4740   case ISD::SETUGE: {
4741     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4742     if (TLI.isOperationLegal(Opcode, VT))
4743       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4744     return SDValue();
4745   }
4746   default:
4747     return SDValue();
4748   }
4749 }
4750
4751 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4752   SDValue N0 = N->getOperand(0);
4753   SDValue N1 = N->getOperand(1);
4754   SDValue N2 = N->getOperand(2);
4755   EVT VT = N->getValueType(0);
4756   EVT VT0 = N0.getValueType();
4757
4758   // fold (select C, X, X) -> X
4759   if (N1 == N2)
4760     return N1;
4761   // fold (select true, X, Y) -> X
4762   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4763   if (N0C && !N0C->isNullValue())
4764     return N1;
4765   // fold (select false, X, Y) -> Y
4766   if (N0C && N0C->isNullValue())
4767     return N2;
4768   // fold (select C, 1, X) -> (or C, X)
4769   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4770   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4771     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4772   // fold (select C, 0, 1) -> (xor C, 1)
4773   // We can't do this reliably if integer based booleans have different contents
4774   // to floating point based booleans. This is because we can't tell whether we
4775   // have an integer-based boolean or a floating-point-based boolean unless we
4776   // can find the SETCC that produced it and inspect its operands. This is
4777   // fairly easy if C is the SETCC node, but it can potentially be
4778   // undiscoverable (or not reasonably discoverable). For example, it could be
4779   // in another basic block or it could require searching a complicated
4780   // expression.
4781   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4782   if (VT.isInteger() &&
4783       (VT0 == MVT::i1 || (VT0.isInteger() &&
4784                           TLI.getBooleanContents(false, false) ==
4785                               TLI.getBooleanContents(false, true) &&
4786                           TLI.getBooleanContents(false, false) ==
4787                               TargetLowering::ZeroOrOneBooleanContent)) &&
4788       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4789     SDValue XORNode;
4790     if (VT == VT0)
4791       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4792                          N0, DAG.getConstant(1, VT0));
4793     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4794                           N0, DAG.getConstant(1, VT0));
4795     AddToWorklist(XORNode.getNode());
4796     if (VT.bitsGT(VT0))
4797       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4798     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4799   }
4800   // fold (select C, 0, X) -> (and (not C), X)
4801   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4802     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4803     AddToWorklist(NOTNode.getNode());
4804     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4805   }
4806   // fold (select C, X, 1) -> (or (not C), X)
4807   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4808     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4809     AddToWorklist(NOTNode.getNode());
4810     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4811   }
4812   // fold (select C, X, 0) -> (and C, X)
4813   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4814     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4815   // fold (select X, X, Y) -> (or X, Y)
4816   // fold (select X, 1, Y) -> (or X, Y)
4817   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4818     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4819   // fold (select X, Y, X) -> (and X, Y)
4820   // fold (select X, Y, 0) -> (and X, Y)
4821   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4822     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4823
4824   // If we can fold this based on the true/false value, do so.
4825   if (SimplifySelectOps(N, N1, N2))
4826     return SDValue(N, 0);  // Don't revisit N.
4827
4828   // fold selects based on a setcc into other things, such as min/max/abs
4829   if (N0.getOpcode() == ISD::SETCC) {
4830     // select x, y (fcmp lt x, y) -> fminnum x, y
4831     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4832     //
4833     // This is OK if we don't care about what happens if either operand is a
4834     // NaN.
4835     //
4836
4837     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4838     // no signed zeros as well as no nans.
4839     const TargetOptions &Options = DAG.getTarget().Options;
4840     if (Options.UnsafeFPMath &&
4841         VT.isFloatingPoint() && N0.hasOneUse() &&
4842         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4843       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4844
4845       SDValue FMinMax =
4846           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4847                               N1, N2, CC, TLI, DAG);
4848       if (FMinMax)
4849         return FMinMax;
4850     }
4851
4852     if ((!LegalOperations &&
4853          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4854         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4855       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4856                          N0.getOperand(0), N0.getOperand(1),
4857                          N1, N2, N0.getOperand(2));
4858     return SimplifySelect(SDLoc(N), N0, N1, N2);
4859   }
4860
4861   if (VT0 == MVT::i1) {
4862     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4863       // select (and Cond0, Cond1), X, Y
4864       //   -> select Cond0, (select Cond1, X, Y), Y
4865       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4866         SDValue Cond0 = N0->getOperand(0);
4867         SDValue Cond1 = N0->getOperand(1);
4868         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4869                                           N1.getValueType(), Cond1, N1, N2);
4870         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4871                            InnerSelect, N2);
4872       }
4873       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4874       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4875         SDValue Cond0 = N0->getOperand(0);
4876         SDValue Cond1 = N0->getOperand(1);
4877         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4878                                           N1.getValueType(), Cond1, N1, N2);
4879         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4880                            InnerSelect);
4881       }
4882     }
4883
4884     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4885     if (N1->getOpcode() == ISD::SELECT) {
4886       SDValue N1_0 = N1->getOperand(0);
4887       SDValue N1_1 = N1->getOperand(1);
4888       SDValue N1_2 = N1->getOperand(2);
4889       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4890         // Create the actual and node if we can generate good code for it.
4891         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4892           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4893                                     N0, N1_0);
4894           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4895                              N1_1, N2);
4896         }
4897         // Otherwise see if we can optimize the "and" to a better pattern.
4898         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4899           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4900                              N1_1, N2);
4901       }
4902     }
4903     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4904     if (N2->getOpcode() == ISD::SELECT) {
4905       SDValue N2_0 = N2->getOperand(0);
4906       SDValue N2_1 = N2->getOperand(1);
4907       SDValue N2_2 = N2->getOperand(2);
4908       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4909         // Create the actual or node if we can generate good code for it.
4910         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4911           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4912                                    N0, N2_0);
4913           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4914                              N1, N2_2);
4915         }
4916         // Otherwise see if we can optimize to a better pattern.
4917         if (SDValue Combined = visitORLike(N0, N2_0, N))
4918           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4919                              N1, N2_2);
4920       }
4921     }
4922   }
4923
4924   return SDValue();
4925 }
4926
4927 static
4928 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4929   SDLoc DL(N);
4930   EVT LoVT, HiVT;
4931   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4932
4933   // Split the inputs.
4934   SDValue Lo, Hi, LL, LH, RL, RH;
4935   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4936   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4937
4938   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4939   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4940
4941   return std::make_pair(Lo, Hi);
4942 }
4943
4944 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4945 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4946 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4947   SDLoc dl(N);
4948   SDValue Cond = N->getOperand(0);
4949   SDValue LHS = N->getOperand(1);
4950   SDValue RHS = N->getOperand(2);
4951   EVT VT = N->getValueType(0);
4952   int NumElems = VT.getVectorNumElements();
4953   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4954          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4955          Cond.getOpcode() == ISD::BUILD_VECTOR);
4956
4957   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4958   // binary ones here.
4959   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4960     return SDValue();
4961
4962   // We're sure we have an even number of elements due to the
4963   // concat_vectors we have as arguments to vselect.
4964   // Skip BV elements until we find one that's not an UNDEF
4965   // After we find an UNDEF element, keep looping until we get to half the
4966   // length of the BV and see if all the non-undef nodes are the same.
4967   ConstantSDNode *BottomHalf = nullptr;
4968   for (int i = 0; i < NumElems / 2; ++i) {
4969     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4970       continue;
4971
4972     if (BottomHalf == nullptr)
4973       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4974     else if (Cond->getOperand(i).getNode() != BottomHalf)
4975       return SDValue();
4976   }
4977
4978   // Do the same for the second half of the BuildVector
4979   ConstantSDNode *TopHalf = nullptr;
4980   for (int i = NumElems / 2; i < NumElems; ++i) {
4981     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4982       continue;
4983
4984     if (TopHalf == nullptr)
4985       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4986     else if (Cond->getOperand(i).getNode() != TopHalf)
4987       return SDValue();
4988   }
4989
4990   assert(TopHalf && BottomHalf &&
4991          "One half of the selector was all UNDEFs and the other was all the "
4992          "same value. This should have been addressed before this function.");
4993   return DAG.getNode(
4994       ISD::CONCAT_VECTORS, dl, VT,
4995       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4996       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4997 }
4998
4999 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5000
5001   if (Level >= AfterLegalizeTypes)
5002     return SDValue();
5003
5004   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5005   SDValue Mask = MST->getMask();
5006   SDValue Data  = MST->getValue();
5007   SDLoc DL(N);
5008
5009   // If the MSTORE data type requires splitting and the mask is provided by a
5010   // SETCC, then split both nodes and its operands before legalization. This
5011   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5012   // and enables future optimizations (e.g. min/max pattern matching on X86).
5013   if (Mask.getOpcode() == ISD::SETCC) {
5014
5015     // Check if any splitting is required.
5016     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5017         TargetLowering::TypeSplitVector)
5018       return SDValue();
5019
5020     SDValue MaskLo, MaskHi, Lo, Hi;
5021     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5022
5023     EVT LoVT, HiVT;
5024     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5025
5026     SDValue Chain = MST->getChain();
5027     SDValue Ptr   = MST->getBasePtr();
5028
5029     EVT MemoryVT = MST->getMemoryVT();
5030     unsigned Alignment = MST->getOriginalAlignment();
5031
5032     // if Alignment is equal to the vector size,
5033     // take the half of it for the second part
5034     unsigned SecondHalfAlignment =
5035       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5036          Alignment/2 : Alignment;
5037
5038     EVT LoMemVT, HiMemVT;
5039     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5040
5041     SDValue DataLo, DataHi;
5042     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5043
5044     MachineMemOperand *MMO = DAG.getMachineFunction().
5045       getMachineMemOperand(MST->getPointerInfo(),
5046                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5047                            Alignment, MST->getAAInfo(), MST->getRanges());
5048
5049     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5050                             MST->isTruncatingStore());
5051
5052     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5053     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5054                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5055
5056     MMO = DAG.getMachineFunction().
5057       getMachineMemOperand(MST->getPointerInfo(),
5058                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5059                            SecondHalfAlignment, MST->getAAInfo(),
5060                            MST->getRanges());
5061
5062     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5063                             MST->isTruncatingStore());
5064
5065     AddToWorklist(Lo.getNode());
5066     AddToWorklist(Hi.getNode());
5067
5068     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5069   }
5070   return SDValue();
5071 }
5072
5073 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5074
5075   if (Level >= AfterLegalizeTypes)
5076     return SDValue();
5077
5078   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5079   SDValue Mask = MLD->getMask();
5080   SDLoc DL(N);
5081
5082   // If the MLOAD result requires splitting and the mask is provided by a
5083   // SETCC, then split both nodes and its operands before legalization. This
5084   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5085   // and enables future optimizations (e.g. min/max pattern matching on X86).
5086
5087   if (Mask.getOpcode() == ISD::SETCC) {
5088     EVT VT = N->getValueType(0);
5089
5090     // Check if any splitting is required.
5091     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5092         TargetLowering::TypeSplitVector)
5093       return SDValue();
5094
5095     SDValue MaskLo, MaskHi, Lo, Hi;
5096     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5097
5098     SDValue Src0 = MLD->getSrc0();
5099     SDValue Src0Lo, Src0Hi;
5100     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5101
5102     EVT LoVT, HiVT;
5103     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5104
5105     SDValue Chain = MLD->getChain();
5106     SDValue Ptr   = MLD->getBasePtr();
5107     EVT MemoryVT = MLD->getMemoryVT();
5108     unsigned Alignment = MLD->getOriginalAlignment();
5109
5110     // if Alignment is equal to the vector size,
5111     // take the half of it for the second part
5112     unsigned SecondHalfAlignment =
5113       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5114          Alignment/2 : Alignment;
5115
5116     EVT LoMemVT, HiMemVT;
5117     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5118
5119     MachineMemOperand *MMO = DAG.getMachineFunction().
5120     getMachineMemOperand(MLD->getPointerInfo(),
5121                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5122                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5123
5124     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5125                            ISD::NON_EXTLOAD);
5126
5127     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5128     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5129                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
5130
5131     MMO = DAG.getMachineFunction().
5132     getMachineMemOperand(MLD->getPointerInfo(),
5133                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5134                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5135
5136     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5137                            ISD::NON_EXTLOAD);
5138
5139     AddToWorklist(Lo.getNode());
5140     AddToWorklist(Hi.getNode());
5141
5142     // Build a factor node to remember that this load is independent of the
5143     // other one.
5144     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5145                         Hi.getValue(1));
5146
5147     // Legalized the chain result - switch anything that used the old chain to
5148     // use the new one.
5149     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5150
5151     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5152
5153     SDValue RetOps[] = { LoadRes, Chain };
5154     return DAG.getMergeValues(RetOps, DL);
5155   }
5156   return SDValue();
5157 }
5158
5159 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5160   SDValue N0 = N->getOperand(0);
5161   SDValue N1 = N->getOperand(1);
5162   SDValue N2 = N->getOperand(2);
5163   SDLoc DL(N);
5164
5165   // Canonicalize integer abs.
5166   // vselect (setg[te] X,  0),  X, -X ->
5167   // vselect (setgt    X, -1),  X, -X ->
5168   // vselect (setl[te] X,  0), -X,  X ->
5169   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5170   if (N0.getOpcode() == ISD::SETCC) {
5171     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5172     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5173     bool isAbs = false;
5174     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5175
5176     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5177          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5178         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5179       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5180     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5181              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5182       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5183
5184     if (isAbs) {
5185       EVT VT = LHS.getValueType();
5186       SDValue Shift = DAG.getNode(
5187           ISD::SRA, DL, VT, LHS,
5188           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5189       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5190       AddToWorklist(Shift.getNode());
5191       AddToWorklist(Add.getNode());
5192       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5193     }
5194   }
5195
5196   if (SimplifySelectOps(N, N1, N2))
5197     return SDValue(N, 0);  // Don't revisit N.
5198
5199   // If the VSELECT result requires splitting and the mask is provided by a
5200   // SETCC, then split both nodes and its operands before legalization. This
5201   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5202   // and enables future optimizations (e.g. min/max pattern matching on X86).
5203   if (N0.getOpcode() == ISD::SETCC) {
5204     EVT VT = N->getValueType(0);
5205
5206     // Check if any splitting is required.
5207     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5208         TargetLowering::TypeSplitVector)
5209       return SDValue();
5210
5211     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5212     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5213     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5214     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5215
5216     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5217     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5218
5219     // Add the new VSELECT nodes to the work list in case they need to be split
5220     // again.
5221     AddToWorklist(Lo.getNode());
5222     AddToWorklist(Hi.getNode());
5223
5224     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5225   }
5226
5227   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5228   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5229     return N1;
5230   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5231   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5232     return N2;
5233
5234   // The ConvertSelectToConcatVector function is assuming both the above
5235   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5236   // and addressed.
5237   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5238       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5239       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5240     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5241     if (CV.getNode())
5242       return CV;
5243   }
5244
5245   return SDValue();
5246 }
5247
5248 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5249   SDValue N0 = N->getOperand(0);
5250   SDValue N1 = N->getOperand(1);
5251   SDValue N2 = N->getOperand(2);
5252   SDValue N3 = N->getOperand(3);
5253   SDValue N4 = N->getOperand(4);
5254   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5255
5256   // fold select_cc lhs, rhs, x, x, cc -> x
5257   if (N2 == N3)
5258     return N2;
5259
5260   // Determine if the condition we're dealing with is constant
5261   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5262                               N0, N1, CC, SDLoc(N), false);
5263   if (SCC.getNode()) {
5264     AddToWorklist(SCC.getNode());
5265
5266     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5267       if (!SCCC->isNullValue())
5268         return N2;    // cond always true -> true val
5269       else
5270         return N3;    // cond always false -> false val
5271     } else if (SCC->getOpcode() == ISD::UNDEF) {
5272       // When the condition is UNDEF, just return the first operand. This is
5273       // coherent the DAG creation, no setcc node is created in this case
5274       return N2;
5275     } else if (SCC.getOpcode() == ISD::SETCC) {
5276       // Fold to a simpler select_cc
5277       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5278                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5279                          SCC.getOperand(2));
5280     }
5281   }
5282
5283   // If we can fold this based on the true/false value, do so.
5284   if (SimplifySelectOps(N, N2, N3))
5285     return SDValue(N, 0);  // Don't revisit N.
5286
5287   // fold select_cc into other things, such as min/max/abs
5288   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5289 }
5290
5291 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5292   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5293                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5294                        SDLoc(N));
5295 }
5296
5297 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5298 // dag node into a ConstantSDNode or a build_vector of constants.
5299 // This function is called by the DAGCombiner when visiting sext/zext/aext
5300 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5301 // Vector extends are not folded if operations are legal; this is to
5302 // avoid introducing illegal build_vector dag nodes.
5303 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5304                                          SelectionDAG &DAG, bool LegalTypes,
5305                                          bool LegalOperations) {
5306   unsigned Opcode = N->getOpcode();
5307   SDValue N0 = N->getOperand(0);
5308   EVT VT = N->getValueType(0);
5309
5310   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5311          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5312
5313   // fold (sext c1) -> c1
5314   // fold (zext c1) -> c1
5315   // fold (aext c1) -> c1
5316   if (isa<ConstantSDNode>(N0))
5317     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5318
5319   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5320   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5321   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5322   EVT SVT = VT.getScalarType();
5323   if (!(VT.isVector() &&
5324       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5325       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5326     return nullptr;
5327
5328   // We can fold this node into a build_vector.
5329   unsigned VTBits = SVT.getSizeInBits();
5330   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5331   unsigned ShAmt = VTBits - EVTBits;
5332   SmallVector<SDValue, 8> Elts;
5333   unsigned NumElts = N0->getNumOperands();
5334   SDLoc DL(N);
5335
5336   for (unsigned i=0; i != NumElts; ++i) {
5337     SDValue Op = N0->getOperand(i);
5338     if (Op->getOpcode() == ISD::UNDEF) {
5339       Elts.push_back(DAG.getUNDEF(SVT));
5340       continue;
5341     }
5342
5343     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5344     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5345     if (Opcode == ISD::SIGN_EXTEND)
5346       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5347                                      SVT));
5348     else
5349       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5350                                      SVT));
5351   }
5352
5353   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5354 }
5355
5356 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5357 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5358 // transformation. Returns true if extension are possible and the above
5359 // mentioned transformation is profitable.
5360 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5361                                     unsigned ExtOpc,
5362                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5363                                     const TargetLowering &TLI) {
5364   bool HasCopyToRegUses = false;
5365   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5366   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5367                             UE = N0.getNode()->use_end();
5368        UI != UE; ++UI) {
5369     SDNode *User = *UI;
5370     if (User == N)
5371       continue;
5372     if (UI.getUse().getResNo() != N0.getResNo())
5373       continue;
5374     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5375     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5376       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5377       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5378         // Sign bits will be lost after a zext.
5379         return false;
5380       bool Add = false;
5381       for (unsigned i = 0; i != 2; ++i) {
5382         SDValue UseOp = User->getOperand(i);
5383         if (UseOp == N0)
5384           continue;
5385         if (!isa<ConstantSDNode>(UseOp))
5386           return false;
5387         Add = true;
5388       }
5389       if (Add)
5390         ExtendNodes.push_back(User);
5391       continue;
5392     }
5393     // If truncates aren't free and there are users we can't
5394     // extend, it isn't worthwhile.
5395     if (!isTruncFree)
5396       return false;
5397     // Remember if this value is live-out.
5398     if (User->getOpcode() == ISD::CopyToReg)
5399       HasCopyToRegUses = true;
5400   }
5401
5402   if (HasCopyToRegUses) {
5403     bool BothLiveOut = false;
5404     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5405          UI != UE; ++UI) {
5406       SDUse &Use = UI.getUse();
5407       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5408         BothLiveOut = true;
5409         break;
5410       }
5411     }
5412     if (BothLiveOut)
5413       // Both unextended and extended values are live out. There had better be
5414       // a good reason for the transformation.
5415       return ExtendNodes.size();
5416   }
5417   return true;
5418 }
5419
5420 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5421                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5422                                   ISD::NodeType ExtType) {
5423   // Extend SetCC uses if necessary.
5424   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5425     SDNode *SetCC = SetCCs[i];
5426     SmallVector<SDValue, 4> Ops;
5427
5428     for (unsigned j = 0; j != 2; ++j) {
5429       SDValue SOp = SetCC->getOperand(j);
5430       if (SOp == Trunc)
5431         Ops.push_back(ExtLoad);
5432       else
5433         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5434     }
5435
5436     Ops.push_back(SetCC->getOperand(2));
5437     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5438   }
5439 }
5440
5441 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5442 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5443   SDValue N0 = N->getOperand(0);
5444   EVT DstVT = N->getValueType(0);
5445   EVT SrcVT = N0.getValueType();
5446
5447   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5448           N->getOpcode() == ISD::ZERO_EXTEND) &&
5449          "Unexpected node type (not an extend)!");
5450
5451   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5452   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5453   //   (v8i32 (sext (v8i16 (load x))))
5454   // into:
5455   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5456   //                          (v4i32 (sextload (x + 16)))))
5457   // Where uses of the original load, i.e.:
5458   //   (v8i16 (load x))
5459   // are replaced with:
5460   //   (v8i16 (truncate
5461   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5462   //                            (v4i32 (sextload (x + 16)))))))
5463   //
5464   // This combine is only applicable to illegal, but splittable, vectors.
5465   // All legal types, and illegal non-vector types, are handled elsewhere.
5466   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5467   //
5468   if (N0->getOpcode() != ISD::LOAD)
5469     return SDValue();
5470
5471   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472
5473   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5474       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5475       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5476     return SDValue();
5477
5478   SmallVector<SDNode *, 4> SetCCs;
5479   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5480     return SDValue();
5481
5482   ISD::LoadExtType ExtType =
5483       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5484
5485   // Try to split the vector types to get down to legal types.
5486   EVT SplitSrcVT = SrcVT;
5487   EVT SplitDstVT = DstVT;
5488   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5489          SplitSrcVT.getVectorNumElements() > 1) {
5490     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5491     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5492   }
5493
5494   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5495     return SDValue();
5496
5497   SDLoc DL(N);
5498   const unsigned NumSplits =
5499       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5500   const unsigned Stride = SplitSrcVT.getStoreSize();
5501   SmallVector<SDValue, 4> Loads;
5502   SmallVector<SDValue, 4> Chains;
5503
5504   SDValue BasePtr = LN0->getBasePtr();
5505   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5506     const unsigned Offset = Idx * Stride;
5507     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5508
5509     SDValue SplitLoad = DAG.getExtLoad(
5510         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5511         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5512         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5513         Align, LN0->getAAInfo());
5514
5515     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5516                           DAG.getConstant(Stride, BasePtr.getValueType()));
5517
5518     Loads.push_back(SplitLoad.getValue(0));
5519     Chains.push_back(SplitLoad.getValue(1));
5520   }
5521
5522   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5523   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5524
5525   CombineTo(N, NewValue);
5526
5527   // Replace uses of the original load (before extension)
5528   // with a truncate of the concatenated sextloaded vectors.
5529   SDValue Trunc =
5530       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5531   CombineTo(N0.getNode(), Trunc, NewChain);
5532   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5533                   (ISD::NodeType)N->getOpcode());
5534   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5535 }
5536
5537 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5538   SDValue N0 = N->getOperand(0);
5539   EVT VT = N->getValueType(0);
5540
5541   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5542                                               LegalOperations))
5543     return SDValue(Res, 0);
5544
5545   // fold (sext (sext x)) -> (sext x)
5546   // fold (sext (aext x)) -> (sext x)
5547   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5548     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5549                        N0.getOperand(0));
5550
5551   if (N0.getOpcode() == ISD::TRUNCATE) {
5552     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5553     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5554     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555     if (NarrowLoad.getNode()) {
5556       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557       if (NarrowLoad.getNode() != N0.getNode()) {
5558         CombineTo(N0.getNode(), NarrowLoad);
5559         // CombineTo deleted the truncate, if needed, but not what's under it.
5560         AddToWorklist(oye);
5561       }
5562       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5563     }
5564
5565     // See if the value being truncated is already sign extended.  If so, just
5566     // eliminate the trunc/sext pair.
5567     SDValue Op = N0.getOperand(0);
5568     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5569     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5570     unsigned DestBits = VT.getScalarType().getSizeInBits();
5571     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5572
5573     if (OpBits == DestBits) {
5574       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5575       // bits, it is already ready.
5576       if (NumSignBits > DestBits-MidBits)
5577         return Op;
5578     } else if (OpBits < DestBits) {
5579       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5580       // bits, just sext from i32.
5581       if (NumSignBits > OpBits-MidBits)
5582         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5583     } else {
5584       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5585       // bits, just truncate to i32.
5586       if (NumSignBits > OpBits-MidBits)
5587         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5588     }
5589
5590     // fold (sext (truncate x)) -> (sextinreg x).
5591     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5592                                                  N0.getValueType())) {
5593       if (OpBits < DestBits)
5594         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5595       else if (OpBits > DestBits)
5596         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5597       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5598                          DAG.getValueType(N0.getValueType()));
5599     }
5600   }
5601
5602   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5603   // Only generate vector extloads when 1) they're legal, and 2) they are
5604   // deemed desirable by the target.
5605   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5606       ((!LegalOperations && !VT.isVector() &&
5607         !cast<LoadSDNode>(N0)->isVolatile()) ||
5608        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5609     bool DoXform = true;
5610     SmallVector<SDNode*, 4> SetCCs;
5611     if (!N0.hasOneUse())
5612       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5613     if (VT.isVector())
5614       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5615     if (DoXform) {
5616       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5617       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5618                                        LN0->getChain(),
5619                                        LN0->getBasePtr(), N0.getValueType(),
5620                                        LN0->getMemOperand());
5621       CombineTo(N, ExtLoad);
5622       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5623                                   N0.getValueType(), ExtLoad);
5624       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5625       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5626                       ISD::SIGN_EXTEND);
5627       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5628     }
5629   }
5630
5631   // fold (sext (load x)) to multiple smaller sextloads.
5632   // Only on illegal but splittable vectors.
5633   if (SDValue ExtLoad = CombineExtLoad(N))
5634     return ExtLoad;
5635
5636   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5637   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5638   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5639       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5640     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5641     EVT MemVT = LN0->getMemoryVT();
5642     if ((!LegalOperations && !LN0->isVolatile()) ||
5643         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5644       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5645                                        LN0->getChain(),
5646                                        LN0->getBasePtr(), MemVT,
5647                                        LN0->getMemOperand());
5648       CombineTo(N, ExtLoad);
5649       CombineTo(N0.getNode(),
5650                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5651                             N0.getValueType(), ExtLoad),
5652                 ExtLoad.getValue(1));
5653       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5654     }
5655   }
5656
5657   // fold (sext (and/or/xor (load x), cst)) ->
5658   //      (and/or/xor (sextload x), (sext cst))
5659   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5660        N0.getOpcode() == ISD::XOR) &&
5661       isa<LoadSDNode>(N0.getOperand(0)) &&
5662       N0.getOperand(1).getOpcode() == ISD::Constant &&
5663       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5664       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5665     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5666     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5667       bool DoXform = true;
5668       SmallVector<SDNode*, 4> SetCCs;
5669       if (!N0.hasOneUse())
5670         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5671                                           SetCCs, TLI);
5672       if (DoXform) {
5673         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5674                                          LN0->getChain(), LN0->getBasePtr(),
5675                                          LN0->getMemoryVT(),
5676                                          LN0->getMemOperand());
5677         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5678         Mask = Mask.sext(VT.getSizeInBits());
5679         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5680                                   ExtLoad, DAG.getConstant(Mask, VT));
5681         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5682                                     SDLoc(N0.getOperand(0)),
5683                                     N0.getOperand(0).getValueType(), ExtLoad);
5684         CombineTo(N, And);
5685         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5686         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5687                         ISD::SIGN_EXTEND);
5688         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5689       }
5690     }
5691   }
5692
5693   if (N0.getOpcode() == ISD::SETCC) {
5694     EVT N0VT = N0.getOperand(0).getValueType();
5695     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5696     // Only do this before legalize for now.
5697     if (VT.isVector() && !LegalOperations &&
5698         TLI.getBooleanContents(N0VT) ==
5699             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5700       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5701       // of the same size as the compared operands. Only optimize sext(setcc())
5702       // if this is the case.
5703       EVT SVT = getSetCCResultType(N0VT);
5704
5705       // We know that the # elements of the results is the same as the
5706       // # elements of the compare (and the # elements of the compare result
5707       // for that matter).  Check to see that they are the same size.  If so,
5708       // we know that the element size of the sext'd result matches the
5709       // element size of the compare operands.
5710       if (VT.getSizeInBits() == SVT.getSizeInBits())
5711         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5712                              N0.getOperand(1),
5713                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5714
5715       // If the desired elements are smaller or larger than the source
5716       // elements we can use a matching integer vector type and then
5717       // truncate/sign extend
5718       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5719       if (SVT == MatchingVectorType) {
5720         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5721                                N0.getOperand(0), N0.getOperand(1),
5722                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5723         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5724       }
5725     }
5726
5727     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5728     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5729     SDValue NegOne =
5730       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5731     SDValue SCC =
5732       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5733                        NegOne, DAG.getConstant(0, VT),
5734                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5735     if (SCC.getNode()) return SCC;
5736
5737     if (!VT.isVector()) {
5738       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5739       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5740         SDLoc DL(N);
5741         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5742         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5743                                      N0.getOperand(0), N0.getOperand(1), CC);
5744         return DAG.getSelect(DL, VT, SetCC,
5745                              NegOne, DAG.getConstant(0, VT));
5746       }
5747     }
5748   }
5749
5750   // fold (sext x) -> (zext x) if the sign bit is known zero.
5751   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5752       DAG.SignBitIsZero(N0))
5753     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5754
5755   return SDValue();
5756 }
5757
5758 // isTruncateOf - If N is a truncate of some other value, return true, record
5759 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5760 // This function computes KnownZero to avoid a duplicated call to
5761 // computeKnownBits in the caller.
5762 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5763                          APInt &KnownZero) {
5764   APInt KnownOne;
5765   if (N->getOpcode() == ISD::TRUNCATE) {
5766     Op = N->getOperand(0);
5767     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5768     return true;
5769   }
5770
5771   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5772       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5773     return false;
5774
5775   SDValue Op0 = N->getOperand(0);
5776   SDValue Op1 = N->getOperand(1);
5777   assert(Op0.getValueType() == Op1.getValueType());
5778
5779   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5780   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5781   if (COp0 && COp0->isNullValue())
5782     Op = Op1;
5783   else if (COp1 && COp1->isNullValue())
5784     Op = Op0;
5785   else
5786     return false;
5787
5788   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5789
5790   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5791     return false;
5792
5793   return true;
5794 }
5795
5796 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5797   SDValue N0 = N->getOperand(0);
5798   EVT VT = N->getValueType(0);
5799
5800   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5801                                               LegalOperations))
5802     return SDValue(Res, 0);
5803
5804   // fold (zext (zext x)) -> (zext x)
5805   // fold (zext (aext x)) -> (zext x)
5806   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5807     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5808                        N0.getOperand(0));
5809
5810   // fold (zext (truncate x)) -> (zext x) or
5811   //      (zext (truncate x)) -> (truncate x)
5812   // This is valid when the truncated bits of x are already zero.
5813   // FIXME: We should extend this to work for vectors too.
5814   SDValue Op;
5815   APInt KnownZero;
5816   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5817     APInt TruncatedBits =
5818       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5819       APInt(Op.getValueSizeInBits(), 0) :
5820       APInt::getBitsSet(Op.getValueSizeInBits(),
5821                         N0.getValueSizeInBits(),
5822                         std::min(Op.getValueSizeInBits(),
5823                                  VT.getSizeInBits()));
5824     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5825       if (VT.bitsGT(Op.getValueType()))
5826         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5827       if (VT.bitsLT(Op.getValueType()))
5828         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5829
5830       return Op;
5831     }
5832   }
5833
5834   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5835   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5836   if (N0.getOpcode() == ISD::TRUNCATE) {
5837     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5838     if (NarrowLoad.getNode()) {
5839       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5840       if (NarrowLoad.getNode() != N0.getNode()) {
5841         CombineTo(N0.getNode(), NarrowLoad);
5842         // CombineTo deleted the truncate, if needed, but not what's under it.
5843         AddToWorklist(oye);
5844       }
5845       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5846     }
5847   }
5848
5849   // fold (zext (truncate x)) -> (and x, mask)
5850   if (N0.getOpcode() == ISD::TRUNCATE &&
5851       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5852
5853     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5854     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5855     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5856     if (NarrowLoad.getNode()) {
5857       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5858       if (NarrowLoad.getNode() != N0.getNode()) {
5859         CombineTo(N0.getNode(), NarrowLoad);
5860         // CombineTo deleted the truncate, if needed, but not what's under it.
5861         AddToWorklist(oye);
5862       }
5863       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5864     }
5865
5866     SDValue Op = N0.getOperand(0);
5867     if (Op.getValueType().bitsLT(VT)) {
5868       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5869       AddToWorklist(Op.getNode());
5870     } else if (Op.getValueType().bitsGT(VT)) {
5871       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5872       AddToWorklist(Op.getNode());
5873     }
5874     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5875                                   N0.getValueType().getScalarType());
5876   }
5877
5878   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5879   // if either of the casts is not free.
5880   if (N0.getOpcode() == ISD::AND &&
5881       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5882       N0.getOperand(1).getOpcode() == ISD::Constant &&
5883       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5884                            N0.getValueType()) ||
5885        !TLI.isZExtFree(N0.getValueType(), VT))) {
5886     SDValue X = N0.getOperand(0).getOperand(0);
5887     if (X.getValueType().bitsLT(VT)) {
5888       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5889     } else if (X.getValueType().bitsGT(VT)) {
5890       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5891     }
5892     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5893     Mask = Mask.zext(VT.getSizeInBits());
5894     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5895                        X, DAG.getConstant(Mask, VT));
5896   }
5897
5898   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5899   // Only generate vector extloads when 1) they're legal, and 2) they are
5900   // deemed desirable by the target.
5901   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5902       ((!LegalOperations && !VT.isVector() &&
5903         !cast<LoadSDNode>(N0)->isVolatile()) ||
5904        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5905     bool DoXform = true;
5906     SmallVector<SDNode*, 4> SetCCs;
5907     if (!N0.hasOneUse())
5908       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5909     if (VT.isVector())
5910       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5911     if (DoXform) {
5912       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5913       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5914                                        LN0->getChain(),
5915                                        LN0->getBasePtr(), N0.getValueType(),
5916                                        LN0->getMemOperand());
5917       CombineTo(N, ExtLoad);
5918       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5919                                   N0.getValueType(), ExtLoad);
5920       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5921
5922       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5923                       ISD::ZERO_EXTEND);
5924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5925     }
5926   }
5927
5928   // fold (zext (load x)) to multiple smaller zextloads.
5929   // Only on illegal but splittable vectors.
5930   if (SDValue ExtLoad = CombineExtLoad(N))
5931     return ExtLoad;
5932
5933   // fold (zext (and/or/xor (load x), cst)) ->
5934   //      (and/or/xor (zextload x), (zext cst))
5935   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5936        N0.getOpcode() == ISD::XOR) &&
5937       isa<LoadSDNode>(N0.getOperand(0)) &&
5938       N0.getOperand(1).getOpcode() == ISD::Constant &&
5939       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5940       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5941     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5942     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5943       bool DoXform = true;
5944       SmallVector<SDNode*, 4> SetCCs;
5945       if (!N0.hasOneUse())
5946         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5947                                           SetCCs, TLI);
5948       if (DoXform) {
5949         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5950                                          LN0->getChain(), LN0->getBasePtr(),
5951                                          LN0->getMemoryVT(),
5952                                          LN0->getMemOperand());
5953         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5954         Mask = Mask.zext(VT.getSizeInBits());
5955         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5956                                   ExtLoad, DAG.getConstant(Mask, VT));
5957         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5958                                     SDLoc(N0.getOperand(0)),
5959                                     N0.getOperand(0).getValueType(), ExtLoad);
5960         CombineTo(N, And);
5961         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5962         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5963                         ISD::ZERO_EXTEND);
5964         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5965       }
5966     }
5967   }
5968
5969   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5970   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5971   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5972       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5973     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5974     EVT MemVT = LN0->getMemoryVT();
5975     if ((!LegalOperations && !LN0->isVolatile()) ||
5976         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5977       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5978                                        LN0->getChain(),
5979                                        LN0->getBasePtr(), MemVT,
5980                                        LN0->getMemOperand());
5981       CombineTo(N, ExtLoad);
5982       CombineTo(N0.getNode(),
5983                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5984                             ExtLoad),
5985                 ExtLoad.getValue(1));
5986       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5987     }
5988   }
5989
5990   if (N0.getOpcode() == ISD::SETCC) {
5991     if (!LegalOperations && VT.isVector() &&
5992         N0.getValueType().getVectorElementType() == MVT::i1) {
5993       EVT N0VT = N0.getOperand(0).getValueType();
5994       if (getSetCCResultType(N0VT) == N0.getValueType())
5995         return SDValue();
5996
5997       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5998       // Only do this before legalize for now.
5999       EVT EltVT = VT.getVectorElementType();
6000       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6001                                     DAG.getConstant(1, EltVT));
6002       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6003         // We know that the # elements of the results is the same as the
6004         // # elements of the compare (and the # elements of the compare result
6005         // for that matter).  Check to see that they are the same size.  If so,
6006         // we know that the element size of the sext'd result matches the
6007         // element size of the compare operands.
6008         return DAG.getNode(ISD::AND, SDLoc(N), VT,
6009                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6010                                          N0.getOperand(1),
6011                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6012                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6013                                        OneOps));
6014
6015       // If the desired elements are smaller or larger than the source
6016       // elements we can use a matching integer vector type and then
6017       // truncate/sign extend
6018       EVT MatchingElementType =
6019         EVT::getIntegerVT(*DAG.getContext(),
6020                           N0VT.getScalarType().getSizeInBits());
6021       EVT MatchingVectorType =
6022         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6023                          N0VT.getVectorNumElements());
6024       SDValue VsetCC =
6025         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6026                       N0.getOperand(1),
6027                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6028       return DAG.getNode(ISD::AND, SDLoc(N), VT,
6029                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6030                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6031     }
6032
6033     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6034     SDValue SCC =
6035       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6036                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6037                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6038     if (SCC.getNode()) return SCC;
6039   }
6040
6041   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6042   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6043       isa<ConstantSDNode>(N0.getOperand(1)) &&
6044       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6045       N0.hasOneUse()) {
6046     SDValue ShAmt = N0.getOperand(1);
6047     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6048     if (N0.getOpcode() == ISD::SHL) {
6049       SDValue InnerZExt = N0.getOperand(0);
6050       // If the original shl may be shifting out bits, do not perform this
6051       // transformation.
6052       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6053         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6054       if (ShAmtVal > KnownZeroBits)
6055         return SDValue();
6056     }
6057
6058     SDLoc DL(N);
6059
6060     // Ensure that the shift amount is wide enough for the shifted value.
6061     if (VT.getSizeInBits() >= 256)
6062       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6063
6064     return DAG.getNode(N0.getOpcode(), DL, VT,
6065                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6066                        ShAmt);
6067   }
6068
6069   return SDValue();
6070 }
6071
6072 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6073   SDValue N0 = N->getOperand(0);
6074   EVT VT = N->getValueType(0);
6075
6076   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6077                                               LegalOperations))
6078     return SDValue(Res, 0);
6079
6080   // fold (aext (aext x)) -> (aext x)
6081   // fold (aext (zext x)) -> (zext x)
6082   // fold (aext (sext x)) -> (sext x)
6083   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6084       N0.getOpcode() == ISD::ZERO_EXTEND ||
6085       N0.getOpcode() == ISD::SIGN_EXTEND)
6086     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6087
6088   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6089   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6090   if (N0.getOpcode() == ISD::TRUNCATE) {
6091     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6092     if (NarrowLoad.getNode()) {
6093       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094       if (NarrowLoad.getNode() != N0.getNode()) {
6095         CombineTo(N0.getNode(), NarrowLoad);
6096         // CombineTo deleted the truncate, if needed, but not what's under it.
6097         AddToWorklist(oye);
6098       }
6099       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6100     }
6101   }
6102
6103   // fold (aext (truncate x))
6104   if (N0.getOpcode() == ISD::TRUNCATE) {
6105     SDValue TruncOp = N0.getOperand(0);
6106     if (TruncOp.getValueType() == VT)
6107       return TruncOp; // x iff x size == zext size.
6108     if (TruncOp.getValueType().bitsGT(VT))
6109       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6110     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6111   }
6112
6113   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6114   // if the trunc is not free.
6115   if (N0.getOpcode() == ISD::AND &&
6116       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6117       N0.getOperand(1).getOpcode() == ISD::Constant &&
6118       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6119                           N0.getValueType())) {
6120     SDValue X = N0.getOperand(0).getOperand(0);
6121     if (X.getValueType().bitsLT(VT)) {
6122       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6123     } else if (X.getValueType().bitsGT(VT)) {
6124       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6125     }
6126     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6127     Mask = Mask.zext(VT.getSizeInBits());
6128     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6129                        X, DAG.getConstant(Mask, VT));
6130   }
6131
6132   // fold (aext (load x)) -> (aext (truncate (extload x)))
6133   // None of the supported targets knows how to perform load and any_ext
6134   // on vectors in one instruction.  We only perform this transformation on
6135   // scalars.
6136   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6137       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6138       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6139     bool DoXform = true;
6140     SmallVector<SDNode*, 4> SetCCs;
6141     if (!N0.hasOneUse())
6142       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6143     if (DoXform) {
6144       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6145       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6146                                        LN0->getChain(),
6147                                        LN0->getBasePtr(), N0.getValueType(),
6148                                        LN0->getMemOperand());
6149       CombineTo(N, ExtLoad);
6150       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6151                                   N0.getValueType(), ExtLoad);
6152       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6153       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6154                       ISD::ANY_EXTEND);
6155       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6156     }
6157   }
6158
6159   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6160   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6161   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6162   if (N0.getOpcode() == ISD::LOAD &&
6163       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6164       N0.hasOneUse()) {
6165     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6166     ISD::LoadExtType ExtType = LN0->getExtensionType();
6167     EVT MemVT = LN0->getMemoryVT();
6168     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6169       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6170                                        VT, LN0->getChain(), LN0->getBasePtr(),
6171                                        MemVT, LN0->getMemOperand());
6172       CombineTo(N, ExtLoad);
6173       CombineTo(N0.getNode(),
6174                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6175                             N0.getValueType(), ExtLoad),
6176                 ExtLoad.getValue(1));
6177       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6178     }
6179   }
6180
6181   if (N0.getOpcode() == ISD::SETCC) {
6182     // For vectors:
6183     // aext(setcc) -> vsetcc
6184     // aext(setcc) -> truncate(vsetcc)
6185     // aext(setcc) -> aext(vsetcc)
6186     // Only do this before legalize for now.
6187     if (VT.isVector() && !LegalOperations) {
6188       EVT N0VT = N0.getOperand(0).getValueType();
6189         // We know that the # elements of the results is the same as the
6190         // # elements of the compare (and the # elements of the compare result
6191         // for that matter).  Check to see that they are the same size.  If so,
6192         // we know that the element size of the sext'd result matches the
6193         // element size of the compare operands.
6194       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6195         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6196                              N0.getOperand(1),
6197                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6198       // If the desired elements are smaller or larger than the source
6199       // elements we can use a matching integer vector type and then
6200       // truncate/any extend
6201       else {
6202         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6203         SDValue VsetCC =
6204           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6205                         N0.getOperand(1),
6206                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6207         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6208       }
6209     }
6210
6211     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6212     SDValue SCC =
6213       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6214                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6215                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6216     if (SCC.getNode())
6217       return SCC;
6218   }
6219
6220   return SDValue();
6221 }
6222
6223 /// See if the specified operand can be simplified with the knowledge that only
6224 /// the bits specified by Mask are used.  If so, return the simpler operand,
6225 /// otherwise return a null SDValue.
6226 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6227   switch (V.getOpcode()) {
6228   default: break;
6229   case ISD::Constant: {
6230     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6231     assert(CV && "Const value should be ConstSDNode.");
6232     const APInt &CVal = CV->getAPIntValue();
6233     APInt NewVal = CVal & Mask;
6234     if (NewVal != CVal)
6235       return DAG.getConstant(NewVal, V.getValueType());
6236     break;
6237   }
6238   case ISD::OR:
6239   case ISD::XOR:
6240     // If the LHS or RHS don't contribute bits to the or, drop them.
6241     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6242       return V.getOperand(1);
6243     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6244       return V.getOperand(0);
6245     break;
6246   case ISD::SRL:
6247     // Only look at single-use SRLs.
6248     if (!V.getNode()->hasOneUse())
6249       break;
6250     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6251       // See if we can recursively simplify the LHS.
6252       unsigned Amt = RHSC->getZExtValue();
6253
6254       // Watch out for shift count overflow though.
6255       if (Amt >= Mask.getBitWidth()) break;
6256       APInt NewMask = Mask << Amt;
6257       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6258       if (SimplifyLHS.getNode())
6259         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6260                            SimplifyLHS, V.getOperand(1));
6261     }
6262   }
6263   return SDValue();
6264 }
6265
6266 /// If the result of a wider load is shifted to right of N  bits and then
6267 /// truncated to a narrower type and where N is a multiple of number of bits of
6268 /// the narrower type, transform it to a narrower load from address + N / num of
6269 /// bits of new type. If the result is to be extended, also fold the extension
6270 /// to form a extending load.
6271 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6272   unsigned Opc = N->getOpcode();
6273
6274   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6275   SDValue N0 = N->getOperand(0);
6276   EVT VT = N->getValueType(0);
6277   EVT ExtVT = VT;
6278
6279   // This transformation isn't valid for vector loads.
6280   if (VT.isVector())
6281     return SDValue();
6282
6283   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6284   // extended to VT.
6285   if (Opc == ISD::SIGN_EXTEND_INREG) {
6286     ExtType = ISD::SEXTLOAD;
6287     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6288   } else if (Opc == ISD::SRL) {
6289     // Another special-case: SRL is basically zero-extending a narrower value.
6290     ExtType = ISD::ZEXTLOAD;
6291     N0 = SDValue(N, 0);
6292     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6293     if (!N01) return SDValue();
6294     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6295                               VT.getSizeInBits() - N01->getZExtValue());
6296   }
6297   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6298     return SDValue();
6299
6300   unsigned EVTBits = ExtVT.getSizeInBits();
6301
6302   // Do not generate loads of non-round integer types since these can
6303   // be expensive (and would be wrong if the type is not byte sized).
6304   if (!ExtVT.isRound())
6305     return SDValue();
6306
6307   unsigned ShAmt = 0;
6308   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6309     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6310       ShAmt = N01->getZExtValue();
6311       // Is the shift amount a multiple of size of VT?
6312       if ((ShAmt & (EVTBits-1)) == 0) {
6313         N0 = N0.getOperand(0);
6314         // Is the load width a multiple of size of VT?
6315         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6316           return SDValue();
6317       }
6318
6319       // At this point, we must have a load or else we can't do the transform.
6320       if (!isa<LoadSDNode>(N0)) return SDValue();
6321
6322       // Because a SRL must be assumed to *need* to zero-extend the high bits
6323       // (as opposed to anyext the high bits), we can't combine the zextload
6324       // lowering of SRL and an sextload.
6325       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6326         return SDValue();
6327
6328       // If the shift amount is larger than the input type then we're not
6329       // accessing any of the loaded bytes.  If the load was a zextload/extload
6330       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6331       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6332         return SDValue();
6333     }
6334   }
6335
6336   // If the load is shifted left (and the result isn't shifted back right),
6337   // we can fold the truncate through the shift.
6338   unsigned ShLeftAmt = 0;
6339   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6340       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6341     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6342       ShLeftAmt = N01->getZExtValue();
6343       N0 = N0.getOperand(0);
6344     }
6345   }
6346
6347   // If we haven't found a load, we can't narrow it.  Don't transform one with
6348   // multiple uses, this would require adding a new load.
6349   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6350     return SDValue();
6351
6352   // Don't change the width of a volatile load.
6353   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6354   if (LN0->isVolatile())
6355     return SDValue();
6356
6357   // Verify that we are actually reducing a load width here.
6358   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6359     return SDValue();
6360
6361   // For the transform to be legal, the load must produce only two values
6362   // (the value loaded and the chain).  Don't transform a pre-increment
6363   // load, for example, which produces an extra value.  Otherwise the
6364   // transformation is not equivalent, and the downstream logic to replace
6365   // uses gets things wrong.
6366   if (LN0->getNumValues() > 2)
6367     return SDValue();
6368
6369   // If the load that we're shrinking is an extload and we're not just
6370   // discarding the extension we can't simply shrink the load. Bail.
6371   // TODO: It would be possible to merge the extensions in some cases.
6372   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6373       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6374     return SDValue();
6375
6376   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6377     return SDValue();
6378
6379   EVT PtrType = N0.getOperand(1).getValueType();
6380
6381   if (PtrType == MVT::Untyped || PtrType.isExtended())
6382     // It's not possible to generate a constant of extended or untyped type.
6383     return SDValue();
6384
6385   // For big endian targets, we need to adjust the offset to the pointer to
6386   // load the correct bytes.
6387   if (TLI.isBigEndian()) {
6388     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6389     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6390     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6391   }
6392
6393   uint64_t PtrOff = ShAmt / 8;
6394   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6395   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6396                                PtrType, LN0->getBasePtr(),
6397                                DAG.getConstant(PtrOff, PtrType));
6398   AddToWorklist(NewPtr.getNode());
6399
6400   SDValue Load;
6401   if (ExtType == ISD::NON_EXTLOAD)
6402     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6403                         LN0->getPointerInfo().getWithOffset(PtrOff),
6404                         LN0->isVolatile(), LN0->isNonTemporal(),
6405                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6406   else
6407     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6408                           LN0->getPointerInfo().getWithOffset(PtrOff),
6409                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6410                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6411
6412   // Replace the old load's chain with the new load's chain.
6413   WorklistRemover DeadNodes(*this);
6414   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6415
6416   // Shift the result left, if we've swallowed a left shift.
6417   SDValue Result = Load;
6418   if (ShLeftAmt != 0) {
6419     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6420     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6421       ShImmTy = VT;
6422     // If the shift amount is as large as the result size (but, presumably,
6423     // no larger than the source) then the useful bits of the result are
6424     // zero; we can't simply return the shortened shift, because the result
6425     // of that operation is undefined.
6426     if (ShLeftAmt >= VT.getSizeInBits())
6427       Result = DAG.getConstant(0, VT);
6428     else
6429       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6430                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6431   }
6432
6433   // Return the new loaded value.
6434   return Result;
6435 }
6436
6437 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6438   SDValue N0 = N->getOperand(0);
6439   SDValue N1 = N->getOperand(1);
6440   EVT VT = N->getValueType(0);
6441   EVT EVT = cast<VTSDNode>(N1)->getVT();
6442   unsigned VTBits = VT.getScalarType().getSizeInBits();
6443   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6444
6445   // fold (sext_in_reg c1) -> c1
6446   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6447     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6448
6449   // If the input is already sign extended, just drop the extension.
6450   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6451     return N0;
6452
6453   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6454   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6455       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6456     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6457                        N0.getOperand(0), N1);
6458
6459   // fold (sext_in_reg (sext x)) -> (sext x)
6460   // fold (sext_in_reg (aext x)) -> (sext x)
6461   // if x is small enough.
6462   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6463     SDValue N00 = N0.getOperand(0);
6464     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6465         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6466       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6467   }
6468
6469   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6470   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6471     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6472
6473   // fold operands of sext_in_reg based on knowledge that the top bits are not
6474   // demanded.
6475   if (SimplifyDemandedBits(SDValue(N, 0)))
6476     return SDValue(N, 0);
6477
6478   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6479   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6480   SDValue NarrowLoad = ReduceLoadWidth(N);
6481   if (NarrowLoad.getNode())
6482     return NarrowLoad;
6483
6484   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6485   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6486   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6487   if (N0.getOpcode() == ISD::SRL) {
6488     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6489       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6490         // We can turn this into an SRA iff the input to the SRL is already sign
6491         // extended enough.
6492         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6493         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6494           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6495                              N0.getOperand(0), N0.getOperand(1));
6496       }
6497   }
6498
6499   // fold (sext_inreg (extload x)) -> (sextload x)
6500   if (ISD::isEXTLoad(N0.getNode()) &&
6501       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6502       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6503       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6504        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6505     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6506     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6507                                      LN0->getChain(),
6508                                      LN0->getBasePtr(), EVT,
6509                                      LN0->getMemOperand());
6510     CombineTo(N, ExtLoad);
6511     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6512     AddToWorklist(ExtLoad.getNode());
6513     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6514   }
6515   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6516   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6517       N0.hasOneUse() &&
6518       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6519       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6520        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6521     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6522     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6523                                      LN0->getChain(),
6524                                      LN0->getBasePtr(), EVT,
6525                                      LN0->getMemOperand());
6526     CombineTo(N, ExtLoad);
6527     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6528     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6529   }
6530
6531   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6532   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6533     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6534                                        N0.getOperand(1), false);
6535     if (BSwap.getNode())
6536       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6537                          BSwap, N1);
6538   }
6539
6540   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6541   // into a build_vector.
6542   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6543     SmallVector<SDValue, 8> Elts;
6544     unsigned NumElts = N0->getNumOperands();
6545     unsigned ShAmt = VTBits - EVTBits;
6546
6547     for (unsigned i = 0; i != NumElts; ++i) {
6548       SDValue Op = N0->getOperand(i);
6549       if (Op->getOpcode() == ISD::UNDEF) {
6550         Elts.push_back(Op);
6551         continue;
6552       }
6553
6554       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6555       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6556       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6557                                      Op.getValueType()));
6558     }
6559
6560     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6561   }
6562
6563   return SDValue();
6564 }
6565
6566 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6567   SDValue N0 = N->getOperand(0);
6568   EVT VT = N->getValueType(0);
6569   bool isLE = TLI.isLittleEndian();
6570
6571   // noop truncate
6572   if (N0.getValueType() == N->getValueType(0))
6573     return N0;
6574   // fold (truncate c1) -> c1
6575   if (isConstantIntBuildVectorOrConstantInt(N0))
6576     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6577   // fold (truncate (truncate x)) -> (truncate x)
6578   if (N0.getOpcode() == ISD::TRUNCATE)
6579     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6580   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6581   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6582       N0.getOpcode() == ISD::SIGN_EXTEND ||
6583       N0.getOpcode() == ISD::ANY_EXTEND) {
6584     if (N0.getOperand(0).getValueType().bitsLT(VT))
6585       // if the source is smaller than the dest, we still need an extend
6586       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6587                          N0.getOperand(0));
6588     if (N0.getOperand(0).getValueType().bitsGT(VT))
6589       // if the source is larger than the dest, than we just need the truncate
6590       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6591     // if the source and dest are the same type, we can drop both the extend
6592     // and the truncate.
6593     return N0.getOperand(0);
6594   }
6595
6596   // Fold extract-and-trunc into a narrow extract. For example:
6597   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6598   //   i32 y = TRUNCATE(i64 x)
6599   //        -- becomes --
6600   //   v16i8 b = BITCAST (v2i64 val)
6601   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6602   //
6603   // Note: We only run this optimization after type legalization (which often
6604   // creates this pattern) and before operation legalization after which
6605   // we need to be more careful about the vector instructions that we generate.
6606   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6607       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6608
6609     EVT VecTy = N0.getOperand(0).getValueType();
6610     EVT ExTy = N0.getValueType();
6611     EVT TrTy = N->getValueType(0);
6612
6613     unsigned NumElem = VecTy.getVectorNumElements();
6614     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6615
6616     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6617     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6618
6619     SDValue EltNo = N0->getOperand(1);
6620     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6621       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6622       EVT IndexTy = TLI.getVectorIdxTy();
6623       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6624
6625       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6626                               NVT, N0.getOperand(0));
6627
6628       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6629                          SDLoc(N), TrTy, V,
6630                          DAG.getConstant(Index, IndexTy));
6631     }
6632   }
6633
6634   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6635   if (N0.getOpcode() == ISD::SELECT) {
6636     EVT SrcVT = N0.getValueType();
6637     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6638         TLI.isTruncateFree(SrcVT, VT)) {
6639       SDLoc SL(N0);
6640       SDValue Cond = N0.getOperand(0);
6641       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6642       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6643       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6644     }
6645   }
6646
6647   // Fold a series of buildvector, bitcast, and truncate if possible.
6648   // For example fold
6649   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6650   //   (2xi32 (buildvector x, y)).
6651   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6652       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6653       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6654       N0.getOperand(0).hasOneUse()) {
6655
6656     SDValue BuildVect = N0.getOperand(0);
6657     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6658     EVT TruncVecEltTy = VT.getVectorElementType();
6659
6660     // Check that the element types match.
6661     if (BuildVectEltTy == TruncVecEltTy) {
6662       // Now we only need to compute the offset of the truncated elements.
6663       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6664       unsigned TruncVecNumElts = VT.getVectorNumElements();
6665       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6666
6667       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6668              "Invalid number of elements");
6669
6670       SmallVector<SDValue, 8> Opnds;
6671       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6672         Opnds.push_back(BuildVect.getOperand(i));
6673
6674       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6675     }
6676   }
6677
6678   // See if we can simplify the input to this truncate through knowledge that
6679   // only the low bits are being used.
6680   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6681   // Currently we only perform this optimization on scalars because vectors
6682   // may have different active low bits.
6683   if (!VT.isVector()) {
6684     SDValue Shorter =
6685       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6686                                                VT.getSizeInBits()));
6687     if (Shorter.getNode())
6688       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6689   }
6690   // fold (truncate (load x)) -> (smaller load x)
6691   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6692   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6693     SDValue Reduced = ReduceLoadWidth(N);
6694     if (Reduced.getNode())
6695       return Reduced;
6696     // Handle the case where the load remains an extending load even
6697     // after truncation.
6698     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6699       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6700       if (!LN0->isVolatile() &&
6701           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6702         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6703                                          VT, LN0->getChain(), LN0->getBasePtr(),
6704                                          LN0->getMemoryVT(),
6705                                          LN0->getMemOperand());
6706         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6707         return NewLoad;
6708       }
6709     }
6710   }
6711   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6712   // where ... are all 'undef'.
6713   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6714     SmallVector<EVT, 8> VTs;
6715     SDValue V;
6716     unsigned Idx = 0;
6717     unsigned NumDefs = 0;
6718
6719     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6720       SDValue X = N0.getOperand(i);
6721       if (X.getOpcode() != ISD::UNDEF) {
6722         V = X;
6723         Idx = i;
6724         NumDefs++;
6725       }
6726       // Stop if more than one members are non-undef.
6727       if (NumDefs > 1)
6728         break;
6729       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6730                                      VT.getVectorElementType(),
6731                                      X.getValueType().getVectorNumElements()));
6732     }
6733
6734     if (NumDefs == 0)
6735       return DAG.getUNDEF(VT);
6736
6737     if (NumDefs == 1) {
6738       assert(V.getNode() && "The single defined operand is empty!");
6739       SmallVector<SDValue, 8> Opnds;
6740       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6741         if (i != Idx) {
6742           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6743           continue;
6744         }
6745         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6746         AddToWorklist(NV.getNode());
6747         Opnds.push_back(NV);
6748       }
6749       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6750     }
6751   }
6752
6753   // Simplify the operands using demanded-bits information.
6754   if (!VT.isVector() &&
6755       SimplifyDemandedBits(SDValue(N, 0)))
6756     return SDValue(N, 0);
6757
6758   return SDValue();
6759 }
6760
6761 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6762   SDValue Elt = N->getOperand(i);
6763   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6764     return Elt.getNode();
6765   return Elt.getOperand(Elt.getResNo()).getNode();
6766 }
6767
6768 /// build_pair (load, load) -> load
6769 /// if load locations are consecutive.
6770 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6771   assert(N->getOpcode() == ISD::BUILD_PAIR);
6772
6773   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6774   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6775   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6776       LD1->getAddressSpace() != LD2->getAddressSpace())
6777     return SDValue();
6778   EVT LD1VT = LD1->getValueType(0);
6779
6780   if (ISD::isNON_EXTLoad(LD2) &&
6781       LD2->hasOneUse() &&
6782       // If both are volatile this would reduce the number of volatile loads.
6783       // If one is volatile it might be ok, but play conservative and bail out.
6784       !LD1->isVolatile() &&
6785       !LD2->isVolatile() &&
6786       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6787     unsigned Align = LD1->getAlignment();
6788     unsigned NewAlign = TLI.getDataLayout()->
6789       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6790
6791     if (NewAlign <= Align &&
6792         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6793       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6794                          LD1->getBasePtr(), LD1->getPointerInfo(),
6795                          false, false, false, Align);
6796   }
6797
6798   return SDValue();
6799 }
6800
6801 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6802   SDValue N0 = N->getOperand(0);
6803   EVT VT = N->getValueType(0);
6804
6805   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6806   // Only do this before legalize, since afterward the target may be depending
6807   // on the bitconvert.
6808   // First check to see if this is all constant.
6809   if (!LegalTypes &&
6810       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6811       VT.isVector()) {
6812     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6813
6814     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6815     assert(!DestEltVT.isVector() &&
6816            "Element type of vector ValueType must not be vector!");
6817     if (isSimple)
6818       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6819   }
6820
6821   // If the input is a constant, let getNode fold it.
6822   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6823     // If we can't allow illegal operations, we need to check that this is just
6824     // a fp -> int or int -> conversion and that the resulting operation will
6825     // be legal.
6826     if (!LegalOperations ||
6827         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6828          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6829         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6830          TLI.isOperationLegal(ISD::Constant, VT)))
6831       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6832   }
6833
6834   // (conv (conv x, t1), t2) -> (conv x, t2)
6835   if (N0.getOpcode() == ISD::BITCAST)
6836     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6837                        N0.getOperand(0));
6838
6839   // fold (conv (load x)) -> (load (conv*)x)
6840   // If the resultant load doesn't need a higher alignment than the original!
6841   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6842       // Do not change the width of a volatile load.
6843       !cast<LoadSDNode>(N0)->isVolatile() &&
6844       // Do not remove the cast if the types differ in endian layout.
6845       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6846       TLI.hasBigEndianPartOrdering(VT) &&
6847       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6848       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6849     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6850     unsigned Align = TLI.getDataLayout()->
6851       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6852     unsigned OrigAlign = LN0->getAlignment();
6853
6854     if (Align <= OrigAlign) {
6855       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6856                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6857                                  LN0->isVolatile(), LN0->isNonTemporal(),
6858                                  LN0->isInvariant(), OrigAlign,
6859                                  LN0->getAAInfo());
6860       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6861       return Load;
6862     }
6863   }
6864
6865   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6866   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6867   // This often reduces constant pool loads.
6868   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6869        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6870       N0.getNode()->hasOneUse() && VT.isInteger() &&
6871       !VT.isVector() && !N0.getValueType().isVector()) {
6872     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6873                                   N0.getOperand(0));
6874     AddToWorklist(NewConv.getNode());
6875
6876     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6877     if (N0.getOpcode() == ISD::FNEG)
6878       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6879                          NewConv, DAG.getConstant(SignBit, VT));
6880     assert(N0.getOpcode() == ISD::FABS);
6881     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6882                        NewConv, DAG.getConstant(~SignBit, VT));
6883   }
6884
6885   // fold (bitconvert (fcopysign cst, x)) ->
6886   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6887   // Note that we don't handle (copysign x, cst) because this can always be
6888   // folded to an fneg or fabs.
6889   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6890       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6891       VT.isInteger() && !VT.isVector()) {
6892     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6893     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6894     if (isTypeLegal(IntXVT)) {
6895       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6896                               IntXVT, N0.getOperand(1));
6897       AddToWorklist(X.getNode());
6898
6899       // If X has a different width than the result/lhs, sext it or truncate it.
6900       unsigned VTWidth = VT.getSizeInBits();
6901       if (OrigXWidth < VTWidth) {
6902         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6903         AddToWorklist(X.getNode());
6904       } else if (OrigXWidth > VTWidth) {
6905         // To get the sign bit in the right place, we have to shift it right
6906         // before truncating.
6907         X = DAG.getNode(ISD::SRL, SDLoc(X),
6908                         X.getValueType(), X,
6909                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6910         AddToWorklist(X.getNode());
6911         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6912         AddToWorklist(X.getNode());
6913       }
6914
6915       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6916       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6917                       X, DAG.getConstant(SignBit, VT));
6918       AddToWorklist(X.getNode());
6919
6920       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6921                                 VT, N0.getOperand(0));
6922       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6923                         Cst, DAG.getConstant(~SignBit, VT));
6924       AddToWorklist(Cst.getNode());
6925
6926       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6927     }
6928   }
6929
6930   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6931   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6932     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6933     if (CombineLD.getNode())
6934       return CombineLD;
6935   }
6936
6937   // Remove double bitcasts from shuffles - this is often a legacy of
6938   // XformToShuffleWithZero being used to combine bitmaskings (of
6939   // float vectors bitcast to integer vectors) into shuffles.
6940   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
6941   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
6942       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
6943       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
6944       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
6945     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
6946
6947     // If operands are a bitcast, peek through if it casts the original VT.
6948     // If operands are a UNDEF or constant, just bitcast back to original VT.
6949     auto PeekThroughBitcast = [&](SDValue Op) {
6950       if (Op.getOpcode() == ISD::BITCAST &&
6951           Op.getOperand(0)->getValueType(0) == VT)
6952         return SDValue(Op.getOperand(0));
6953       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
6954           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
6955         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
6956       return SDValue();
6957     };
6958
6959     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
6960     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
6961     if (!(SV0 && SV1))
6962       return SDValue();
6963
6964     int MaskScale =
6965         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
6966     SmallVector<int, 8> NewMask;
6967     for (int M : SVN->getMask())
6968       for (int i = 0; i != MaskScale; ++i)
6969         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
6970
6971     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
6972     if (!LegalMask) {
6973       std::swap(SV0, SV1);
6974       ShuffleVectorSDNode::commuteMask(NewMask);
6975       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
6976     }
6977
6978     if (LegalMask)
6979       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
6980   }
6981
6982   return SDValue();
6983 }
6984
6985 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6986   EVT VT = N->getValueType(0);
6987   return CombineConsecutiveLoads(N, VT);
6988 }
6989
6990 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6991 /// operands. DstEltVT indicates the destination element value type.
6992 SDValue DAGCombiner::
6993 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6994   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6995
6996   // If this is already the right type, we're done.
6997   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6998
6999   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7000   unsigned DstBitSize = DstEltVT.getSizeInBits();
7001
7002   // If this is a conversion of N elements of one type to N elements of another
7003   // type, convert each element.  This handles FP<->INT cases.
7004   if (SrcBitSize == DstBitSize) {
7005     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7006                               BV->getValueType(0).getVectorNumElements());
7007
7008     // Due to the FP element handling below calling this routine recursively,
7009     // we can end up with a scalar-to-vector node here.
7010     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7011       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7012                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7013                                      DstEltVT, BV->getOperand(0)));
7014
7015     SmallVector<SDValue, 8> Ops;
7016     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7017       SDValue Op = BV->getOperand(i);
7018       // If the vector element type is not legal, the BUILD_VECTOR operands
7019       // are promoted and implicitly truncated.  Make that explicit here.
7020       if (Op.getValueType() != SrcEltVT)
7021         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7022       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7023                                 DstEltVT, Op));
7024       AddToWorklist(Ops.back().getNode());
7025     }
7026     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7027   }
7028
7029   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7030   // handle annoying details of growing/shrinking FP values, we convert them to
7031   // int first.
7032   if (SrcEltVT.isFloatingPoint()) {
7033     // Convert the input float vector to a int vector where the elements are the
7034     // same sizes.
7035     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7036     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7037     SrcEltVT = IntVT;
7038   }
7039
7040   // Now we know the input is an integer vector.  If the output is a FP type,
7041   // convert to integer first, then to FP of the right size.
7042   if (DstEltVT.isFloatingPoint()) {
7043     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7044     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7045
7046     // Next, convert to FP elements of the same size.
7047     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7048   }
7049
7050   // Okay, we know the src/dst types are both integers of differing types.
7051   // Handling growing first.
7052   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7053   if (SrcBitSize < DstBitSize) {
7054     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7055
7056     SmallVector<SDValue, 8> Ops;
7057     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7058          i += NumInputsPerOutput) {
7059       bool isLE = TLI.isLittleEndian();
7060       APInt NewBits = APInt(DstBitSize, 0);
7061       bool EltIsUndef = true;
7062       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7063         // Shift the previously computed bits over.
7064         NewBits <<= SrcBitSize;
7065         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7066         if (Op.getOpcode() == ISD::UNDEF) continue;
7067         EltIsUndef = false;
7068
7069         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7070                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7071       }
7072
7073       if (EltIsUndef)
7074         Ops.push_back(DAG.getUNDEF(DstEltVT));
7075       else
7076         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7077     }
7078
7079     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7080     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7081   }
7082
7083   // Finally, this must be the case where we are shrinking elements: each input
7084   // turns into multiple outputs.
7085   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7086   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7087                             NumOutputsPerInput*BV->getNumOperands());
7088   SmallVector<SDValue, 8> Ops;
7089
7090   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7091     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7092       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7093       continue;
7094     }
7095
7096     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7097                   getAPIntValue().zextOrTrunc(SrcBitSize);
7098
7099     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7100       APInt ThisVal = OpVal.trunc(DstBitSize);
7101       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7102       OpVal = OpVal.lshr(DstBitSize);
7103     }
7104
7105     // For big endian targets, swap the order of the pieces of each element.
7106     if (TLI.isBigEndian())
7107       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7108   }
7109
7110   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7111 }
7112
7113 /// Try to perform FMA combining on a given FADD node.
7114 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7115
7116
7117
7118
7119   SDValue N0 = N->getOperand(0);
7120   SDValue N1 = N->getOperand(1);
7121   EVT VT = N->getValueType(0);
7122   SDLoc SL(N);
7123
7124   const TargetOptions &Options = DAG.getTarget().Options;
7125   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7126                        Options.UnsafeFPMath);
7127
7128   // Floating-point multiply-add with intermediate rounding.
7129   bool HasFMAD = (LegalOperations &&
7130                   TLI.isOperationLegal(ISD::FMAD, VT));
7131
7132   // Floating-point multiply-add without intermediate rounding.
7133   bool HasFMA = ((!LegalOperations ||
7134                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7135                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7136                  UnsafeFPMath);
7137
7138   // No valid opcode, do not combine.
7139   if (!HasFMAD && !HasFMA)
7140     return SDValue();
7141
7142   // Always prefer FMAD to FMA for precision.
7143   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7144   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7145   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7146
7147   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7148   if (N0.getOpcode() == ISD::FMUL &&
7149       (Aggressive || N0->hasOneUse())) {
7150     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7151                        N0.getOperand(0), N0.getOperand(1), N1);
7152   }
7153
7154   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7155   // Note: Commutes FADD operands.
7156   if (N1.getOpcode() == ISD::FMUL &&
7157       (Aggressive || N1->hasOneUse())) {
7158     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7159                        N1.getOperand(0), N1.getOperand(1), N0);
7160   }
7161
7162   // Look through FP_EXTEND nodes to do more combining.
7163   if (UnsafeFPMath && LookThroughFPExt) {
7164     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7165     if (N0.getOpcode() == ISD::FP_EXTEND) {
7166       SDValue N00 = N0.getOperand(0);
7167       if (N00.getOpcode() == ISD::FMUL)
7168         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7169                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7170                                        N00.getOperand(0)),
7171                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7172                                        N00.getOperand(1)), N1);
7173     }
7174
7175     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7176     // Note: Commutes FADD operands.
7177     if (N1.getOpcode() == ISD::FP_EXTEND) {
7178       SDValue N10 = N1.getOperand(0);
7179       if (N10.getOpcode() == ISD::FMUL)
7180         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7181                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7182                                        N10.getOperand(0)),
7183                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7184                                        N10.getOperand(1)), N0);
7185     }
7186   }
7187
7188   // More folding opportunities when target permits.
7189   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7190     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7191     if (N0.getOpcode() == PreferredFusedOpcode &&
7192         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7193       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7194                          N0.getOperand(0), N0.getOperand(1),
7195                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7196                                      N0.getOperand(2).getOperand(0),
7197                                      N0.getOperand(2).getOperand(1),
7198                                      N1));
7199     }
7200
7201     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7202     if (N1->getOpcode() == PreferredFusedOpcode &&
7203         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7204       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7205                          N1.getOperand(0), N1.getOperand(1),
7206                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7207                                      N1.getOperand(2).getOperand(0),
7208                                      N1.getOperand(2).getOperand(1),
7209                                      N0));
7210     }
7211
7212     if (UnsafeFPMath && LookThroughFPExt) {
7213       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7214       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7215       auto FoldFAddFMAFPExtFMul = [&] (
7216           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7217         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7218                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7219                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7220                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7221                                        Z));
7222       };
7223       if (N0.getOpcode() == PreferredFusedOpcode) {
7224         SDValue N02 = N0.getOperand(2);
7225         if (N02.getOpcode() == ISD::FP_EXTEND) {
7226           SDValue N020 = N02.getOperand(0);
7227           if (N020.getOpcode() == ISD::FMUL)
7228             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7229                                         N020.getOperand(0), N020.getOperand(1),
7230                                         N1);
7231         }
7232       }
7233
7234       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7235       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7236       // FIXME: This turns two single-precision and one double-precision
7237       // operation into two double-precision operations, which might not be
7238       // interesting for all targets, especially GPUs.
7239       auto FoldFAddFPExtFMAFMul = [&] (
7240           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7241         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7242                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7243                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7244                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7245                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7246                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7247                                        Z));
7248       };
7249       if (N0.getOpcode() == ISD::FP_EXTEND) {
7250         SDValue N00 = N0.getOperand(0);
7251         if (N00.getOpcode() == PreferredFusedOpcode) {
7252           SDValue N002 = N00.getOperand(2);
7253           if (N002.getOpcode() == ISD::FMUL)
7254             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7255                                         N002.getOperand(0), N002.getOperand(1),
7256                                         N1);
7257         }
7258       }
7259
7260       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7261       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7262       if (N1.getOpcode() == PreferredFusedOpcode) {
7263         SDValue N12 = N1.getOperand(2);
7264         if (N12.getOpcode() == ISD::FP_EXTEND) {
7265           SDValue N120 = N12.getOperand(0);
7266           if (N120.getOpcode() == ISD::FMUL)
7267             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7268                                         N120.getOperand(0), N120.getOperand(1),
7269                                         N0);
7270         }
7271       }
7272
7273       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7274       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7275       // FIXME: This turns two single-precision and one double-precision
7276       // operation into two double-precision operations, which might not be
7277       // interesting for all targets, especially GPUs.
7278       if (N1.getOpcode() == ISD::FP_EXTEND) {
7279         SDValue N10 = N1.getOperand(0);
7280         if (N10.getOpcode() == PreferredFusedOpcode) {
7281           SDValue N102 = N10.getOperand(2);
7282           if (N102.getOpcode() == ISD::FMUL)
7283             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7284                                         N102.getOperand(0), N102.getOperand(1),
7285                                         N0);
7286         }
7287       }
7288     }
7289   }
7290
7291   return SDValue();
7292 }
7293
7294 /// Try to perform FMA combining on a given FSUB node.
7295 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7296
7297
7298
7299   SDValue N0 = N->getOperand(0);
7300   SDValue N1 = N->getOperand(1);
7301   EVT VT = N->getValueType(0);
7302
7303   SDLoc SL(N);
7304
7305   const TargetOptions &Options = DAG.getTarget().Options;
7306   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7307                        Options.UnsafeFPMath);
7308
7309   // Floating-point multiply-add with intermediate rounding.
7310   bool HasFMAD = (LegalOperations &&
7311                   TLI.isOperationLegal(ISD::FMAD, VT));
7312
7313   // Floating-point multiply-add without intermediate rounding.
7314   bool HasFMA = ((!LegalOperations ||
7315                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7316                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7317                  UnsafeFPMath);
7318
7319   // No valid opcode, do not combine.
7320   if (!HasFMAD && !HasFMA)
7321     return SDValue();
7322
7323   // Always prefer FMAD to FMA for precision.
7324   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7325   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7326   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7327
7328   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7329   if (N0.getOpcode() == ISD::FMUL &&
7330       (Aggressive || N0->hasOneUse())) {
7331     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7332                        N0.getOperand(0), N0.getOperand(1),
7333                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7334   }
7335
7336   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7337   // Note: Commutes FSUB operands.
7338   if (N1.getOpcode() == ISD::FMUL &&
7339       (Aggressive || N1->hasOneUse()))
7340     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7341                        DAG.getNode(ISD::FNEG, SL, VT,
7342                                    N1.getOperand(0)),
7343                        N1.getOperand(1), N0);
7344
7345   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7346   if (N0.getOpcode() == ISD::FNEG &&
7347       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7348       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7349     SDValue N00 = N0.getOperand(0).getOperand(0);
7350     SDValue N01 = N0.getOperand(0).getOperand(1);
7351     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7352                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7353                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7354   }
7355
7356   // Look through FP_EXTEND nodes to do more combining.
7357   if (UnsafeFPMath && LookThroughFPExt) {
7358     // fold (fsub (fpext (fmul x, y)), z)
7359     //   -> (fma (fpext x), (fpext y), (fneg z))
7360     if (N0.getOpcode() == ISD::FP_EXTEND) {
7361       SDValue N00 = N0.getOperand(0);
7362       if (N00.getOpcode() == ISD::FMUL)
7363         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7364                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7365                                        N00.getOperand(0)),
7366                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7367                                        N00.getOperand(1)),
7368                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7369     }
7370
7371     // fold (fsub x, (fpext (fmul y, z)))
7372     //   -> (fma (fneg (fpext y)), (fpext z), x)
7373     // Note: Commutes FSUB operands.
7374     if (N1.getOpcode() == ISD::FP_EXTEND) {
7375       SDValue N10 = N1.getOperand(0);
7376       if (N10.getOpcode() == ISD::FMUL)
7377         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7378                            DAG.getNode(ISD::FNEG, SL, VT,
7379                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7380                                                    N10.getOperand(0))),
7381                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7382                                        N10.getOperand(1)),
7383                            N0);
7384     }
7385
7386     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7387     //   -> (fneg (fma (fpext x), (fpext y), z))
7388     // Note: This could be removed with appropriate canonicalization of the
7389     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7390     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7391     // from implementing the canonicalization in visitFSUB.
7392     if (N0.getOpcode() == ISD::FP_EXTEND) {
7393       SDValue N00 = N0.getOperand(0);
7394       if (N00.getOpcode() == ISD::FNEG) {
7395         SDValue N000 = N00.getOperand(0);
7396         if (N000.getOpcode() == ISD::FMUL) {
7397           return DAG.getNode(ISD::FNEG, SL, VT,
7398                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7399                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7400                                                      N000.getOperand(0)),
7401                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7402                                                      N000.getOperand(1)),
7403                                          N1));
7404         }
7405       }
7406     }
7407
7408     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7409     //   -> (fneg (fma (fpext x)), (fpext y), z)
7410     // Note: This could be removed with appropriate canonicalization of the
7411     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7412     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7413     // from implementing the canonicalization in visitFSUB.
7414     if (N0.getOpcode() == ISD::FNEG) {
7415       SDValue N00 = N0.getOperand(0);
7416       if (N00.getOpcode() == ISD::FP_EXTEND) {
7417         SDValue N000 = N00.getOperand(0);
7418         if (N000.getOpcode() == ISD::FMUL) {
7419           return DAG.getNode(ISD::FNEG, SL, VT,
7420                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7421                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7422                                                      N000.getOperand(0)),
7423                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7424                                                      N000.getOperand(1)),
7425                                          N1));
7426         }
7427       }
7428     }
7429
7430   }
7431
7432   // More folding opportunities when target permits.
7433   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7434     // fold (fsub (fma x, y, (fmul u, v)), z)
7435     //   -> (fma x, y (fma u, v, (fneg z)))
7436     if (N0.getOpcode() == PreferredFusedOpcode &&
7437         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7438       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7439                          N0.getOperand(0), N0.getOperand(1),
7440                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7441                                      N0.getOperand(2).getOperand(0),
7442                                      N0.getOperand(2).getOperand(1),
7443                                      DAG.getNode(ISD::FNEG, SL, VT,
7444                                                  N1)));
7445     }
7446
7447     // fold (fsub x, (fma y, z, (fmul u, v)))
7448     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7449     if (N1.getOpcode() == PreferredFusedOpcode &&
7450         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7451       SDValue N20 = N1.getOperand(2).getOperand(0);
7452       SDValue N21 = N1.getOperand(2).getOperand(1);
7453       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7454                          DAG.getNode(ISD::FNEG, SL, VT,
7455                                      N1.getOperand(0)),
7456                          N1.getOperand(1),
7457                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7458                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7459
7460                                      N21, N0));
7461     }
7462
7463     if (UnsafeFPMath && LookThroughFPExt) {
7464       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7465       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7466       if (N0.getOpcode() == PreferredFusedOpcode) {
7467         SDValue N02 = N0.getOperand(2);
7468         if (N02.getOpcode() == ISD::FP_EXTEND) {
7469           SDValue N020 = N02.getOperand(0);
7470           if (N020.getOpcode() == ISD::FMUL)
7471             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7472                                N0.getOperand(0), N0.getOperand(1),
7473                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7475                                                        N020.getOperand(0)),
7476                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7477                                                        N020.getOperand(1)),
7478                                            DAG.getNode(ISD::FNEG, SL, VT,
7479                                                        N1)));
7480         }
7481       }
7482
7483       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7484       //   -> (fma (fpext x), (fpext y),
7485       //           (fma (fpext u), (fpext v), (fneg z)))
7486       // FIXME: This turns two single-precision and one double-precision
7487       // operation into two double-precision operations, which might not be
7488       // interesting for all targets, especially GPUs.
7489       if (N0.getOpcode() == ISD::FP_EXTEND) {
7490         SDValue N00 = N0.getOperand(0);
7491         if (N00.getOpcode() == PreferredFusedOpcode) {
7492           SDValue N002 = N00.getOperand(2);
7493           if (N002.getOpcode() == ISD::FMUL)
7494             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7495                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7496                                            N00.getOperand(0)),
7497                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7498                                            N00.getOperand(1)),
7499                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7500                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7501                                                        N002.getOperand(0)),
7502                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7503                                                        N002.getOperand(1)),
7504                                            DAG.getNode(ISD::FNEG, SL, VT,
7505                                                        N1)));
7506         }
7507       }
7508
7509       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7510       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7511       if (N1.getOpcode() == PreferredFusedOpcode &&
7512         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7513         SDValue N120 = N1.getOperand(2).getOperand(0);
7514         if (N120.getOpcode() == ISD::FMUL) {
7515           SDValue N1200 = N120.getOperand(0);
7516           SDValue N1201 = N120.getOperand(1);
7517           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7519                              N1.getOperand(1),
7520                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7521                                          DAG.getNode(ISD::FNEG, SL, VT,
7522                                              DAG.getNode(ISD::FP_EXTEND, SL,
7523                                                          VT, N1200)),
7524                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7525                                                      N1201),
7526                                          N0));
7527         }
7528       }
7529
7530       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7531       //   -> (fma (fneg (fpext y)), (fpext z),
7532       //           (fma (fneg (fpext u)), (fpext v), x))
7533       // FIXME: This turns two single-precision and one double-precision
7534       // operation into two double-precision operations, which might not be
7535       // interesting for all targets, especially GPUs.
7536       if (N1.getOpcode() == ISD::FP_EXTEND &&
7537         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7538         SDValue N100 = N1.getOperand(0).getOperand(0);
7539         SDValue N101 = N1.getOperand(0).getOperand(1);
7540         SDValue N102 = N1.getOperand(0).getOperand(2);
7541         if (N102.getOpcode() == ISD::FMUL) {
7542           SDValue N1020 = N102.getOperand(0);
7543           SDValue N1021 = N102.getOperand(1);
7544           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7545                              DAG.getNode(ISD::FNEG, SL, VT,
7546                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7547                                                      N100)),
7548                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7549                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7550                                          DAG.getNode(ISD::FNEG, SL, VT,
7551                                              DAG.getNode(ISD::FP_EXTEND, SL,
7552                                                          VT, N1020)),
7553                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7554                                                      N1021),
7555                                          N0));
7556         }
7557       }
7558     }
7559   }
7560
7561   return SDValue();
7562 }
7563
7564 SDValue DAGCombiner::visitFADD(SDNode *N) {
7565   SDValue N0 = N->getOperand(0);
7566   SDValue N1 = N->getOperand(1);
7567   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7568   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7569   EVT VT = N->getValueType(0);
7570   const TargetOptions &Options = DAG.getTarget().Options;
7571
7572   // fold vector ops
7573   if (VT.isVector())
7574     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7575       return FoldedVOp;
7576
7577   // fold (fadd c1, c2) -> c1 + c2
7578   if (N0CFP && N1CFP)
7579     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7580
7581   // canonicalize constant to RHS
7582   if (N0CFP && !N1CFP)
7583     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7584
7585   // fold (fadd A, (fneg B)) -> (fsub A, B)
7586   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7587       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7588     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7589                        GetNegatedExpression(N1, DAG, LegalOperations));
7590
7591   // fold (fadd (fneg A), B) -> (fsub B, A)
7592   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7593       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7594     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7595                        GetNegatedExpression(N0, DAG, LegalOperations));
7596
7597   // If 'unsafe math' is enabled, fold lots of things.
7598   if (Options.UnsafeFPMath) {
7599     // No FP constant should be created after legalization as Instruction
7600     // Selection pass has a hard time dealing with FP constants.
7601     bool AllowNewConst = (Level < AfterLegalizeDAG);
7602
7603     // fold (fadd A, 0) -> A
7604     if (N1CFP && N1CFP->getValueAPF().isZero())
7605       return N0;
7606
7607     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7608     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7609         isa<ConstantFPSDNode>(N0.getOperand(1)))
7610       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7611                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7612                                      N0.getOperand(1), N1));
7613
7614     // If allowed, fold (fadd (fneg x), x) -> 0.0
7615     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7616       return DAG.getConstantFP(0.0, VT);
7617
7618     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7619     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7620       return DAG.getConstantFP(0.0, VT);
7621
7622     // We can fold chains of FADD's of the same value into multiplications.
7623     // This transform is not safe in general because we are reducing the number
7624     // of rounding steps.
7625     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7626       if (N0.getOpcode() == ISD::FMUL) {
7627         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7628         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7629
7630         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7631         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7632           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7633                                        SDValue(CFP01, 0),
7634                                        DAG.getConstantFP(1.0, VT));
7635           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7636         }
7637
7638         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7639         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7640             N1.getOperand(0) == N1.getOperand(1) &&
7641             N0.getOperand(0) == N1.getOperand(0)) {
7642           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7643                                        SDValue(CFP01, 0),
7644                                        DAG.getConstantFP(2.0, VT));
7645           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7646                              N0.getOperand(0), NewCFP);
7647         }
7648       }
7649
7650       if (N1.getOpcode() == ISD::FMUL) {
7651         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7652         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7653
7654         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7655         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7656           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7657                                        SDValue(CFP11, 0),
7658                                        DAG.getConstantFP(1.0, VT));
7659           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7660         }
7661
7662         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7663         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7664             N0.getOperand(0) == N0.getOperand(1) &&
7665             N1.getOperand(0) == N0.getOperand(0)) {
7666           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7667                                        SDValue(CFP11, 0),
7668                                        DAG.getConstantFP(2.0, VT));
7669           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7670         }
7671       }
7672
7673       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7674         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7675         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7676         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7677             (N0.getOperand(0) == N1))
7678           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7679                              N1, DAG.getConstantFP(3.0, VT));
7680       }
7681
7682       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7683         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7684         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7685         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7686             N1.getOperand(0) == N0)
7687           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7688                              N0, DAG.getConstantFP(3.0, VT));
7689       }
7690
7691       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7692       if (AllowNewConst &&
7693           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7694           N0.getOperand(0) == N0.getOperand(1) &&
7695           N1.getOperand(0) == N1.getOperand(1) &&
7696           N0.getOperand(0) == N1.getOperand(0))
7697         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7698                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7699     }
7700   } // enable-unsafe-fp-math
7701
7702   // FADD -> FMA combines:
7703   SDValue Fused = visitFADDForFMACombine(N);
7704   if (Fused) {
7705     AddToWorklist(Fused.getNode());
7706     return Fused;
7707   }
7708
7709   return SDValue();
7710 }
7711
7712 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7713   SDValue N0 = N->getOperand(0);
7714   SDValue N1 = N->getOperand(1);
7715   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7716   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7717   EVT VT = N->getValueType(0);
7718   SDLoc dl(N);
7719   const TargetOptions &Options = DAG.getTarget().Options;
7720
7721   // fold vector ops
7722   if (VT.isVector())
7723     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7724       return FoldedVOp;
7725
7726   // fold (fsub c1, c2) -> c1-c2
7727   if (N0CFP && N1CFP)
7728     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7729
7730   // fold (fsub A, (fneg B)) -> (fadd A, B)
7731   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7732     return DAG.getNode(ISD::FADD, dl, VT, N0,
7733                        GetNegatedExpression(N1, DAG, LegalOperations));
7734
7735   // If 'unsafe math' is enabled, fold lots of things.
7736   if (Options.UnsafeFPMath) {
7737     // (fsub A, 0) -> A
7738     if (N1CFP && N1CFP->getValueAPF().isZero())
7739       return N0;
7740
7741     // (fsub 0, B) -> -B
7742     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7743       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7744         return GetNegatedExpression(N1, DAG, LegalOperations);
7745       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7746         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7747     }
7748
7749     // (fsub x, x) -> 0.0
7750     if (N0 == N1)
7751       return DAG.getConstantFP(0.0f, VT);
7752
7753     // (fsub x, (fadd x, y)) -> (fneg y)
7754     // (fsub x, (fadd y, x)) -> (fneg y)
7755     if (N1.getOpcode() == ISD::FADD) {
7756       SDValue N10 = N1->getOperand(0);
7757       SDValue N11 = N1->getOperand(1);
7758
7759       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7760         return GetNegatedExpression(N11, DAG, LegalOperations);
7761
7762       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7763         return GetNegatedExpression(N10, DAG, LegalOperations);
7764     }
7765   }
7766
7767   // FSUB -> FMA combines:
7768   SDValue Fused = visitFSUBForFMACombine(N);
7769   if (Fused) {
7770     AddToWorklist(Fused.getNode());
7771     return Fused;
7772   }
7773
7774   return SDValue();
7775 }
7776
7777 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7778   SDValue N0 = N->getOperand(0);
7779   SDValue N1 = N->getOperand(1);
7780   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7781   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7782   EVT VT = N->getValueType(0);
7783   const TargetOptions &Options = DAG.getTarget().Options;
7784
7785   // fold vector ops
7786   if (VT.isVector()) {
7787     // This just handles C1 * C2 for vectors. Other vector folds are below.
7788     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7789       return FoldedVOp;
7790   }
7791
7792   // fold (fmul c1, c2) -> c1*c2
7793   if (N0CFP && N1CFP)
7794     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7795
7796   // canonicalize constant to RHS
7797   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7798      !isConstantFPBuildVectorOrConstantFP(N1))
7799     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7800
7801   // fold (fmul A, 1.0) -> A
7802   if (N1CFP && N1CFP->isExactlyValue(1.0))
7803     return N0;
7804
7805   if (Options.UnsafeFPMath) {
7806     // fold (fmul A, 0) -> 0
7807     if (N1CFP && N1CFP->getValueAPF().isZero())
7808       return N1;
7809
7810     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7811     if (N0.getOpcode() == ISD::FMUL) {
7812       // Fold scalars or any vector constants (not just splats).
7813       // This fold is done in general by InstCombine, but extra fmul insts
7814       // may have been generated during lowering.
7815       SDValue N00 = N0.getOperand(0);
7816       SDValue N01 = N0.getOperand(1);
7817       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7818       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7819       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7820       
7821       // Check 1: Make sure that the first operand of the inner multiply is NOT
7822       // a constant. Otherwise, we may induce infinite looping.
7823       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7824         // Check 2: Make sure that the second operand of the inner multiply and
7825         // the second operand of the outer multiply are constants.
7826         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7827             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7828           SDLoc SL(N);
7829           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7830           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7831         }
7832       }
7833     }
7834
7835     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7836     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7837     // during an early run of DAGCombiner can prevent folding with fmuls
7838     // inserted during lowering.
7839     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7840       SDLoc SL(N);
7841       const SDValue Two = DAG.getConstantFP(2.0, VT);
7842       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7843       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7844     }
7845   }
7846
7847   // fold (fmul X, 2.0) -> (fadd X, X)
7848   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7849     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7850
7851   // fold (fmul X, -1.0) -> (fneg X)
7852   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7853     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7854       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7855
7856   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7857   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7858     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7859       // Both can be negated for free, check to see if at least one is cheaper
7860       // negated.
7861       if (LHSNeg == 2 || RHSNeg == 2)
7862         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7863                            GetNegatedExpression(N0, DAG, LegalOperations),
7864                            GetNegatedExpression(N1, DAG, LegalOperations));
7865     }
7866   }
7867
7868   return SDValue();
7869 }
7870
7871 SDValue DAGCombiner::visitFMA(SDNode *N) {
7872   SDValue N0 = N->getOperand(0);
7873   SDValue N1 = N->getOperand(1);
7874   SDValue N2 = N->getOperand(2);
7875   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7876   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7877   EVT VT = N->getValueType(0);
7878   SDLoc dl(N);
7879   const TargetOptions &Options = DAG.getTarget().Options;
7880
7881   // Constant fold FMA.
7882   if (isa<ConstantFPSDNode>(N0) &&
7883       isa<ConstantFPSDNode>(N1) &&
7884       isa<ConstantFPSDNode>(N2)) {
7885     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7886   }
7887
7888   if (Options.UnsafeFPMath) {
7889     if (N0CFP && N0CFP->isZero())
7890       return N2;
7891     if (N1CFP && N1CFP->isZero())
7892       return N2;
7893   }
7894   if (N0CFP && N0CFP->isExactlyValue(1.0))
7895     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7896   if (N1CFP && N1CFP->isExactlyValue(1.0))
7897     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7898
7899   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7900   if (N0CFP && !N1CFP)
7901     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7902
7903   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7904   if (Options.UnsafeFPMath && N1CFP &&
7905       N2.getOpcode() == ISD::FMUL &&
7906       N0 == N2.getOperand(0) &&
7907       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7908     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7909                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7910   }
7911
7912
7913   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7914   if (Options.UnsafeFPMath &&
7915       N0.getOpcode() == ISD::FMUL && N1CFP &&
7916       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7917     return DAG.getNode(ISD::FMA, dl, VT,
7918                        N0.getOperand(0),
7919                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7920                        N2);
7921   }
7922
7923   // (fma x, 1, y) -> (fadd x, y)
7924   // (fma x, -1, y) -> (fadd (fneg x), y)
7925   if (N1CFP) {
7926     if (N1CFP->isExactlyValue(1.0))
7927       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7928
7929     if (N1CFP->isExactlyValue(-1.0) &&
7930         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7931       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7932       AddToWorklist(RHSNeg.getNode());
7933       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7934     }
7935   }
7936
7937   // (fma x, c, x) -> (fmul x, (c+1))
7938   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7939     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7940                        DAG.getNode(ISD::FADD, dl, VT,
7941                                    N1, DAG.getConstantFP(1.0, VT)));
7942
7943   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7944   if (Options.UnsafeFPMath && N1CFP &&
7945       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7946     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7947                        DAG.getNode(ISD::FADD, dl, VT,
7948                                    N1, DAG.getConstantFP(-1.0, VT)));
7949
7950
7951   return SDValue();
7952 }
7953
7954 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7955   SDValue N0 = N->getOperand(0);
7956   SDValue N1 = N->getOperand(1);
7957   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7958   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7959   EVT VT = N->getValueType(0);
7960   SDLoc DL(N);
7961   const TargetOptions &Options = DAG.getTarget().Options;
7962
7963   // fold vector ops
7964   if (VT.isVector())
7965     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7966       return FoldedVOp;
7967
7968   // fold (fdiv c1, c2) -> c1/c2
7969   if (N0CFP && N1CFP)
7970     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7971
7972   if (Options.UnsafeFPMath) {
7973     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7974     if (N1CFP) {
7975       // Compute the reciprocal 1.0 / c2.
7976       APFloat N1APF = N1CFP->getValueAPF();
7977       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7978       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7979       // Only do the transform if the reciprocal is a legal fp immediate that
7980       // isn't too nasty (eg NaN, denormal, ...).
7981       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7982           (!LegalOperations ||
7983            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7984            // backend)... we should handle this gracefully after Legalize.
7985            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7986            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7987            TLI.isFPImmLegal(Recip, VT)))
7988         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7989                            DAG.getConstantFP(Recip, VT));
7990     }
7991
7992     // If this FDIV is part of a reciprocal square root, it may be folded
7993     // into a target-specific square root estimate instruction.
7994     if (N1.getOpcode() == ISD::FSQRT) {
7995       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7996         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7997       }
7998     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7999                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8000       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8001         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8002         AddToWorklist(RV.getNode());
8003         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8004       }
8005     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8006                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8007       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8008         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8009         AddToWorklist(RV.getNode());
8010         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8011       }
8012     } else if (N1.getOpcode() == ISD::FMUL) {
8013       // Look through an FMUL. Even though this won't remove the FDIV directly,
8014       // it's still worthwhile to get rid of the FSQRT if possible.
8015       SDValue SqrtOp;
8016       SDValue OtherOp;
8017       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8018         SqrtOp = N1.getOperand(0);
8019         OtherOp = N1.getOperand(1);
8020       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8021         SqrtOp = N1.getOperand(1);
8022         OtherOp = N1.getOperand(0);
8023       }
8024       if (SqrtOp.getNode()) {
8025         // We found a FSQRT, so try to make this fold:
8026         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8027         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8028           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8029           AddToWorklist(RV.getNode());
8030           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8031         }
8032       }
8033     }
8034
8035     // Fold into a reciprocal estimate and multiply instead of a real divide.
8036     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8037       AddToWorklist(RV.getNode());
8038       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8039     }
8040   }
8041
8042   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8043   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8044     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8045       // Both can be negated for free, check to see if at least one is cheaper
8046       // negated.
8047       if (LHSNeg == 2 || RHSNeg == 2)
8048         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8049                            GetNegatedExpression(N0, DAG, LegalOperations),
8050                            GetNegatedExpression(N1, DAG, LegalOperations));
8051     }
8052   }
8053
8054   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8055   // reciprocal.
8056   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8057   // Notice that this is not always beneficial. One reason is different target
8058   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8059   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8060   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8061   if (Options.UnsafeFPMath) {
8062     // Skip if current node is a reciprocal.
8063     if (N0CFP && N0CFP->isExactlyValue(1.0))
8064       return SDValue();
8065
8066     SmallVector<SDNode *, 4> Users;
8067     // Find all FDIV users of the same divisor.
8068     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8069                               UE = N1.getNode()->use_end();
8070          UI != UE; ++UI) {
8071       SDNode *User = UI.getUse().getUser();
8072       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8073         Users.push_back(User);
8074     }
8075
8076     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8077       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
8078       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
8079
8080       // Dividend / Divisor -> Dividend * Reciprocal
8081       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8082         if ((*I)->getOperand(0) != FPOne) {
8083           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8084                                         (*I)->getOperand(0), Reciprocal);
8085           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8086         }
8087       }
8088       return SDValue();
8089     }
8090   }
8091
8092   return SDValue();
8093 }
8094
8095 SDValue DAGCombiner::visitFREM(SDNode *N) {
8096   SDValue N0 = N->getOperand(0);
8097   SDValue N1 = N->getOperand(1);
8098   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8099   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8100   EVT VT = N->getValueType(0);
8101
8102   // fold (frem c1, c2) -> fmod(c1,c2)
8103   if (N0CFP && N1CFP)
8104     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8105
8106   return SDValue();
8107 }
8108
8109 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8110   if (DAG.getTarget().Options.UnsafeFPMath &&
8111       !TLI.isFsqrtCheap()) {
8112     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8113     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8114       EVT VT = RV.getValueType();
8115       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
8116       AddToWorklist(RV.getNode());
8117
8118       // Unfortunately, RV is now NaN if the input was exactly 0.
8119       // Select out this case and force the answer to 0.
8120       SDValue Zero = DAG.getConstantFP(0.0, VT);
8121       SDValue ZeroCmp =
8122         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
8123                      N->getOperand(0), Zero, ISD::SETEQ);
8124       AddToWorklist(ZeroCmp.getNode());
8125       AddToWorklist(RV.getNode());
8126
8127       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8128                        SDLoc(N), VT, ZeroCmp, Zero, RV);
8129       return RV;
8130     }
8131   }
8132   return SDValue();
8133 }
8134
8135 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8136   SDValue N0 = N->getOperand(0);
8137   SDValue N1 = N->getOperand(1);
8138   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8139   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8140   EVT VT = N->getValueType(0);
8141
8142   if (N0CFP && N1CFP)  // Constant fold
8143     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8144
8145   if (N1CFP) {
8146     const APFloat& V = N1CFP->getValueAPF();
8147     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8148     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8149     if (!V.isNegative()) {
8150       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8151         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8152     } else {
8153       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8154         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8155                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8156     }
8157   }
8158
8159   // copysign(fabs(x), y) -> copysign(x, y)
8160   // copysign(fneg(x), y) -> copysign(x, y)
8161   // copysign(copysign(x,z), y) -> copysign(x, y)
8162   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8163       N0.getOpcode() == ISD::FCOPYSIGN)
8164     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8165                        N0.getOperand(0), N1);
8166
8167   // copysign(x, abs(y)) -> abs(x)
8168   if (N1.getOpcode() == ISD::FABS)
8169     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8170
8171   // copysign(x, copysign(y,z)) -> copysign(x, z)
8172   if (N1.getOpcode() == ISD::FCOPYSIGN)
8173     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8174                        N0, N1.getOperand(1));
8175
8176   // copysign(x, fp_extend(y)) -> copysign(x, y)
8177   // copysign(x, fp_round(y)) -> copysign(x, y)
8178   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8179     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8180                        N0, N1.getOperand(0));
8181
8182   return SDValue();
8183 }
8184
8185 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8186   SDValue N0 = N->getOperand(0);
8187   EVT VT = N->getValueType(0);
8188   EVT OpVT = N0.getValueType();
8189
8190   // fold (sint_to_fp c1) -> c1fp
8191   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8192       // ...but only if the target supports immediate floating-point values
8193       (!LegalOperations ||
8194        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8195     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8196
8197   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8198   // but UINT_TO_FP is legal on this target, try to convert.
8199   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8200       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8201     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8202     if (DAG.SignBitIsZero(N0))
8203       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8204   }
8205
8206   // The next optimizations are desirable only if SELECT_CC can be lowered.
8207   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8208     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8209     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8210         !VT.isVector() &&
8211         (!LegalOperations ||
8212          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8213       SDValue Ops[] =
8214         { N0.getOperand(0), N0.getOperand(1),
8215           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
8216           N0.getOperand(2) };
8217       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8218     }
8219
8220     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8221     //      (select_cc x, y, 1.0, 0.0,, cc)
8222     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8223         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8224         (!LegalOperations ||
8225          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8226       SDValue Ops[] =
8227         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8228           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8229           N0.getOperand(0).getOperand(2) };
8230       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8231     }
8232   }
8233
8234   return SDValue();
8235 }
8236
8237 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8238   SDValue N0 = N->getOperand(0);
8239   EVT VT = N->getValueType(0);
8240   EVT OpVT = N0.getValueType();
8241
8242   // fold (uint_to_fp c1) -> c1fp
8243   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8244       // ...but only if the target supports immediate floating-point values
8245       (!LegalOperations ||
8246        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8247     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8248
8249   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8250   // but SINT_TO_FP is legal on this target, try to convert.
8251   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8252       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8253     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8254     if (DAG.SignBitIsZero(N0))
8255       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8256   }
8257
8258   // The next optimizations are desirable only if SELECT_CC can be lowered.
8259   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8260     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8261
8262     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8263         (!LegalOperations ||
8264          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8265       SDValue Ops[] =
8266         { N0.getOperand(0), N0.getOperand(1),
8267           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
8268           N0.getOperand(2) };
8269       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8270     }
8271   }
8272
8273   return SDValue();
8274 }
8275
8276 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8277 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8278   SDValue N0 = N->getOperand(0);
8279   EVT VT = N->getValueType(0);
8280
8281   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8282     return SDValue();
8283
8284   SDValue Src = N0.getOperand(0);
8285   EVT SrcVT = Src.getValueType();
8286   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8287   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8288
8289   // We can safely assume the conversion won't overflow the output range,
8290   // because (for example) (uint8_t)18293.f is undefined behavior.
8291
8292   // Since we can assume the conversion won't overflow, our decision as to
8293   // whether the input will fit in the float should depend on the minimum
8294   // of the input range and output range.
8295
8296   // This means this is also safe for a signed input and unsigned output, since
8297   // a negative input would lead to undefined behavior.
8298   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8299   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8300   unsigned ActualSize = std::min(InputSize, OutputSize);
8301   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8302
8303   // We can only fold away the float conversion if the input range can be
8304   // represented exactly in the float range.
8305   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8306     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8307       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8308                                                        : ISD::ZERO_EXTEND;
8309       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8310     }
8311     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8312       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8313     if (SrcVT == VT)
8314       return Src;
8315     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8316   }
8317   return SDValue();
8318 }
8319
8320 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8321   SDValue N0 = N->getOperand(0);
8322   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8323   EVT VT = N->getValueType(0);
8324
8325   // fold (fp_to_sint c1fp) -> c1
8326   if (N0CFP)
8327     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8328
8329   return FoldIntToFPToInt(N, DAG);
8330 }
8331
8332 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8333   SDValue N0 = N->getOperand(0);
8334   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8335   EVT VT = N->getValueType(0);
8336
8337   // fold (fp_to_uint c1fp) -> c1
8338   if (N0CFP)
8339     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8340
8341   return FoldIntToFPToInt(N, DAG);
8342 }
8343
8344 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8345   SDValue N0 = N->getOperand(0);
8346   SDValue N1 = N->getOperand(1);
8347   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8348   EVT VT = N->getValueType(0);
8349
8350   // fold (fp_round c1fp) -> c1fp
8351   if (N0CFP)
8352     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8353
8354   // fold (fp_round (fp_extend x)) -> x
8355   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8356     return N0.getOperand(0);
8357
8358   // fold (fp_round (fp_round x)) -> (fp_round x)
8359   if (N0.getOpcode() == ISD::FP_ROUND) {
8360     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8361     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8362     // If the first fp_round isn't a value preserving truncation, it might
8363     // introduce a tie in the second fp_round, that wouldn't occur in the
8364     // single-step fp_round we want to fold to.
8365     // In other words, double rounding isn't the same as rounding.
8366     // Also, this is a value preserving truncation iff both fp_round's are.
8367     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8368       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8369                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8370   }
8371
8372   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8373   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8374     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8375                               N0.getOperand(0), N1);
8376     AddToWorklist(Tmp.getNode());
8377     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8378                        Tmp, N0.getOperand(1));
8379   }
8380
8381   return SDValue();
8382 }
8383
8384 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8385   SDValue N0 = N->getOperand(0);
8386   EVT VT = N->getValueType(0);
8387   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8388   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8389
8390   // fold (fp_round_inreg c1fp) -> c1fp
8391   if (N0CFP && isTypeLegal(EVT)) {
8392     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8393     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8394   }
8395
8396   return SDValue();
8397 }
8398
8399 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8400   SDValue N0 = N->getOperand(0);
8401   EVT VT = N->getValueType(0);
8402
8403   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8404   if (N->hasOneUse() &&
8405       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8406     return SDValue();
8407
8408   // fold (fp_extend c1fp) -> c1fp
8409   if (isConstantFPBuildVectorOrConstantFP(N0))
8410     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8411
8412   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8413   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8414       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8415     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8416
8417   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8418   // value of X.
8419   if (N0.getOpcode() == ISD::FP_ROUND
8420       && N0.getNode()->getConstantOperandVal(1) == 1) {
8421     SDValue In = N0.getOperand(0);
8422     if (In.getValueType() == VT) return In;
8423     if (VT.bitsLT(In.getValueType()))
8424       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8425                          In, N0.getOperand(1));
8426     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8427   }
8428
8429   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8430   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8431        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8432     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8433     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8434                                      LN0->getChain(),
8435                                      LN0->getBasePtr(), N0.getValueType(),
8436                                      LN0->getMemOperand());
8437     CombineTo(N, ExtLoad);
8438     CombineTo(N0.getNode(),
8439               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8440                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8441               ExtLoad.getValue(1));
8442     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8443   }
8444
8445   return SDValue();
8446 }
8447
8448 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8449   SDValue N0 = N->getOperand(0);
8450   EVT VT = N->getValueType(0);
8451
8452   // fold (fceil c1) -> fceil(c1)
8453   if (isConstantFPBuildVectorOrConstantFP(N0))
8454     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8455
8456   return SDValue();
8457 }
8458
8459 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8460   SDValue N0 = N->getOperand(0);
8461   EVT VT = N->getValueType(0);
8462
8463   // fold (ftrunc c1) -> ftrunc(c1)
8464   if (isConstantFPBuildVectorOrConstantFP(N0))
8465     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8466
8467   return SDValue();
8468 }
8469
8470 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8471   SDValue N0 = N->getOperand(0);
8472   EVT VT = N->getValueType(0);
8473
8474   // fold (ffloor c1) -> ffloor(c1)
8475   if (isConstantFPBuildVectorOrConstantFP(N0))
8476     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8477
8478   return SDValue();
8479 }
8480
8481 // FIXME: FNEG and FABS have a lot in common; refactor.
8482 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8483   SDValue N0 = N->getOperand(0);
8484   EVT VT = N->getValueType(0);
8485
8486   // Constant fold FNEG.
8487   if (isConstantFPBuildVectorOrConstantFP(N0))
8488     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8489
8490   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8491                          &DAG.getTarget().Options))
8492     return GetNegatedExpression(N0, DAG, LegalOperations);
8493
8494   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8495   // constant pool values.
8496   if (!TLI.isFNegFree(VT) &&
8497       N0.getOpcode() == ISD::BITCAST &&
8498       N0.getNode()->hasOneUse()) {
8499     SDValue Int = N0.getOperand(0);
8500     EVT IntVT = Int.getValueType();
8501     if (IntVT.isInteger() && !IntVT.isVector()) {
8502       APInt SignMask;
8503       if (N0.getValueType().isVector()) {
8504         // For a vector, get a mask such as 0x80... per scalar element
8505         // and splat it.
8506         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8507         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8508       } else {
8509         // For a scalar, just generate 0x80...
8510         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8511       }
8512       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8513                         DAG.getConstant(SignMask, IntVT));
8514       AddToWorklist(Int.getNode());
8515       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8516     }
8517   }
8518
8519   // (fneg (fmul c, x)) -> (fmul -c, x)
8520   if (N0.getOpcode() == ISD::FMUL) {
8521     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8522     if (CFP1) {
8523       APFloat CVal = CFP1->getValueAPF();
8524       CVal.changeSign();
8525       if (Level >= AfterLegalizeDAG &&
8526           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8527            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8528         return DAG.getNode(
8529             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8530             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8531     }
8532   }
8533
8534   return SDValue();
8535 }
8536
8537 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8538   SDValue N0 = N->getOperand(0);
8539   SDValue N1 = N->getOperand(1);
8540   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8541   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8542
8543   if (N0CFP && N1CFP) {
8544     const APFloat &C0 = N0CFP->getValueAPF();
8545     const APFloat &C1 = N1CFP->getValueAPF();
8546     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8547   }
8548
8549   if (N0CFP) {
8550     EVT VT = N->getValueType(0);
8551     // Canonicalize to constant on RHS.
8552     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8553   }
8554
8555   return SDValue();
8556 }
8557
8558 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8559   SDValue N0 = N->getOperand(0);
8560   SDValue N1 = N->getOperand(1);
8561   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8562   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8563
8564   if (N0CFP && N1CFP) {
8565     const APFloat &C0 = N0CFP->getValueAPF();
8566     const APFloat &C1 = N1CFP->getValueAPF();
8567     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8568   }
8569
8570   if (N0CFP) {
8571     EVT VT = N->getValueType(0);
8572     // Canonicalize to constant on RHS.
8573     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8574   }
8575
8576   return SDValue();
8577 }
8578
8579 SDValue DAGCombiner::visitFABS(SDNode *N) {
8580   SDValue N0 = N->getOperand(0);
8581   EVT VT = N->getValueType(0);
8582
8583   // fold (fabs c1) -> fabs(c1)
8584   if (isConstantFPBuildVectorOrConstantFP(N0))
8585     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8586
8587   // fold (fabs (fabs x)) -> (fabs x)
8588   if (N0.getOpcode() == ISD::FABS)
8589     return N->getOperand(0);
8590
8591   // fold (fabs (fneg x)) -> (fabs x)
8592   // fold (fabs (fcopysign x, y)) -> (fabs x)
8593   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8594     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8595
8596   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8597   // constant pool values.
8598   if (!TLI.isFAbsFree(VT) &&
8599       N0.getOpcode() == ISD::BITCAST &&
8600       N0.getNode()->hasOneUse()) {
8601     SDValue Int = N0.getOperand(0);
8602     EVT IntVT = Int.getValueType();
8603     if (IntVT.isInteger() && !IntVT.isVector()) {
8604       APInt SignMask;
8605       if (N0.getValueType().isVector()) {
8606         // For a vector, get a mask such as 0x7f... per scalar element
8607         // and splat it.
8608         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8609         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8610       } else {
8611         // For a scalar, just generate 0x7f...
8612         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8613       }
8614       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8615                         DAG.getConstant(SignMask, IntVT));
8616       AddToWorklist(Int.getNode());
8617       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8618     }
8619   }
8620
8621   return SDValue();
8622 }
8623
8624 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8625   SDValue Chain = N->getOperand(0);
8626   SDValue N1 = N->getOperand(1);
8627   SDValue N2 = N->getOperand(2);
8628
8629   // If N is a constant we could fold this into a fallthrough or unconditional
8630   // branch. However that doesn't happen very often in normal code, because
8631   // Instcombine/SimplifyCFG should have handled the available opportunities.
8632   // If we did this folding here, it would be necessary to update the
8633   // MachineBasicBlock CFG, which is awkward.
8634
8635   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8636   // on the target.
8637   if (N1.getOpcode() == ISD::SETCC &&
8638       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8639                                    N1.getOperand(0).getValueType())) {
8640     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8641                        Chain, N1.getOperand(2),
8642                        N1.getOperand(0), N1.getOperand(1), N2);
8643   }
8644
8645   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8646       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8647        (N1.getOperand(0).hasOneUse() &&
8648         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8649     SDNode *Trunc = nullptr;
8650     if (N1.getOpcode() == ISD::TRUNCATE) {
8651       // Look pass the truncate.
8652       Trunc = N1.getNode();
8653       N1 = N1.getOperand(0);
8654     }
8655
8656     // Match this pattern so that we can generate simpler code:
8657     //
8658     //   %a = ...
8659     //   %b = and i32 %a, 2
8660     //   %c = srl i32 %b, 1
8661     //   brcond i32 %c ...
8662     //
8663     // into
8664     //
8665     //   %a = ...
8666     //   %b = and i32 %a, 2
8667     //   %c = setcc eq %b, 0
8668     //   brcond %c ...
8669     //
8670     // This applies only when the AND constant value has one bit set and the
8671     // SRL constant is equal to the log2 of the AND constant. The back-end is
8672     // smart enough to convert the result into a TEST/JMP sequence.
8673     SDValue Op0 = N1.getOperand(0);
8674     SDValue Op1 = N1.getOperand(1);
8675
8676     if (Op0.getOpcode() == ISD::AND &&
8677         Op1.getOpcode() == ISD::Constant) {
8678       SDValue AndOp1 = Op0.getOperand(1);
8679
8680       if (AndOp1.getOpcode() == ISD::Constant) {
8681         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8682
8683         if (AndConst.isPowerOf2() &&
8684             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8685           SDValue SetCC =
8686             DAG.getSetCC(SDLoc(N),
8687                          getSetCCResultType(Op0.getValueType()),
8688                          Op0, DAG.getConstant(0, Op0.getValueType()),
8689                          ISD::SETNE);
8690
8691           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8692                                           MVT::Other, Chain, SetCC, N2);
8693           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8694           // will convert it back to (X & C1) >> C2.
8695           CombineTo(N, NewBRCond, false);
8696           // Truncate is dead.
8697           if (Trunc)
8698             deleteAndRecombine(Trunc);
8699           // Replace the uses of SRL with SETCC
8700           WorklistRemover DeadNodes(*this);
8701           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8702           deleteAndRecombine(N1.getNode());
8703           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8704         }
8705       }
8706     }
8707
8708     if (Trunc)
8709       // Restore N1 if the above transformation doesn't match.
8710       N1 = N->getOperand(1);
8711   }
8712
8713   // Transform br(xor(x, y)) -> br(x != y)
8714   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8715   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8716     SDNode *TheXor = N1.getNode();
8717     SDValue Op0 = TheXor->getOperand(0);
8718     SDValue Op1 = TheXor->getOperand(1);
8719     if (Op0.getOpcode() == Op1.getOpcode()) {
8720       // Avoid missing important xor optimizations.
8721       SDValue Tmp = visitXOR(TheXor);
8722       if (Tmp.getNode()) {
8723         if (Tmp.getNode() != TheXor) {
8724           DEBUG(dbgs() << "\nReplacing.8 ";
8725                 TheXor->dump(&DAG);
8726                 dbgs() << "\nWith: ";
8727                 Tmp.getNode()->dump(&DAG);
8728                 dbgs() << '\n');
8729           WorklistRemover DeadNodes(*this);
8730           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8731           deleteAndRecombine(TheXor);
8732           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8733                              MVT::Other, Chain, Tmp, N2);
8734         }
8735
8736         // visitXOR has changed XOR's operands or replaced the XOR completely,
8737         // bail out.
8738         return SDValue(N, 0);
8739       }
8740     }
8741
8742     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8743       bool Equal = false;
8744       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8745         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8746             Op0.getOpcode() == ISD::XOR) {
8747           TheXor = Op0.getNode();
8748           Equal = true;
8749         }
8750
8751       EVT SetCCVT = N1.getValueType();
8752       if (LegalTypes)
8753         SetCCVT = getSetCCResultType(SetCCVT);
8754       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8755                                    SetCCVT,
8756                                    Op0, Op1,
8757                                    Equal ? ISD::SETEQ : ISD::SETNE);
8758       // Replace the uses of XOR with SETCC
8759       WorklistRemover DeadNodes(*this);
8760       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8761       deleteAndRecombine(N1.getNode());
8762       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8763                          MVT::Other, Chain, SetCC, N2);
8764     }
8765   }
8766
8767   return SDValue();
8768 }
8769
8770 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8771 //
8772 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8773   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8774   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8775
8776   // If N is a constant we could fold this into a fallthrough or unconditional
8777   // branch. However that doesn't happen very often in normal code, because
8778   // Instcombine/SimplifyCFG should have handled the available opportunities.
8779   // If we did this folding here, it would be necessary to update the
8780   // MachineBasicBlock CFG, which is awkward.
8781
8782   // Use SimplifySetCC to simplify SETCC's.
8783   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8784                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8785                                false);
8786   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8787
8788   // fold to a simpler setcc
8789   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8790     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8791                        N->getOperand(0), Simp.getOperand(2),
8792                        Simp.getOperand(0), Simp.getOperand(1),
8793                        N->getOperand(4));
8794
8795   return SDValue();
8796 }
8797
8798 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8799 /// and that N may be folded in the load / store addressing mode.
8800 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8801                                     SelectionDAG &DAG,
8802                                     const TargetLowering &TLI) {
8803   EVT VT;
8804   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8805     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8806       return false;
8807     VT = LD->getMemoryVT();
8808   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8809     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8810       return false;
8811     VT = ST->getMemoryVT();
8812   } else
8813     return false;
8814
8815   TargetLowering::AddrMode AM;
8816   if (N->getOpcode() == ISD::ADD) {
8817     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8818     if (Offset)
8819       // [reg +/- imm]
8820       AM.BaseOffs = Offset->getSExtValue();
8821     else
8822       // [reg +/- reg]
8823       AM.Scale = 1;
8824   } else if (N->getOpcode() == ISD::SUB) {
8825     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8826     if (Offset)
8827       // [reg +/- imm]
8828       AM.BaseOffs = -Offset->getSExtValue();
8829     else
8830       // [reg +/- reg]
8831       AM.Scale = 1;
8832   } else
8833     return false;
8834
8835   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8836 }
8837
8838 /// Try turning a load/store into a pre-indexed load/store when the base
8839 /// pointer is an add or subtract and it has other uses besides the load/store.
8840 /// After the transformation, the new indexed load/store has effectively folded
8841 /// the add/subtract in and all of its other uses are redirected to the
8842 /// new load/store.
8843 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8844   if (Level < AfterLegalizeDAG)
8845     return false;
8846
8847   bool isLoad = true;
8848   SDValue Ptr;
8849   EVT VT;
8850   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8851     if (LD->isIndexed())
8852       return false;
8853     VT = LD->getMemoryVT();
8854     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8855         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8856       return false;
8857     Ptr = LD->getBasePtr();
8858   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8859     if (ST->isIndexed())
8860       return false;
8861     VT = ST->getMemoryVT();
8862     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8863         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8864       return false;
8865     Ptr = ST->getBasePtr();
8866     isLoad = false;
8867   } else {
8868     return false;
8869   }
8870
8871   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8872   // out.  There is no reason to make this a preinc/predec.
8873   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8874       Ptr.getNode()->hasOneUse())
8875     return false;
8876
8877   // Ask the target to do addressing mode selection.
8878   SDValue BasePtr;
8879   SDValue Offset;
8880   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8881   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8882     return false;
8883
8884   // Backends without true r+i pre-indexed forms may need to pass a
8885   // constant base with a variable offset so that constant coercion
8886   // will work with the patterns in canonical form.
8887   bool Swapped = false;
8888   if (isa<ConstantSDNode>(BasePtr)) {
8889     std::swap(BasePtr, Offset);
8890     Swapped = true;
8891   }
8892
8893   // Don't create a indexed load / store with zero offset.
8894   if (isa<ConstantSDNode>(Offset) &&
8895       cast<ConstantSDNode>(Offset)->isNullValue())
8896     return false;
8897
8898   // Try turning it into a pre-indexed load / store except when:
8899   // 1) The new base ptr is a frame index.
8900   // 2) If N is a store and the new base ptr is either the same as or is a
8901   //    predecessor of the value being stored.
8902   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8903   //    that would create a cycle.
8904   // 4) All uses are load / store ops that use it as old base ptr.
8905
8906   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8907   // (plus the implicit offset) to a register to preinc anyway.
8908   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8909     return false;
8910
8911   // Check #2.
8912   if (!isLoad) {
8913     SDValue Val = cast<StoreSDNode>(N)->getValue();
8914     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8915       return false;
8916   }
8917
8918   // If the offset is a constant, there may be other adds of constants that
8919   // can be folded with this one. We should do this to avoid having to keep
8920   // a copy of the original base pointer.
8921   SmallVector<SDNode *, 16> OtherUses;
8922   if (isa<ConstantSDNode>(Offset))
8923     for (SDNode *Use : BasePtr.getNode()->uses()) {
8924       if (Use == Ptr.getNode())
8925         continue;
8926
8927       if (Use->isPredecessorOf(N))
8928         continue;
8929
8930       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8931         OtherUses.clear();
8932         break;
8933       }
8934
8935       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8936       if (Op1.getNode() == BasePtr.getNode())
8937         std::swap(Op0, Op1);
8938       assert(Op0.getNode() == BasePtr.getNode() &&
8939              "Use of ADD/SUB but not an operand");
8940
8941       if (!isa<ConstantSDNode>(Op1)) {
8942         OtherUses.clear();
8943         break;
8944       }
8945
8946       // FIXME: In some cases, we can be smarter about this.
8947       if (Op1.getValueType() != Offset.getValueType()) {
8948         OtherUses.clear();
8949         break;
8950       }
8951
8952       OtherUses.push_back(Use);
8953     }
8954
8955   if (Swapped)
8956     std::swap(BasePtr, Offset);
8957
8958   // Now check for #3 and #4.
8959   bool RealUse = false;
8960
8961   // Caches for hasPredecessorHelper
8962   SmallPtrSet<const SDNode *, 32> Visited;
8963   SmallVector<const SDNode *, 16> Worklist;
8964
8965   for (SDNode *Use : Ptr.getNode()->uses()) {
8966     if (Use == N)
8967       continue;
8968     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8969       return false;
8970
8971     // If Ptr may be folded in addressing mode of other use, then it's
8972     // not profitable to do this transformation.
8973     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8974       RealUse = true;
8975   }
8976
8977   if (!RealUse)
8978     return false;
8979
8980   SDValue Result;
8981   if (isLoad)
8982     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8983                                 BasePtr, Offset, AM);
8984   else
8985     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8986                                  BasePtr, Offset, AM);
8987   ++PreIndexedNodes;
8988   ++NodesCombined;
8989   DEBUG(dbgs() << "\nReplacing.4 ";
8990         N->dump(&DAG);
8991         dbgs() << "\nWith: ";
8992         Result.getNode()->dump(&DAG);
8993         dbgs() << '\n');
8994   WorklistRemover DeadNodes(*this);
8995   if (isLoad) {
8996     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8997     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8998   } else {
8999     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9000   }
9001
9002   // Finally, since the node is now dead, remove it from the graph.
9003   deleteAndRecombine(N);
9004
9005   if (Swapped)
9006     std::swap(BasePtr, Offset);
9007
9008   // Replace other uses of BasePtr that can be updated to use Ptr
9009   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9010     unsigned OffsetIdx = 1;
9011     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9012       OffsetIdx = 0;
9013     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9014            BasePtr.getNode() && "Expected BasePtr operand");
9015
9016     // We need to replace ptr0 in the following expression:
9017     //   x0 * offset0 + y0 * ptr0 = t0
9018     // knowing that
9019     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9020     //
9021     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9022     // indexed load/store and the expresion that needs to be re-written.
9023     //
9024     // Therefore, we have:
9025     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9026
9027     ConstantSDNode *CN =
9028       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9029     int X0, X1, Y0, Y1;
9030     APInt Offset0 = CN->getAPIntValue();
9031     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9032
9033     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9034     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9035     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9036     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9037
9038     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9039
9040     APInt CNV = Offset0;
9041     if (X0 < 0) CNV = -CNV;
9042     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9043     else CNV = CNV - Offset1;
9044
9045     // We can now generate the new expression.
9046     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
9047     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9048
9049     SDValue NewUse = DAG.getNode(Opcode,
9050                                  SDLoc(OtherUses[i]),
9051                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9052     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9053     deleteAndRecombine(OtherUses[i]);
9054   }
9055
9056   // Replace the uses of Ptr with uses of the updated base value.
9057   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9058   deleteAndRecombine(Ptr.getNode());
9059
9060   return true;
9061 }
9062
9063 /// Try to combine a load/store with a add/sub of the base pointer node into a
9064 /// post-indexed load/store. The transformation folded the add/subtract into the
9065 /// new indexed load/store effectively and all of its uses are redirected to the
9066 /// new load/store.
9067 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9068   if (Level < AfterLegalizeDAG)
9069     return false;
9070
9071   bool isLoad = true;
9072   SDValue Ptr;
9073   EVT VT;
9074   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9075     if (LD->isIndexed())
9076       return false;
9077     VT = LD->getMemoryVT();
9078     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9079         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9080       return false;
9081     Ptr = LD->getBasePtr();
9082   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9083     if (ST->isIndexed())
9084       return false;
9085     VT = ST->getMemoryVT();
9086     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9087         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9088       return false;
9089     Ptr = ST->getBasePtr();
9090     isLoad = false;
9091   } else {
9092     return false;
9093   }
9094
9095   if (Ptr.getNode()->hasOneUse())
9096     return false;
9097
9098   for (SDNode *Op : Ptr.getNode()->uses()) {
9099     if (Op == N ||
9100         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9101       continue;
9102
9103     SDValue BasePtr;
9104     SDValue Offset;
9105     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9106     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9107       // Don't create a indexed load / store with zero offset.
9108       if (isa<ConstantSDNode>(Offset) &&
9109           cast<ConstantSDNode>(Offset)->isNullValue())
9110         continue;
9111
9112       // Try turning it into a post-indexed load / store except when
9113       // 1) All uses are load / store ops that use it as base ptr (and
9114       //    it may be folded as addressing mmode).
9115       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9116       //    nor a successor of N. Otherwise, if Op is folded that would
9117       //    create a cycle.
9118
9119       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9120         continue;
9121
9122       // Check for #1.
9123       bool TryNext = false;
9124       for (SDNode *Use : BasePtr.getNode()->uses()) {
9125         if (Use == Ptr.getNode())
9126           continue;
9127
9128         // If all the uses are load / store addresses, then don't do the
9129         // transformation.
9130         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9131           bool RealUse = false;
9132           for (SDNode *UseUse : Use->uses()) {
9133             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9134               RealUse = true;
9135           }
9136
9137           if (!RealUse) {
9138             TryNext = true;
9139             break;
9140           }
9141         }
9142       }
9143
9144       if (TryNext)
9145         continue;
9146
9147       // Check for #2
9148       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9149         SDValue Result = isLoad
9150           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9151                                BasePtr, Offset, AM)
9152           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9153                                 BasePtr, Offset, AM);
9154         ++PostIndexedNodes;
9155         ++NodesCombined;
9156         DEBUG(dbgs() << "\nReplacing.5 ";
9157               N->dump(&DAG);
9158               dbgs() << "\nWith: ";
9159               Result.getNode()->dump(&DAG);
9160               dbgs() << '\n');
9161         WorklistRemover DeadNodes(*this);
9162         if (isLoad) {
9163           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9164           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9165         } else {
9166           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9167         }
9168
9169         // Finally, since the node is now dead, remove it from the graph.
9170         deleteAndRecombine(N);
9171
9172         // Replace the uses of Use with uses of the updated base value.
9173         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9174                                       Result.getValue(isLoad ? 1 : 0));
9175         deleteAndRecombine(Op);
9176         return true;
9177       }
9178     }
9179   }
9180
9181   return false;
9182 }
9183
9184 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9185 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9186   ISD::MemIndexedMode AM = LD->getAddressingMode();
9187   assert(AM != ISD::UNINDEXED);
9188   SDValue BP = LD->getOperand(1);
9189   SDValue Inc = LD->getOperand(2);
9190
9191   // Some backends use TargetConstants for load offsets, but don't expect
9192   // TargetConstants in general ADD nodes. We can convert these constants into
9193   // regular Constants (if the constant is not opaque).
9194   assert((Inc.getOpcode() != ISD::TargetConstant ||
9195           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9196          "Cannot split out indexing using opaque target constants");
9197   if (Inc.getOpcode() == ISD::TargetConstant) {
9198     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9199     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
9200                           ConstInc->getValueType(0));
9201   }
9202
9203   unsigned Opc =
9204       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9205   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9206 }
9207
9208 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9209   LoadSDNode *LD  = cast<LoadSDNode>(N);
9210   SDValue Chain = LD->getChain();
9211   SDValue Ptr   = LD->getBasePtr();
9212
9213   // If load is not volatile and there are no uses of the loaded value (and
9214   // the updated indexed value in case of indexed loads), change uses of the
9215   // chain value into uses of the chain input (i.e. delete the dead load).
9216   if (!LD->isVolatile()) {
9217     if (N->getValueType(1) == MVT::Other) {
9218       // Unindexed loads.
9219       if (!N->hasAnyUseOfValue(0)) {
9220         // It's not safe to use the two value CombineTo variant here. e.g.
9221         // v1, chain2 = load chain1, loc
9222         // v2, chain3 = load chain2, loc
9223         // v3         = add v2, c
9224         // Now we replace use of chain2 with chain1.  This makes the second load
9225         // isomorphic to the one we are deleting, and thus makes this load live.
9226         DEBUG(dbgs() << "\nReplacing.6 ";
9227               N->dump(&DAG);
9228               dbgs() << "\nWith chain: ";
9229               Chain.getNode()->dump(&DAG);
9230               dbgs() << "\n");
9231         WorklistRemover DeadNodes(*this);
9232         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9233
9234         if (N->use_empty())
9235           deleteAndRecombine(N);
9236
9237         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9238       }
9239     } else {
9240       // Indexed loads.
9241       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9242
9243       // If this load has an opaque TargetConstant offset, then we cannot split
9244       // the indexing into an add/sub directly (that TargetConstant may not be
9245       // valid for a different type of node, and we cannot convert an opaque
9246       // target constant into a regular constant).
9247       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9248                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9249
9250       if (!N->hasAnyUseOfValue(0) &&
9251           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9252         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9253         SDValue Index;
9254         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9255           Index = SplitIndexingFromLoad(LD);
9256           // Try to fold the base pointer arithmetic into subsequent loads and
9257           // stores.
9258           AddUsersToWorklist(N);
9259         } else
9260           Index = DAG.getUNDEF(N->getValueType(1));
9261         DEBUG(dbgs() << "\nReplacing.7 ";
9262               N->dump(&DAG);
9263               dbgs() << "\nWith: ";
9264               Undef.getNode()->dump(&DAG);
9265               dbgs() << " and 2 other values\n");
9266         WorklistRemover DeadNodes(*this);
9267         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9268         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9269         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9270         deleteAndRecombine(N);
9271         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9272       }
9273     }
9274   }
9275
9276   // If this load is directly stored, replace the load value with the stored
9277   // value.
9278   // TODO: Handle store large -> read small portion.
9279   // TODO: Handle TRUNCSTORE/LOADEXT
9280   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9281     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9282       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9283       if (PrevST->getBasePtr() == Ptr &&
9284           PrevST->getValue().getValueType() == N->getValueType(0))
9285       return CombineTo(N, Chain.getOperand(1), Chain);
9286     }
9287   }
9288
9289   // Try to infer better alignment information than the load already has.
9290   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9291     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9292       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9293         SDValue NewLoad =
9294                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9295                               LD->getValueType(0),
9296                               Chain, Ptr, LD->getPointerInfo(),
9297                               LD->getMemoryVT(),
9298                               LD->isVolatile(), LD->isNonTemporal(),
9299                               LD->isInvariant(), Align, LD->getAAInfo());
9300         if (NewLoad.getNode() != N)
9301           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9302       }
9303     }
9304   }
9305
9306   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9307                                                   : DAG.getSubtarget().useAA();
9308 #ifndef NDEBUG
9309   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9310       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9311     UseAA = false;
9312 #endif
9313   if (UseAA && LD->isUnindexed()) {
9314     // Walk up chain skipping non-aliasing memory nodes.
9315     SDValue BetterChain = FindBetterChain(N, Chain);
9316
9317     // If there is a better chain.
9318     if (Chain != BetterChain) {
9319       SDValue ReplLoad;
9320
9321       // Replace the chain to void dependency.
9322       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9323         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9324                                BetterChain, Ptr, LD->getMemOperand());
9325       } else {
9326         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9327                                   LD->getValueType(0),
9328                                   BetterChain, Ptr, LD->getMemoryVT(),
9329                                   LD->getMemOperand());
9330       }
9331
9332       // Create token factor to keep old chain connected.
9333       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9334                                   MVT::Other, Chain, ReplLoad.getValue(1));
9335
9336       // Make sure the new and old chains are cleaned up.
9337       AddToWorklist(Token.getNode());
9338
9339       // Replace uses with load result and token factor. Don't add users
9340       // to work list.
9341       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9342     }
9343   }
9344
9345   // Try transforming N to an indexed load.
9346   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9347     return SDValue(N, 0);
9348
9349   // Try to slice up N to more direct loads if the slices are mapped to
9350   // different register banks or pairing can take place.
9351   if (SliceUpLoad(N))
9352     return SDValue(N, 0);
9353
9354   return SDValue();
9355 }
9356
9357 namespace {
9358 /// \brief Helper structure used to slice a load in smaller loads.
9359 /// Basically a slice is obtained from the following sequence:
9360 /// Origin = load Ty1, Base
9361 /// Shift = srl Ty1 Origin, CstTy Amount
9362 /// Inst = trunc Shift to Ty2
9363 ///
9364 /// Then, it will be rewriten into:
9365 /// Slice = load SliceTy, Base + SliceOffset
9366 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9367 ///
9368 /// SliceTy is deduced from the number of bits that are actually used to
9369 /// build Inst.
9370 struct LoadedSlice {
9371   /// \brief Helper structure used to compute the cost of a slice.
9372   struct Cost {
9373     /// Are we optimizing for code size.
9374     bool ForCodeSize;
9375     /// Various cost.
9376     unsigned Loads;
9377     unsigned Truncates;
9378     unsigned CrossRegisterBanksCopies;
9379     unsigned ZExts;
9380     unsigned Shift;
9381
9382     Cost(bool ForCodeSize = false)
9383         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9384           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9385
9386     /// \brief Get the cost of one isolated slice.
9387     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9388         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9389           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9390       EVT TruncType = LS.Inst->getValueType(0);
9391       EVT LoadedType = LS.getLoadedType();
9392       if (TruncType != LoadedType &&
9393           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9394         ZExts = 1;
9395     }
9396
9397     /// \brief Account for slicing gain in the current cost.
9398     /// Slicing provide a few gains like removing a shift or a
9399     /// truncate. This method allows to grow the cost of the original
9400     /// load with the gain from this slice.
9401     void addSliceGain(const LoadedSlice &LS) {
9402       // Each slice saves a truncate.
9403       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9404       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9405                               LS.Inst->getOperand(0).getValueType()))
9406         ++Truncates;
9407       // If there is a shift amount, this slice gets rid of it.
9408       if (LS.Shift)
9409         ++Shift;
9410       // If this slice can merge a cross register bank copy, account for it.
9411       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9412         ++CrossRegisterBanksCopies;
9413     }
9414
9415     Cost &operator+=(const Cost &RHS) {
9416       Loads += RHS.Loads;
9417       Truncates += RHS.Truncates;
9418       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9419       ZExts += RHS.ZExts;
9420       Shift += RHS.Shift;
9421       return *this;
9422     }
9423
9424     bool operator==(const Cost &RHS) const {
9425       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9426              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9427              ZExts == RHS.ZExts && Shift == RHS.Shift;
9428     }
9429
9430     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9431
9432     bool operator<(const Cost &RHS) const {
9433       // Assume cross register banks copies are as expensive as loads.
9434       // FIXME: Do we want some more target hooks?
9435       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9436       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9437       // Unless we are optimizing for code size, consider the
9438       // expensive operation first.
9439       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9440         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9441       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9442              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9443     }
9444
9445     bool operator>(const Cost &RHS) const { return RHS < *this; }
9446
9447     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9448
9449     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9450   };
9451   // The last instruction that represent the slice. This should be a
9452   // truncate instruction.
9453   SDNode *Inst;
9454   // The original load instruction.
9455   LoadSDNode *Origin;
9456   // The right shift amount in bits from the original load.
9457   unsigned Shift;
9458   // The DAG from which Origin came from.
9459   // This is used to get some contextual information about legal types, etc.
9460   SelectionDAG *DAG;
9461
9462   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9463               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9464       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9465
9466   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9467   /// \return Result is \p BitWidth and has used bits set to 1 and
9468   ///         not used bits set to 0.
9469   APInt getUsedBits() const {
9470     // Reproduce the trunc(lshr) sequence:
9471     // - Start from the truncated value.
9472     // - Zero extend to the desired bit width.
9473     // - Shift left.
9474     assert(Origin && "No original load to compare against.");
9475     unsigned BitWidth = Origin->getValueSizeInBits(0);
9476     assert(Inst && "This slice is not bound to an instruction");
9477     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9478            "Extracted slice is bigger than the whole type!");
9479     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9480     UsedBits.setAllBits();
9481     UsedBits = UsedBits.zext(BitWidth);
9482     UsedBits <<= Shift;
9483     return UsedBits;
9484   }
9485
9486   /// \brief Get the size of the slice to be loaded in bytes.
9487   unsigned getLoadedSize() const {
9488     unsigned SliceSize = getUsedBits().countPopulation();
9489     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9490     return SliceSize / 8;
9491   }
9492
9493   /// \brief Get the type that will be loaded for this slice.
9494   /// Note: This may not be the final type for the slice.
9495   EVT getLoadedType() const {
9496     assert(DAG && "Missing context");
9497     LLVMContext &Ctxt = *DAG->getContext();
9498     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9499   }
9500
9501   /// \brief Get the alignment of the load used for this slice.
9502   unsigned getAlignment() const {
9503     unsigned Alignment = Origin->getAlignment();
9504     unsigned Offset = getOffsetFromBase();
9505     if (Offset != 0)
9506       Alignment = MinAlign(Alignment, Alignment + Offset);
9507     return Alignment;
9508   }
9509
9510   /// \brief Check if this slice can be rewritten with legal operations.
9511   bool isLegal() const {
9512     // An invalid slice is not legal.
9513     if (!Origin || !Inst || !DAG)
9514       return false;
9515
9516     // Offsets are for indexed load only, we do not handle that.
9517     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9518       return false;
9519
9520     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9521
9522     // Check that the type is legal.
9523     EVT SliceType = getLoadedType();
9524     if (!TLI.isTypeLegal(SliceType))
9525       return false;
9526
9527     // Check that the load is legal for this type.
9528     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9529       return false;
9530
9531     // Check that the offset can be computed.
9532     // 1. Check its type.
9533     EVT PtrType = Origin->getBasePtr().getValueType();
9534     if (PtrType == MVT::Untyped || PtrType.isExtended())
9535       return false;
9536
9537     // 2. Check that it fits in the immediate.
9538     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9539       return false;
9540
9541     // 3. Check that the computation is legal.
9542     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9543       return false;
9544
9545     // Check that the zext is legal if it needs one.
9546     EVT TruncateType = Inst->getValueType(0);
9547     if (TruncateType != SliceType &&
9548         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9549       return false;
9550
9551     return true;
9552   }
9553
9554   /// \brief Get the offset in bytes of this slice in the original chunk of
9555   /// bits.
9556   /// \pre DAG != nullptr.
9557   uint64_t getOffsetFromBase() const {
9558     assert(DAG && "Missing context.");
9559     bool IsBigEndian =
9560         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9561     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9562     uint64_t Offset = Shift / 8;
9563     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9564     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9565            "The size of the original loaded type is not a multiple of a"
9566            " byte.");
9567     // If Offset is bigger than TySizeInBytes, it means we are loading all
9568     // zeros. This should have been optimized before in the process.
9569     assert(TySizeInBytes > Offset &&
9570            "Invalid shift amount for given loaded size");
9571     if (IsBigEndian)
9572       Offset = TySizeInBytes - Offset - getLoadedSize();
9573     return Offset;
9574   }
9575
9576   /// \brief Generate the sequence of instructions to load the slice
9577   /// represented by this object and redirect the uses of this slice to
9578   /// this new sequence of instructions.
9579   /// \pre this->Inst && this->Origin are valid Instructions and this
9580   /// object passed the legal check: LoadedSlice::isLegal returned true.
9581   /// \return The last instruction of the sequence used to load the slice.
9582   SDValue loadSlice() const {
9583     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9584     const SDValue &OldBaseAddr = Origin->getBasePtr();
9585     SDValue BaseAddr = OldBaseAddr;
9586     // Get the offset in that chunk of bytes w.r.t. the endianess.
9587     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9588     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9589     if (Offset) {
9590       // BaseAddr = BaseAddr + Offset.
9591       EVT ArithType = BaseAddr.getValueType();
9592       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9593                               DAG->getConstant(Offset, ArithType));
9594     }
9595
9596     // Create the type of the loaded slice according to its size.
9597     EVT SliceType = getLoadedType();
9598
9599     // Create the load for the slice.
9600     SDValue LastInst = DAG->getLoad(
9601         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9602         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9603         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9604     // If the final type is not the same as the loaded type, this means that
9605     // we have to pad with zero. Create a zero extend for that.
9606     EVT FinalType = Inst->getValueType(0);
9607     if (SliceType != FinalType)
9608       LastInst =
9609           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9610     return LastInst;
9611   }
9612
9613   /// \brief Check if this slice can be merged with an expensive cross register
9614   /// bank copy. E.g.,
9615   /// i = load i32
9616   /// f = bitcast i32 i to float
9617   bool canMergeExpensiveCrossRegisterBankCopy() const {
9618     if (!Inst || !Inst->hasOneUse())
9619       return false;
9620     SDNode *Use = *Inst->use_begin();
9621     if (Use->getOpcode() != ISD::BITCAST)
9622       return false;
9623     assert(DAG && "Missing context");
9624     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9625     EVT ResVT = Use->getValueType(0);
9626     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9627     const TargetRegisterClass *ArgRC =
9628         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9629     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9630       return false;
9631
9632     // At this point, we know that we perform a cross-register-bank copy.
9633     // Check if it is expensive.
9634     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9635     // Assume bitcasts are cheap, unless both register classes do not
9636     // explicitly share a common sub class.
9637     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9638       return false;
9639
9640     // Check if it will be merged with the load.
9641     // 1. Check the alignment constraint.
9642     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9643         ResVT.getTypeForEVT(*DAG->getContext()));
9644
9645     if (RequiredAlignment > getAlignment())
9646       return false;
9647
9648     // 2. Check that the load is a legal operation for that type.
9649     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9650       return false;
9651
9652     // 3. Check that we do not have a zext in the way.
9653     if (Inst->getValueType(0) != getLoadedType())
9654       return false;
9655
9656     return true;
9657   }
9658 };
9659 }
9660
9661 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9662 /// \p UsedBits looks like 0..0 1..1 0..0.
9663 static bool areUsedBitsDense(const APInt &UsedBits) {
9664   // If all the bits are one, this is dense!
9665   if (UsedBits.isAllOnesValue())
9666     return true;
9667
9668   // Get rid of the unused bits on the right.
9669   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9670   // Get rid of the unused bits on the left.
9671   if (NarrowedUsedBits.countLeadingZeros())
9672     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9673   // Check that the chunk of bits is completely used.
9674   return NarrowedUsedBits.isAllOnesValue();
9675 }
9676
9677 /// \brief Check whether or not \p First and \p Second are next to each other
9678 /// in memory. This means that there is no hole between the bits loaded
9679 /// by \p First and the bits loaded by \p Second.
9680 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9681                                      const LoadedSlice &Second) {
9682   assert(First.Origin == Second.Origin && First.Origin &&
9683          "Unable to match different memory origins.");
9684   APInt UsedBits = First.getUsedBits();
9685   assert((UsedBits & Second.getUsedBits()) == 0 &&
9686          "Slices are not supposed to overlap.");
9687   UsedBits |= Second.getUsedBits();
9688   return areUsedBitsDense(UsedBits);
9689 }
9690
9691 /// \brief Adjust the \p GlobalLSCost according to the target
9692 /// paring capabilities and the layout of the slices.
9693 /// \pre \p GlobalLSCost should account for at least as many loads as
9694 /// there is in the slices in \p LoadedSlices.
9695 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9696                                  LoadedSlice::Cost &GlobalLSCost) {
9697   unsigned NumberOfSlices = LoadedSlices.size();
9698   // If there is less than 2 elements, no pairing is possible.
9699   if (NumberOfSlices < 2)
9700     return;
9701
9702   // Sort the slices so that elements that are likely to be next to each
9703   // other in memory are next to each other in the list.
9704   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9705             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9706     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9707     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9708   });
9709   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9710   // First (resp. Second) is the first (resp. Second) potentially candidate
9711   // to be placed in a paired load.
9712   const LoadedSlice *First = nullptr;
9713   const LoadedSlice *Second = nullptr;
9714   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9715                 // Set the beginning of the pair.
9716                                                            First = Second) {
9717
9718     Second = &LoadedSlices[CurrSlice];
9719
9720     // If First is NULL, it means we start a new pair.
9721     // Get to the next slice.
9722     if (!First)
9723       continue;
9724
9725     EVT LoadedType = First->getLoadedType();
9726
9727     // If the types of the slices are different, we cannot pair them.
9728     if (LoadedType != Second->getLoadedType())
9729       continue;
9730
9731     // Check if the target supplies paired loads for this type.
9732     unsigned RequiredAlignment = 0;
9733     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9734       // move to the next pair, this type is hopeless.
9735       Second = nullptr;
9736       continue;
9737     }
9738     // Check if we meet the alignment requirement.
9739     if (RequiredAlignment > First->getAlignment())
9740       continue;
9741
9742     // Check that both loads are next to each other in memory.
9743     if (!areSlicesNextToEachOther(*First, *Second))
9744       continue;
9745
9746     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9747     --GlobalLSCost.Loads;
9748     // Move to the next pair.
9749     Second = nullptr;
9750   }
9751 }
9752
9753 /// \brief Check the profitability of all involved LoadedSlice.
9754 /// Currently, it is considered profitable if there is exactly two
9755 /// involved slices (1) which are (2) next to each other in memory, and
9756 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9757 ///
9758 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9759 /// the elements themselves.
9760 ///
9761 /// FIXME: When the cost model will be mature enough, we can relax
9762 /// constraints (1) and (2).
9763 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9764                                 const APInt &UsedBits, bool ForCodeSize) {
9765   unsigned NumberOfSlices = LoadedSlices.size();
9766   if (StressLoadSlicing)
9767     return NumberOfSlices > 1;
9768
9769   // Check (1).
9770   if (NumberOfSlices != 2)
9771     return false;
9772
9773   // Check (2).
9774   if (!areUsedBitsDense(UsedBits))
9775     return false;
9776
9777   // Check (3).
9778   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9779   // The original code has one big load.
9780   OrigCost.Loads = 1;
9781   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9782     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9783     // Accumulate the cost of all the slices.
9784     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9785     GlobalSlicingCost += SliceCost;
9786
9787     // Account as cost in the original configuration the gain obtained
9788     // with the current slices.
9789     OrigCost.addSliceGain(LS);
9790   }
9791
9792   // If the target supports paired load, adjust the cost accordingly.
9793   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9794   return OrigCost > GlobalSlicingCost;
9795 }
9796
9797 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9798 /// operations, split it in the various pieces being extracted.
9799 ///
9800 /// This sort of thing is introduced by SROA.
9801 /// This slicing takes care not to insert overlapping loads.
9802 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9803 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9804   if (Level < AfterLegalizeDAG)
9805     return false;
9806
9807   LoadSDNode *LD = cast<LoadSDNode>(N);
9808   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9809       !LD->getValueType(0).isInteger())
9810     return false;
9811
9812   // Keep track of already used bits to detect overlapping values.
9813   // In that case, we will just abort the transformation.
9814   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9815
9816   SmallVector<LoadedSlice, 4> LoadedSlices;
9817
9818   // Check if this load is used as several smaller chunks of bits.
9819   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9820   // of computation for each trunc.
9821   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9822        UI != UIEnd; ++UI) {
9823     // Skip the uses of the chain.
9824     if (UI.getUse().getResNo() != 0)
9825       continue;
9826
9827     SDNode *User = *UI;
9828     unsigned Shift = 0;
9829
9830     // Check if this is a trunc(lshr).
9831     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9832         isa<ConstantSDNode>(User->getOperand(1))) {
9833       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9834       User = *User->use_begin();
9835     }
9836
9837     // At this point, User is a Truncate, iff we encountered, trunc or
9838     // trunc(lshr).
9839     if (User->getOpcode() != ISD::TRUNCATE)
9840       return false;
9841
9842     // The width of the type must be a power of 2 and greater than 8-bits.
9843     // Otherwise the load cannot be represented in LLVM IR.
9844     // Moreover, if we shifted with a non-8-bits multiple, the slice
9845     // will be across several bytes. We do not support that.
9846     unsigned Width = User->getValueSizeInBits(0);
9847     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9848       return 0;
9849
9850     // Build the slice for this chain of computations.
9851     LoadedSlice LS(User, LD, Shift, &DAG);
9852     APInt CurrentUsedBits = LS.getUsedBits();
9853
9854     // Check if this slice overlaps with another.
9855     if ((CurrentUsedBits & UsedBits) != 0)
9856       return false;
9857     // Update the bits used globally.
9858     UsedBits |= CurrentUsedBits;
9859
9860     // Check if the new slice would be legal.
9861     if (!LS.isLegal())
9862       return false;
9863
9864     // Record the slice.
9865     LoadedSlices.push_back(LS);
9866   }
9867
9868   // Abort slicing if it does not seem to be profitable.
9869   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9870     return false;
9871
9872   ++SlicedLoads;
9873
9874   // Rewrite each chain to use an independent load.
9875   // By construction, each chain can be represented by a unique load.
9876
9877   // Prepare the argument for the new token factor for all the slices.
9878   SmallVector<SDValue, 8> ArgChains;
9879   for (SmallVectorImpl<LoadedSlice>::const_iterator
9880            LSIt = LoadedSlices.begin(),
9881            LSItEnd = LoadedSlices.end();
9882        LSIt != LSItEnd; ++LSIt) {
9883     SDValue SliceInst = LSIt->loadSlice();
9884     CombineTo(LSIt->Inst, SliceInst, true);
9885     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9886       SliceInst = SliceInst.getOperand(0);
9887     assert(SliceInst->getOpcode() == ISD::LOAD &&
9888            "It takes more than a zext to get to the loaded slice!!");
9889     ArgChains.push_back(SliceInst.getValue(1));
9890   }
9891
9892   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9893                               ArgChains);
9894   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9895   return true;
9896 }
9897
9898 /// Check to see if V is (and load (ptr), imm), where the load is having
9899 /// specific bytes cleared out.  If so, return the byte size being masked out
9900 /// and the shift amount.
9901 static std::pair<unsigned, unsigned>
9902 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9903   std::pair<unsigned, unsigned> Result(0, 0);
9904
9905   // Check for the structure we're looking for.
9906   if (V->getOpcode() != ISD::AND ||
9907       !isa<ConstantSDNode>(V->getOperand(1)) ||
9908       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9909     return Result;
9910
9911   // Check the chain and pointer.
9912   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9913   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9914
9915   // The store should be chained directly to the load or be an operand of a
9916   // tokenfactor.
9917   if (LD == Chain.getNode())
9918     ; // ok.
9919   else if (Chain->getOpcode() != ISD::TokenFactor)
9920     return Result; // Fail.
9921   else {
9922     bool isOk = false;
9923     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9924       if (Chain->getOperand(i).getNode() == LD) {
9925         isOk = true;
9926         break;
9927       }
9928     if (!isOk) return Result;
9929   }
9930
9931   // This only handles simple types.
9932   if (V.getValueType() != MVT::i16 &&
9933       V.getValueType() != MVT::i32 &&
9934       V.getValueType() != MVT::i64)
9935     return Result;
9936
9937   // Check the constant mask.  Invert it so that the bits being masked out are
9938   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9939   // follow the sign bit for uniformity.
9940   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9941   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9942   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9943   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9944   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9945   if (NotMaskLZ == 64) return Result;  // All zero mask.
9946
9947   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9948   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9949     return Result;
9950
9951   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9952   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9953     NotMaskLZ -= 64-V.getValueSizeInBits();
9954
9955   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9956   switch (MaskedBytes) {
9957   case 1:
9958   case 2:
9959   case 4: break;
9960   default: return Result; // All one mask, or 5-byte mask.
9961   }
9962
9963   // Verify that the first bit starts at a multiple of mask so that the access
9964   // is aligned the same as the access width.
9965   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9966
9967   Result.first = MaskedBytes;
9968   Result.second = NotMaskTZ/8;
9969   return Result;
9970 }
9971
9972
9973 /// Check to see if IVal is something that provides a value as specified by
9974 /// MaskInfo. If so, replace the specified store with a narrower store of
9975 /// truncated IVal.
9976 static SDNode *
9977 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9978                                 SDValue IVal, StoreSDNode *St,
9979                                 DAGCombiner *DC) {
9980   unsigned NumBytes = MaskInfo.first;
9981   unsigned ByteShift = MaskInfo.second;
9982   SelectionDAG &DAG = DC->getDAG();
9983
9984   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9985   // that uses this.  If not, this is not a replacement.
9986   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9987                                   ByteShift*8, (ByteShift+NumBytes)*8);
9988   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9989
9990   // Check that it is legal on the target to do this.  It is legal if the new
9991   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9992   // legalization.
9993   MVT VT = MVT::getIntegerVT(NumBytes*8);
9994   if (!DC->isTypeLegal(VT))
9995     return nullptr;
9996
9997   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9998   // shifted by ByteShift and truncated down to NumBytes.
9999   if (ByteShift)
10000     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
10001                        DAG.getConstant(ByteShift*8,
10002                                     DC->getShiftAmountTy(IVal.getValueType())));
10003
10004   // Figure out the offset for the store and the alignment of the access.
10005   unsigned StOffset;
10006   unsigned NewAlign = St->getAlignment();
10007
10008   if (DAG.getTargetLoweringInfo().isLittleEndian())
10009     StOffset = ByteShift;
10010   else
10011     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10012
10013   SDValue Ptr = St->getBasePtr();
10014   if (StOffset) {
10015     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
10016                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
10017     NewAlign = MinAlign(NewAlign, StOffset);
10018   }
10019
10020   // Truncate down to the new size.
10021   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10022
10023   ++OpsNarrowed;
10024   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10025                       St->getPointerInfo().getWithOffset(StOffset),
10026                       false, false, NewAlign).getNode();
10027 }
10028
10029
10030 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10031 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10032 /// narrowing the load and store if it would end up being a win for performance
10033 /// or code size.
10034 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10035   StoreSDNode *ST  = cast<StoreSDNode>(N);
10036   if (ST->isVolatile())
10037     return SDValue();
10038
10039   SDValue Chain = ST->getChain();
10040   SDValue Value = ST->getValue();
10041   SDValue Ptr   = ST->getBasePtr();
10042   EVT VT = Value.getValueType();
10043
10044   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10045     return SDValue();
10046
10047   unsigned Opc = Value.getOpcode();
10048
10049   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10050   // is a byte mask indicating a consecutive number of bytes, check to see if
10051   // Y is known to provide just those bytes.  If so, we try to replace the
10052   // load + replace + store sequence with a single (narrower) store, which makes
10053   // the load dead.
10054   if (Opc == ISD::OR) {
10055     std::pair<unsigned, unsigned> MaskedLoad;
10056     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10057     if (MaskedLoad.first)
10058       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10059                                                   Value.getOperand(1), ST,this))
10060         return SDValue(NewST, 0);
10061
10062     // Or is commutative, so try swapping X and Y.
10063     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10064     if (MaskedLoad.first)
10065       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10066                                                   Value.getOperand(0), ST,this))
10067         return SDValue(NewST, 0);
10068   }
10069
10070   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10071       Value.getOperand(1).getOpcode() != ISD::Constant)
10072     return SDValue();
10073
10074   SDValue N0 = Value.getOperand(0);
10075   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10076       Chain == SDValue(N0.getNode(), 1)) {
10077     LoadSDNode *LD = cast<LoadSDNode>(N0);
10078     if (LD->getBasePtr() != Ptr ||
10079         LD->getPointerInfo().getAddrSpace() !=
10080         ST->getPointerInfo().getAddrSpace())
10081       return SDValue();
10082
10083     // Find the type to narrow it the load / op / store to.
10084     SDValue N1 = Value.getOperand(1);
10085     unsigned BitWidth = N1.getValueSizeInBits();
10086     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10087     if (Opc == ISD::AND)
10088       Imm ^= APInt::getAllOnesValue(BitWidth);
10089     if (Imm == 0 || Imm.isAllOnesValue())
10090       return SDValue();
10091     unsigned ShAmt = Imm.countTrailingZeros();
10092     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10093     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10094     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10095     // The narrowing should be profitable, the load/store operation should be
10096     // legal (or custom) and the store size should be equal to the NewVT width.
10097     while (NewBW < BitWidth &&
10098            (NewVT.getStoreSizeInBits() != NewBW ||
10099             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10100             !TLI.isNarrowingProfitable(VT, NewVT))) {
10101       NewBW = NextPowerOf2(NewBW);
10102       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10103     }
10104     if (NewBW >= BitWidth)
10105       return SDValue();
10106
10107     // If the lsb changed does not start at the type bitwidth boundary,
10108     // start at the previous one.
10109     if (ShAmt % NewBW)
10110       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10111     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10112                                    std::min(BitWidth, ShAmt + NewBW));
10113     if ((Imm & Mask) == Imm) {
10114       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10115       if (Opc == ISD::AND)
10116         NewImm ^= APInt::getAllOnesValue(NewBW);
10117       uint64_t PtrOff = ShAmt / 8;
10118       // For big endian targets, we need to adjust the offset to the pointer to
10119       // load the correct bytes.
10120       if (TLI.isBigEndian())
10121         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10122
10123       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10124       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10125       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10126         return SDValue();
10127
10128       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10129                                    Ptr.getValueType(), Ptr,
10130                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
10131       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10132                                   LD->getChain(), NewPtr,
10133                                   LD->getPointerInfo().getWithOffset(PtrOff),
10134                                   LD->isVolatile(), LD->isNonTemporal(),
10135                                   LD->isInvariant(), NewAlign,
10136                                   LD->getAAInfo());
10137       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10138                                    DAG.getConstant(NewImm, NewVT));
10139       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10140                                    NewVal, NewPtr,
10141                                    ST->getPointerInfo().getWithOffset(PtrOff),
10142                                    false, false, NewAlign);
10143
10144       AddToWorklist(NewPtr.getNode());
10145       AddToWorklist(NewLD.getNode());
10146       AddToWorklist(NewVal.getNode());
10147       WorklistRemover DeadNodes(*this);
10148       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10149       ++OpsNarrowed;
10150       return NewST;
10151     }
10152   }
10153
10154   return SDValue();
10155 }
10156
10157 /// For a given floating point load / store pair, if the load value isn't used
10158 /// by any other operations, then consider transforming the pair to integer
10159 /// load / store operations if the target deems the transformation profitable.
10160 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10161   StoreSDNode *ST  = cast<StoreSDNode>(N);
10162   SDValue Chain = ST->getChain();
10163   SDValue Value = ST->getValue();
10164   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10165       Value.hasOneUse() &&
10166       Chain == SDValue(Value.getNode(), 1)) {
10167     LoadSDNode *LD = cast<LoadSDNode>(Value);
10168     EVT VT = LD->getMemoryVT();
10169     if (!VT.isFloatingPoint() ||
10170         VT != ST->getMemoryVT() ||
10171         LD->isNonTemporal() ||
10172         ST->isNonTemporal() ||
10173         LD->getPointerInfo().getAddrSpace() != 0 ||
10174         ST->getPointerInfo().getAddrSpace() != 0)
10175       return SDValue();
10176
10177     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10178     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10179         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10180         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10181         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10182       return SDValue();
10183
10184     unsigned LDAlign = LD->getAlignment();
10185     unsigned STAlign = ST->getAlignment();
10186     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10187     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10188     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10189       return SDValue();
10190
10191     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10192                                 LD->getChain(), LD->getBasePtr(),
10193                                 LD->getPointerInfo(),
10194                                 false, false, false, LDAlign);
10195
10196     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10197                                  NewLD, ST->getBasePtr(),
10198                                  ST->getPointerInfo(),
10199                                  false, false, STAlign);
10200
10201     AddToWorklist(NewLD.getNode());
10202     AddToWorklist(NewST.getNode());
10203     WorklistRemover DeadNodes(*this);
10204     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10205     ++LdStFP2Int;
10206     return NewST;
10207   }
10208
10209   return SDValue();
10210 }
10211
10212 namespace {
10213 /// Helper struct to parse and store a memory address as base + index + offset.
10214 /// We ignore sign extensions when it is safe to do so.
10215 /// The following two expressions are not equivalent. To differentiate we need
10216 /// to store whether there was a sign extension involved in the index
10217 /// computation.
10218 ///  (load (i64 add (i64 copyfromreg %c)
10219 ///                 (i64 signextend (add (i8 load %index)
10220 ///                                      (i8 1))))
10221 /// vs
10222 ///
10223 /// (load (i64 add (i64 copyfromreg %c)
10224 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10225 ///                                         (i32 1)))))
10226 struct BaseIndexOffset {
10227   SDValue Base;
10228   SDValue Index;
10229   int64_t Offset;
10230   bool IsIndexSignExt;
10231
10232   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10233
10234   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10235                   bool IsIndexSignExt) :
10236     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10237
10238   bool equalBaseIndex(const BaseIndexOffset &Other) {
10239     return Other.Base == Base && Other.Index == Index &&
10240       Other.IsIndexSignExt == IsIndexSignExt;
10241   }
10242
10243   /// Parses tree in Ptr for base, index, offset addresses.
10244   static BaseIndexOffset match(SDValue Ptr) {
10245     bool IsIndexSignExt = false;
10246
10247     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10248     // instruction, then it could be just the BASE or everything else we don't
10249     // know how to handle. Just use Ptr as BASE and give up.
10250     if (Ptr->getOpcode() != ISD::ADD)
10251       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10252
10253     // We know that we have at least an ADD instruction. Try to pattern match
10254     // the simple case of BASE + OFFSET.
10255     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10256       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10257       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10258                               IsIndexSignExt);
10259     }
10260
10261     // Inside a loop the current BASE pointer is calculated using an ADD and a
10262     // MUL instruction. In this case Ptr is the actual BASE pointer.
10263     // (i64 add (i64 %array_ptr)
10264     //          (i64 mul (i64 %induction_var)
10265     //                   (i64 %element_size)))
10266     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10267       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10268
10269     // Look at Base + Index + Offset cases.
10270     SDValue Base = Ptr->getOperand(0);
10271     SDValue IndexOffset = Ptr->getOperand(1);
10272
10273     // Skip signextends.
10274     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10275       IndexOffset = IndexOffset->getOperand(0);
10276       IsIndexSignExt = true;
10277     }
10278
10279     // Either the case of Base + Index (no offset) or something else.
10280     if (IndexOffset->getOpcode() != ISD::ADD)
10281       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10282
10283     // Now we have the case of Base + Index + offset.
10284     SDValue Index = IndexOffset->getOperand(0);
10285     SDValue Offset = IndexOffset->getOperand(1);
10286
10287     if (!isa<ConstantSDNode>(Offset))
10288       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10289
10290     // Ignore signextends.
10291     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10292       Index = Index->getOperand(0);
10293       IsIndexSignExt = true;
10294     } else IsIndexSignExt = false;
10295
10296     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10297     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10298   }
10299 };
10300 } // namespace
10301
10302 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10303                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10304                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10305   // Make sure we have something to merge.
10306   if (NumElem < 2)
10307     return false;
10308
10309   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10310   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10311   unsigned LatestNodeUsed = 0;
10312
10313   for (unsigned i=0; i < NumElem; ++i) {
10314     // Find a chain for the new wide-store operand. Notice that some
10315     // of the store nodes that we found may not be selected for inclusion
10316     // in the wide store. The chain we use needs to be the chain of the
10317     // latest store node which is *used* and replaced by the wide store.
10318     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10319       LatestNodeUsed = i;
10320   }
10321
10322   // The latest Node in the DAG.
10323   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10324   SDLoc DL(StoreNodes[0].MemNode);
10325
10326   SDValue StoredVal;
10327   if (UseVector) {
10328     // Find a legal type for the vector store.
10329     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10330     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10331     if (IsConstantSrc) {
10332       // A vector store with a constant source implies that the constant is
10333       // zero; we only handle merging stores of constant zeros because the zero
10334       // can be materialized without a load.
10335       // It may be beneficial to loosen this restriction to allow non-zero
10336       // store merging.
10337       StoredVal = DAG.getConstant(0, Ty);
10338     } else {
10339       SmallVector<SDValue, 8> Ops;
10340       for (unsigned i = 0; i < NumElem ; ++i) {
10341         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10342         SDValue Val = St->getValue();
10343         // All of the operands of a BUILD_VECTOR must have the same type.
10344         if (Val.getValueType() != MemVT)
10345           return false;
10346         Ops.push_back(Val);
10347       }
10348
10349       // Build the extracted vector elements back into a vector.
10350       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10351     }
10352   } else {
10353     // We should always use a vector store when merging extracted vector
10354     // elements, so this path implies a store of constants.
10355     assert(IsConstantSrc && "Merged vector elements should use vector store");
10356
10357     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10358     APInt StoreInt(StoreBW, 0);
10359
10360     // Construct a single integer constant which is made of the smaller
10361     // constant inputs.
10362     bool IsLE = TLI.isLittleEndian();
10363     for (unsigned i = 0; i < NumElem ; ++i) {
10364       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10365       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10366       SDValue Val = St->getValue();
10367       StoreInt <<= ElementSizeBytes*8;
10368       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10369         StoreInt |= C->getAPIntValue().zext(StoreBW);
10370       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10371         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10372       } else {
10373         llvm_unreachable("Invalid constant element type");
10374       }
10375     }
10376
10377     // Create the new Load and Store operations.
10378     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10379     StoredVal = DAG.getConstant(StoreInt, StoreTy);
10380   }
10381
10382   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10383                                   FirstInChain->getBasePtr(),
10384                                   FirstInChain->getPointerInfo(),
10385                                   false, false,
10386                                   FirstInChain->getAlignment());
10387
10388   // Replace the last store with the new store
10389   CombineTo(LatestOp, NewStore);
10390   // Erase all other stores.
10391   for (unsigned i = 0; i < NumElem ; ++i) {
10392     if (StoreNodes[i].MemNode == LatestOp)
10393       continue;
10394     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10395     // ReplaceAllUsesWith will replace all uses that existed when it was
10396     // called, but graph optimizations may cause new ones to appear. For
10397     // example, the case in pr14333 looks like
10398     //
10399     //  St's chain -> St -> another store -> X
10400     //
10401     // And the only difference from St to the other store is the chain.
10402     // When we change it's chain to be St's chain they become identical,
10403     // get CSEed and the net result is that X is now a use of St.
10404     // Since we know that St is redundant, just iterate.
10405     while (!St->use_empty())
10406       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10407     deleteAndRecombine(St);
10408   }
10409
10410   return true;
10411 }
10412
10413 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10414   if (OptLevel == CodeGenOpt::None)
10415     return false;
10416
10417   EVT MemVT = St->getMemoryVT();
10418   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10419   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10420       Attribute::NoImplicitFloat);
10421
10422   // Don't merge vectors into wider inputs.
10423   if (MemVT.isVector() || !MemVT.isSimple())
10424     return false;
10425
10426   // Perform an early exit check. Do not bother looking at stored values that
10427   // are not constants, loads, or extracted vector elements.
10428   SDValue StoredVal = St->getValue();
10429   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10430   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10431                        isa<ConstantFPSDNode>(StoredVal);
10432   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10433
10434   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10435     return false;
10436
10437   // Only look at ends of store sequences.
10438   SDValue Chain = SDValue(St, 0);
10439   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10440     return false;
10441
10442   // This holds the base pointer, index, and the offset in bytes from the base
10443   // pointer.
10444   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10445
10446   // We must have a base and an offset.
10447   if (!BasePtr.Base.getNode())
10448     return false;
10449
10450   // Do not handle stores to undef base pointers.
10451   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10452     return false;
10453
10454   // Save the LoadSDNodes that we find in the chain.
10455   // We need to make sure that these nodes do not interfere with
10456   // any of the store nodes.
10457   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10458
10459   // Save the StoreSDNodes that we find in the chain.
10460   SmallVector<MemOpLink, 8> StoreNodes;
10461
10462   // Walk up the chain and look for nodes with offsets from the same
10463   // base pointer. Stop when reaching an instruction with a different kind
10464   // or instruction which has a different base pointer.
10465   unsigned Seq = 0;
10466   StoreSDNode *Index = St;
10467   while (Index) {
10468     // If the chain has more than one use, then we can't reorder the mem ops.
10469     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10470       break;
10471
10472     // Find the base pointer and offset for this memory node.
10473     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10474
10475     // Check that the base pointer is the same as the original one.
10476     if (!Ptr.equalBaseIndex(BasePtr))
10477       break;
10478
10479     // Check that the alignment is the same.
10480     if (Index->getAlignment() != St->getAlignment())
10481       break;
10482
10483     // The memory operands must not be volatile.
10484     if (Index->isVolatile() || Index->isIndexed())
10485       break;
10486
10487     // No truncation.
10488     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10489       if (St->isTruncatingStore())
10490         break;
10491
10492     // The stored memory type must be the same.
10493     if (Index->getMemoryVT() != MemVT)
10494       break;
10495
10496     // We do not allow unaligned stores because we want to prevent overriding
10497     // stores.
10498     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10499       break;
10500
10501     // We found a potential memory operand to merge.
10502     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10503
10504     // Find the next memory operand in the chain. If the next operand in the
10505     // chain is a store then move up and continue the scan with the next
10506     // memory operand. If the next operand is a load save it and use alias
10507     // information to check if it interferes with anything.
10508     SDNode *NextInChain = Index->getChain().getNode();
10509     while (1) {
10510       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10511         // We found a store node. Use it for the next iteration.
10512         Index = STn;
10513         break;
10514       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10515         if (Ldn->isVolatile()) {
10516           Index = nullptr;
10517           break;
10518         }
10519
10520         // Save the load node for later. Continue the scan.
10521         AliasLoadNodes.push_back(Ldn);
10522         NextInChain = Ldn->getChain().getNode();
10523         continue;
10524       } else {
10525         Index = nullptr;
10526         break;
10527       }
10528     }
10529   }
10530
10531   // Check if there is anything to merge.
10532   if (StoreNodes.size() < 2)
10533     return false;
10534
10535   // Sort the memory operands according to their distance from the base pointer.
10536   std::sort(StoreNodes.begin(), StoreNodes.end(),
10537             [](MemOpLink LHS, MemOpLink RHS) {
10538     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10539            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10540             LHS.SequenceNum > RHS.SequenceNum);
10541   });
10542
10543   // Scan the memory operations on the chain and find the first non-consecutive
10544   // store memory address.
10545   unsigned LastConsecutiveStore = 0;
10546   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10547   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10548
10549     // Check that the addresses are consecutive starting from the second
10550     // element in the list of stores.
10551     if (i > 0) {
10552       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10553       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10554         break;
10555     }
10556
10557     bool Alias = false;
10558     // Check if this store interferes with any of the loads that we found.
10559     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10560       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10561         Alias = true;
10562         break;
10563       }
10564     // We found a load that alias with this store. Stop the sequence.
10565     if (Alias)
10566       break;
10567
10568     // Mark this node as useful.
10569     LastConsecutiveStore = i;
10570   }
10571
10572   // The node with the lowest store address.
10573   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10574
10575   // Store the constants into memory as one consecutive store.
10576   if (IsConstantSrc) {
10577     unsigned LastLegalType = 0;
10578     unsigned LastLegalVectorType = 0;
10579     bool NonZero = false;
10580     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10581       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10582       SDValue StoredVal = St->getValue();
10583
10584       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10585         NonZero |= !C->isNullValue();
10586       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10587         NonZero |= !C->getConstantFPValue()->isNullValue();
10588       } else {
10589         // Non-constant.
10590         break;
10591       }
10592
10593       // Find a legal type for the constant store.
10594       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10595       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10596       if (TLI.isTypeLegal(StoreTy))
10597         LastLegalType = i+1;
10598       // Or check whether a truncstore is legal.
10599       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10600                TargetLowering::TypePromoteInteger) {
10601         EVT LegalizedStoredValueTy =
10602           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10603         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10604           LastLegalType = i+1;
10605       }
10606
10607       // Find a legal type for the vector store.
10608       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10609       if (TLI.isTypeLegal(Ty))
10610         LastLegalVectorType = i + 1;
10611     }
10612
10613     // We only use vectors if the constant is known to be zero and the
10614     // function is not marked with the noimplicitfloat attribute.
10615     if (NonZero || NoVectors)
10616       LastLegalVectorType = 0;
10617
10618     // Check if we found a legal integer type to store.
10619     if (LastLegalType == 0 && LastLegalVectorType == 0)
10620       return false;
10621
10622     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10623     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10624
10625     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10626                                            true, UseVector);
10627   }
10628
10629   // When extracting multiple vector elements, try to store them
10630   // in one vector store rather than a sequence of scalar stores.
10631   if (IsExtractVecEltSrc) {
10632     unsigned NumElem = 0;
10633     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10634       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10635       SDValue StoredVal = St->getValue();
10636       // This restriction could be loosened.
10637       // Bail out if any stored values are not elements extracted from a vector.
10638       // It should be possible to handle mixed sources, but load sources need
10639       // more careful handling (see the block of code below that handles
10640       // consecutive loads).
10641       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10642         return false;
10643
10644       // Find a legal type for the vector store.
10645       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10646       if (TLI.isTypeLegal(Ty))
10647         NumElem = i + 1;
10648     }
10649
10650     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10651                                            false, true);
10652   }
10653
10654   // Below we handle the case of multiple consecutive stores that
10655   // come from multiple consecutive loads. We merge them into a single
10656   // wide load and a single wide store.
10657
10658   // Look for load nodes which are used by the stored values.
10659   SmallVector<MemOpLink, 8> LoadNodes;
10660
10661   // Find acceptable loads. Loads need to have the same chain (token factor),
10662   // must not be zext, volatile, indexed, and they must be consecutive.
10663   BaseIndexOffset LdBasePtr;
10664   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10665     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10666     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10667     if (!Ld) break;
10668
10669     // Loads must only have one use.
10670     if (!Ld->hasNUsesOfValue(1, 0))
10671       break;
10672
10673     // Check that the alignment is the same as the stores.
10674     if (Ld->getAlignment() != St->getAlignment())
10675       break;
10676
10677     // The memory operands must not be volatile.
10678     if (Ld->isVolatile() || Ld->isIndexed())
10679       break;
10680
10681     // We do not accept ext loads.
10682     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10683       break;
10684
10685     // The stored memory type must be the same.
10686     if (Ld->getMemoryVT() != MemVT)
10687       break;
10688
10689     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10690     // If this is not the first ptr that we check.
10691     if (LdBasePtr.Base.getNode()) {
10692       // The base ptr must be the same.
10693       if (!LdPtr.equalBaseIndex(LdBasePtr))
10694         break;
10695     } else {
10696       // Check that all other base pointers are the same as this one.
10697       LdBasePtr = LdPtr;
10698     }
10699
10700     // We found a potential memory operand to merge.
10701     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10702   }
10703
10704   if (LoadNodes.size() < 2)
10705     return false;
10706
10707   // If we have load/store pair instructions and we only have two values,
10708   // don't bother.
10709   unsigned RequiredAlignment;
10710   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10711       St->getAlignment() >= RequiredAlignment)
10712     return false;
10713
10714   // Scan the memory operations on the chain and find the first non-consecutive
10715   // load memory address. These variables hold the index in the store node
10716   // array.
10717   unsigned LastConsecutiveLoad = 0;
10718   // This variable refers to the size and not index in the array.
10719   unsigned LastLegalVectorType = 0;
10720   unsigned LastLegalIntegerType = 0;
10721   StartAddress = LoadNodes[0].OffsetFromBase;
10722   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10723   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10724     // All loads much share the same chain.
10725     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10726       break;
10727
10728     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10729     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10730       break;
10731     LastConsecutiveLoad = i;
10732
10733     // Find a legal type for the vector store.
10734     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10735     if (TLI.isTypeLegal(StoreTy))
10736       LastLegalVectorType = i + 1;
10737
10738     // Find a legal type for the integer store.
10739     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10740     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10741     if (TLI.isTypeLegal(StoreTy))
10742       LastLegalIntegerType = i + 1;
10743     // Or check whether a truncstore and extload is legal.
10744     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10745              TargetLowering::TypePromoteInteger) {
10746       EVT LegalizedStoredValueTy =
10747         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10748       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10749           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10750           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10751           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10752         LastLegalIntegerType = i+1;
10753     }
10754   }
10755
10756   // Only use vector types if the vector type is larger than the integer type.
10757   // If they are the same, use integers.
10758   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10759   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10760
10761   // We add +1 here because the LastXXX variables refer to location while
10762   // the NumElem refers to array/index size.
10763   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10764   NumElem = std::min(LastLegalType, NumElem);
10765
10766   if (NumElem < 2)
10767     return false;
10768
10769   // The latest Node in the DAG.
10770   unsigned LatestNodeUsed = 0;
10771   for (unsigned i=1; i<NumElem; ++i) {
10772     // Find a chain for the new wide-store operand. Notice that some
10773     // of the store nodes that we found may not be selected for inclusion
10774     // in the wide store. The chain we use needs to be the chain of the
10775     // latest store node which is *used* and replaced by the wide store.
10776     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10777       LatestNodeUsed = i;
10778   }
10779
10780   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10781
10782   // Find if it is better to use vectors or integers to load and store
10783   // to memory.
10784   EVT JointMemOpVT;
10785   if (UseVectorTy) {
10786     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10787   } else {
10788     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10789     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10790   }
10791
10792   SDLoc LoadDL(LoadNodes[0].MemNode);
10793   SDLoc StoreDL(StoreNodes[0].MemNode);
10794
10795   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10796   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10797                                 FirstLoad->getChain(),
10798                                 FirstLoad->getBasePtr(),
10799                                 FirstLoad->getPointerInfo(),
10800                                 false, false, false,
10801                                 FirstLoad->getAlignment());
10802
10803   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10804                                   FirstInChain->getBasePtr(),
10805                                   FirstInChain->getPointerInfo(), false, false,
10806                                   FirstInChain->getAlignment());
10807
10808   // Replace one of the loads with the new load.
10809   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10810   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10811                                 SDValue(NewLoad.getNode(), 1));
10812
10813   // Remove the rest of the load chains.
10814   for (unsigned i = 1; i < NumElem ; ++i) {
10815     // Replace all chain users of the old load nodes with the chain of the new
10816     // load node.
10817     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10818     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10819   }
10820
10821   // Replace the last store with the new store.
10822   CombineTo(LatestOp, NewStore);
10823   // Erase all other stores.
10824   for (unsigned i = 0; i < NumElem ; ++i) {
10825     // Remove all Store nodes.
10826     if (StoreNodes[i].MemNode == LatestOp)
10827       continue;
10828     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10829     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10830     deleteAndRecombine(St);
10831   }
10832
10833   return true;
10834 }
10835
10836 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10837   StoreSDNode *ST  = cast<StoreSDNode>(N);
10838   SDValue Chain = ST->getChain();
10839   SDValue Value = ST->getValue();
10840   SDValue Ptr   = ST->getBasePtr();
10841
10842   // If this is a store of a bit convert, store the input value if the
10843   // resultant store does not need a higher alignment than the original.
10844   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10845       ST->isUnindexed()) {
10846     unsigned OrigAlign = ST->getAlignment();
10847     EVT SVT = Value.getOperand(0).getValueType();
10848     unsigned Align = TLI.getDataLayout()->
10849       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10850     if (Align <= OrigAlign &&
10851         ((!LegalOperations && !ST->isVolatile()) ||
10852          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10853       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10854                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10855                           ST->isNonTemporal(), OrigAlign,
10856                           ST->getAAInfo());
10857   }
10858
10859   // Turn 'store undef, Ptr' -> nothing.
10860   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10861     return Chain;
10862
10863   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10864   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10865     // NOTE: If the original store is volatile, this transform must not increase
10866     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10867     // processor operation but an i64 (which is not legal) requires two.  So the
10868     // transform should not be done in this case.
10869     if (Value.getOpcode() != ISD::TargetConstantFP) {
10870       SDValue Tmp;
10871       switch (CFP->getSimpleValueType(0).SimpleTy) {
10872       default: llvm_unreachable("Unknown FP type");
10873       case MVT::f16:    // We don't do this for these yet.
10874       case MVT::f80:
10875       case MVT::f128:
10876       case MVT::ppcf128:
10877         break;
10878       case MVT::f32:
10879         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10880             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10881           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10882                               bitcastToAPInt().getZExtValue(), MVT::i32);
10883           return DAG.getStore(Chain, SDLoc(N), Tmp,
10884                               Ptr, ST->getMemOperand());
10885         }
10886         break;
10887       case MVT::f64:
10888         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10889              !ST->isVolatile()) ||
10890             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10891           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10892                                 getZExtValue(), MVT::i64);
10893           return DAG.getStore(Chain, SDLoc(N), Tmp,
10894                               Ptr, ST->getMemOperand());
10895         }
10896
10897         if (!ST->isVolatile() &&
10898             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10899           // Many FP stores are not made apparent until after legalize, e.g. for
10900           // argument passing.  Since this is so common, custom legalize the
10901           // 64-bit integer store into two 32-bit stores.
10902           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10903           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10904           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10905           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10906
10907           unsigned Alignment = ST->getAlignment();
10908           bool isVolatile = ST->isVolatile();
10909           bool isNonTemporal = ST->isNonTemporal();
10910           AAMDNodes AAInfo = ST->getAAInfo();
10911
10912           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10913                                      Ptr, ST->getPointerInfo(),
10914                                      isVolatile, isNonTemporal,
10915                                      ST->getAlignment(), AAInfo);
10916           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10917                             DAG.getConstant(4, Ptr.getValueType()));
10918           Alignment = MinAlign(Alignment, 4U);
10919           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10920                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10921                                      isVolatile, isNonTemporal,
10922                                      Alignment, AAInfo);
10923           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10924                              St0, St1);
10925         }
10926
10927         break;
10928       }
10929     }
10930   }
10931
10932   // Try to infer better alignment information than the store already has.
10933   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10934     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10935       if (Align > ST->getAlignment()) {
10936         SDValue NewStore =
10937                DAG.getTruncStore(Chain, SDLoc(N), Value,
10938                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10939                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10940                                  ST->getAAInfo());
10941         if (NewStore.getNode() != N)
10942           return CombineTo(ST, NewStore, true);
10943       }
10944     }
10945   }
10946
10947   // Try transforming a pair floating point load / store ops to integer
10948   // load / store ops.
10949   SDValue NewST = TransformFPLoadStorePair(N);
10950   if (NewST.getNode())
10951     return NewST;
10952
10953   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10954                                                   : DAG.getSubtarget().useAA();
10955 #ifndef NDEBUG
10956   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10957       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10958     UseAA = false;
10959 #endif
10960   if (UseAA && ST->isUnindexed()) {
10961     // Walk up chain skipping non-aliasing memory nodes.
10962     SDValue BetterChain = FindBetterChain(N, Chain);
10963
10964     // If there is a better chain.
10965     if (Chain != BetterChain) {
10966       SDValue ReplStore;
10967
10968       // Replace the chain to avoid dependency.
10969       if (ST->isTruncatingStore()) {
10970         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10971                                       ST->getMemoryVT(), ST->getMemOperand());
10972       } else {
10973         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10974                                  ST->getMemOperand());
10975       }
10976
10977       // Create token to keep both nodes around.
10978       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10979                                   MVT::Other, Chain, ReplStore);
10980
10981       // Make sure the new and old chains are cleaned up.
10982       AddToWorklist(Token.getNode());
10983
10984       // Don't add users to work list.
10985       return CombineTo(N, Token, false);
10986     }
10987   }
10988
10989   // Try transforming N to an indexed store.
10990   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10991     return SDValue(N, 0);
10992
10993   // FIXME: is there such a thing as a truncating indexed store?
10994   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10995       Value.getValueType().isInteger()) {
10996     // See if we can simplify the input to this truncstore with knowledge that
10997     // only the low bits are being used.  For example:
10998     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10999     SDValue Shorter =
11000       GetDemandedBits(Value,
11001                       APInt::getLowBitsSet(
11002                         Value.getValueType().getScalarType().getSizeInBits(),
11003                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11004     AddToWorklist(Value.getNode());
11005     if (Shorter.getNode())
11006       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11007                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11008
11009     // Otherwise, see if we can simplify the operation with
11010     // SimplifyDemandedBits, which only works if the value has a single use.
11011     if (SimplifyDemandedBits(Value,
11012                         APInt::getLowBitsSet(
11013                           Value.getValueType().getScalarType().getSizeInBits(),
11014                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11015       return SDValue(N, 0);
11016   }
11017
11018   // If this is a load followed by a store to the same location, then the store
11019   // is dead/noop.
11020   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11021     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11022         ST->isUnindexed() && !ST->isVolatile() &&
11023         // There can't be any side effects between the load and store, such as
11024         // a call or store.
11025         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11026       // The store is dead, remove it.
11027       return Chain;
11028     }
11029   }
11030
11031   // If this is a store followed by a store with the same value to the same
11032   // location, then the store is dead/noop.
11033   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11034     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11035         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11036         ST1->isUnindexed() && !ST1->isVolatile()) {
11037       // The store is dead, remove it.
11038       return Chain;
11039     }
11040   }
11041
11042   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11043   // truncating store.  We can do this even if this is already a truncstore.
11044   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11045       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11046       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11047                             ST->getMemoryVT())) {
11048     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11049                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11050   }
11051
11052   // Only perform this optimization before the types are legal, because we
11053   // don't want to perform this optimization on every DAGCombine invocation.
11054   if (!LegalTypes) {
11055     bool EverChanged = false;
11056
11057     do {
11058       // There can be multiple store sequences on the same chain.
11059       // Keep trying to merge store sequences until we are unable to do so
11060       // or until we merge the last store on the chain.
11061       bool Changed = MergeConsecutiveStores(ST);
11062       EverChanged |= Changed;
11063       if (!Changed) break;
11064     } while (ST->getOpcode() != ISD::DELETED_NODE);
11065
11066     if (EverChanged)
11067       return SDValue(N, 0);
11068   }
11069
11070   return ReduceLoadOpStoreWidth(N);
11071 }
11072
11073 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11074   SDValue InVec = N->getOperand(0);
11075   SDValue InVal = N->getOperand(1);
11076   SDValue EltNo = N->getOperand(2);
11077   SDLoc dl(N);
11078
11079   // If the inserted element is an UNDEF, just use the input vector.
11080   if (InVal.getOpcode() == ISD::UNDEF)
11081     return InVec;
11082
11083   EVT VT = InVec.getValueType();
11084
11085   // If we can't generate a legal BUILD_VECTOR, exit
11086   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11087     return SDValue();
11088
11089   // Check that we know which element is being inserted
11090   if (!isa<ConstantSDNode>(EltNo))
11091     return SDValue();
11092   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11093
11094   // Canonicalize insert_vector_elt dag nodes.
11095   // Example:
11096   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11097   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11098   //
11099   // Do this only if the child insert_vector node has one use; also
11100   // do this only if indices are both constants and Idx1 < Idx0.
11101   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11102       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11103     unsigned OtherElt =
11104       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11105     if (Elt < OtherElt) {
11106       // Swap nodes.
11107       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11108                                   InVec.getOperand(0), InVal, EltNo);
11109       AddToWorklist(NewOp.getNode());
11110       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11111                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11112     }
11113   }
11114
11115   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11116   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11117   // vector elements.
11118   SmallVector<SDValue, 8> Ops;
11119   // Do not combine these two vectors if the output vector will not replace
11120   // the input vector.
11121   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11122     Ops.append(InVec.getNode()->op_begin(),
11123                InVec.getNode()->op_end());
11124   } else if (InVec.getOpcode() == ISD::UNDEF) {
11125     unsigned NElts = VT.getVectorNumElements();
11126     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11127   } else {
11128     return SDValue();
11129   }
11130
11131   // Insert the element
11132   if (Elt < Ops.size()) {
11133     // All the operands of BUILD_VECTOR must have the same type;
11134     // we enforce that here.
11135     EVT OpVT = Ops[0].getValueType();
11136     if (InVal.getValueType() != OpVT)
11137       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11138                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11139                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11140     Ops[Elt] = InVal;
11141   }
11142
11143   // Return the new vector
11144   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11145 }
11146
11147 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11148     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11149   EVT ResultVT = EVE->getValueType(0);
11150   EVT VecEltVT = InVecVT.getVectorElementType();
11151   unsigned Align = OriginalLoad->getAlignment();
11152   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11153       VecEltVT.getTypeForEVT(*DAG.getContext()));
11154
11155   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11156     return SDValue();
11157
11158   Align = NewAlign;
11159
11160   SDValue NewPtr = OriginalLoad->getBasePtr();
11161   SDValue Offset;
11162   EVT PtrType = NewPtr.getValueType();
11163   MachinePointerInfo MPI;
11164   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11165     int Elt = ConstEltNo->getZExtValue();
11166     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11167     if (TLI.isBigEndian())
11168       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11169     Offset = DAG.getConstant(PtrOff, PtrType);
11170     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11171   } else {
11172     Offset = DAG.getNode(
11173         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
11174         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
11175     if (TLI.isBigEndian())
11176       Offset = DAG.getNode(
11177           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
11178           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
11179     MPI = OriginalLoad->getPointerInfo();
11180   }
11181   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
11182
11183   // The replacement we need to do here is a little tricky: we need to
11184   // replace an extractelement of a load with a load.
11185   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11186   // Note that this replacement assumes that the extractvalue is the only
11187   // use of the load; that's okay because we don't want to perform this
11188   // transformation in other cases anyway.
11189   SDValue Load;
11190   SDValue Chain;
11191   if (ResultVT.bitsGT(VecEltVT)) {
11192     // If the result type of vextract is wider than the load, then issue an
11193     // extending load instead.
11194     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11195                                                   VecEltVT)
11196                                    ? ISD::ZEXTLOAD
11197                                    : ISD::EXTLOAD;
11198     Load = DAG.getExtLoad(
11199         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11200         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11201         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11202     Chain = Load.getValue(1);
11203   } else {
11204     Load = DAG.getLoad(
11205         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11206         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11207         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11208     Chain = Load.getValue(1);
11209     if (ResultVT.bitsLT(VecEltVT))
11210       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11211     else
11212       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11213   }
11214   WorklistRemover DeadNodes(*this);
11215   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11216   SDValue To[] = { Load, Chain };
11217   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11218   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11219   // worklist explicitly as well.
11220   AddToWorklist(Load.getNode());
11221   AddUsersToWorklist(Load.getNode()); // Add users too
11222   // Make sure to revisit this node to clean it up; it will usually be dead.
11223   AddToWorklist(EVE);
11224   ++OpsNarrowed;
11225   return SDValue(EVE, 0);
11226 }
11227
11228 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11229   // (vextract (scalar_to_vector val, 0) -> val
11230   SDValue InVec = N->getOperand(0);
11231   EVT VT = InVec.getValueType();
11232   EVT NVT = N->getValueType(0);
11233
11234   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11235     // Check if the result type doesn't match the inserted element type. A
11236     // SCALAR_TO_VECTOR may truncate the inserted element and the
11237     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11238     SDValue InOp = InVec.getOperand(0);
11239     if (InOp.getValueType() != NVT) {
11240       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11241       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11242     }
11243     return InOp;
11244   }
11245
11246   SDValue EltNo = N->getOperand(1);
11247   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11248
11249   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11250   // We only perform this optimization before the op legalization phase because
11251   // we may introduce new vector instructions which are not backed by TD
11252   // patterns. For example on AVX, extracting elements from a wide vector
11253   // without using extract_subvector. However, if we can find an underlying
11254   // scalar value, then we can always use that.
11255   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11256       && ConstEltNo) {
11257     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11258     int NumElem = VT.getVectorNumElements();
11259     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11260     // Find the new index to extract from.
11261     int OrigElt = SVOp->getMaskElt(Elt);
11262
11263     // Extracting an undef index is undef.
11264     if (OrigElt == -1)
11265       return DAG.getUNDEF(NVT);
11266
11267     // Select the right vector half to extract from.
11268     SDValue SVInVec;
11269     if (OrigElt < NumElem) {
11270       SVInVec = InVec->getOperand(0);
11271     } else {
11272       SVInVec = InVec->getOperand(1);
11273       OrigElt -= NumElem;
11274     }
11275
11276     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11277       SDValue InOp = SVInVec.getOperand(OrigElt);
11278       if (InOp.getValueType() != NVT) {
11279         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11280         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11281       }
11282
11283       return InOp;
11284     }
11285
11286     // FIXME: We should handle recursing on other vector shuffles and
11287     // scalar_to_vector here as well.
11288
11289     if (!LegalOperations) {
11290       EVT IndexTy = TLI.getVectorIdxTy();
11291       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11292                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
11293     }
11294   }
11295
11296   bool BCNumEltsChanged = false;
11297   EVT ExtVT = VT.getVectorElementType();
11298   EVT LVT = ExtVT;
11299
11300   // If the result of load has to be truncated, then it's not necessarily
11301   // profitable.
11302   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11303     return SDValue();
11304
11305   if (InVec.getOpcode() == ISD::BITCAST) {
11306     // Don't duplicate a load with other uses.
11307     if (!InVec.hasOneUse())
11308       return SDValue();
11309
11310     EVT BCVT = InVec.getOperand(0).getValueType();
11311     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11312       return SDValue();
11313     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11314       BCNumEltsChanged = true;
11315     InVec = InVec.getOperand(0);
11316     ExtVT = BCVT.getVectorElementType();
11317   }
11318
11319   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11320   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11321       ISD::isNormalLoad(InVec.getNode()) &&
11322       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11323     SDValue Index = N->getOperand(1);
11324     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11325       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11326                                                            OrigLoad);
11327   }
11328
11329   // Perform only after legalization to ensure build_vector / vector_shuffle
11330   // optimizations have already been done.
11331   if (!LegalOperations) return SDValue();
11332
11333   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11334   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11335   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11336
11337   if (ConstEltNo) {
11338     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11339
11340     LoadSDNode *LN0 = nullptr;
11341     const ShuffleVectorSDNode *SVN = nullptr;
11342     if (ISD::isNormalLoad(InVec.getNode())) {
11343       LN0 = cast<LoadSDNode>(InVec);
11344     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11345                InVec.getOperand(0).getValueType() == ExtVT &&
11346                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11347       // Don't duplicate a load with other uses.
11348       if (!InVec.hasOneUse())
11349         return SDValue();
11350
11351       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11352     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11353       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11354       // =>
11355       // (load $addr+1*size)
11356
11357       // Don't duplicate a load with other uses.
11358       if (!InVec.hasOneUse())
11359         return SDValue();
11360
11361       // If the bit convert changed the number of elements, it is unsafe
11362       // to examine the mask.
11363       if (BCNumEltsChanged)
11364         return SDValue();
11365
11366       // Select the input vector, guarding against out of range extract vector.
11367       unsigned NumElems = VT.getVectorNumElements();
11368       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11369       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11370
11371       if (InVec.getOpcode() == ISD::BITCAST) {
11372         // Don't duplicate a load with other uses.
11373         if (!InVec.hasOneUse())
11374           return SDValue();
11375
11376         InVec = InVec.getOperand(0);
11377       }
11378       if (ISD::isNormalLoad(InVec.getNode())) {
11379         LN0 = cast<LoadSDNode>(InVec);
11380         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11381         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11382       }
11383     }
11384
11385     // Make sure we found a non-volatile load and the extractelement is
11386     // the only use.
11387     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11388       return SDValue();
11389
11390     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11391     if (Elt == -1)
11392       return DAG.getUNDEF(LVT);
11393
11394     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11395   }
11396
11397   return SDValue();
11398 }
11399
11400 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11401 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11402   // We perform this optimization post type-legalization because
11403   // the type-legalizer often scalarizes integer-promoted vectors.
11404   // Performing this optimization before may create bit-casts which
11405   // will be type-legalized to complex code sequences.
11406   // We perform this optimization only before the operation legalizer because we
11407   // may introduce illegal operations.
11408   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11409     return SDValue();
11410
11411   unsigned NumInScalars = N->getNumOperands();
11412   SDLoc dl(N);
11413   EVT VT = N->getValueType(0);
11414
11415   // Check to see if this is a BUILD_VECTOR of a bunch of values
11416   // which come from any_extend or zero_extend nodes. If so, we can create
11417   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11418   // optimizations. We do not handle sign-extend because we can't fill the sign
11419   // using shuffles.
11420   EVT SourceType = MVT::Other;
11421   bool AllAnyExt = true;
11422
11423   for (unsigned i = 0; i != NumInScalars; ++i) {
11424     SDValue In = N->getOperand(i);
11425     // Ignore undef inputs.
11426     if (In.getOpcode() == ISD::UNDEF) continue;
11427
11428     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11429     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11430
11431     // Abort if the element is not an extension.
11432     if (!ZeroExt && !AnyExt) {
11433       SourceType = MVT::Other;
11434       break;
11435     }
11436
11437     // The input is a ZeroExt or AnyExt. Check the original type.
11438     EVT InTy = In.getOperand(0).getValueType();
11439
11440     // Check that all of the widened source types are the same.
11441     if (SourceType == MVT::Other)
11442       // First time.
11443       SourceType = InTy;
11444     else if (InTy != SourceType) {
11445       // Multiple income types. Abort.
11446       SourceType = MVT::Other;
11447       break;
11448     }
11449
11450     // Check if all of the extends are ANY_EXTENDs.
11451     AllAnyExt &= AnyExt;
11452   }
11453
11454   // In order to have valid types, all of the inputs must be extended from the
11455   // same source type and all of the inputs must be any or zero extend.
11456   // Scalar sizes must be a power of two.
11457   EVT OutScalarTy = VT.getScalarType();
11458   bool ValidTypes = SourceType != MVT::Other &&
11459                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11460                  isPowerOf2_32(SourceType.getSizeInBits());
11461
11462   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11463   // turn into a single shuffle instruction.
11464   if (!ValidTypes)
11465     return SDValue();
11466
11467   bool isLE = TLI.isLittleEndian();
11468   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11469   assert(ElemRatio > 1 && "Invalid element size ratio");
11470   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11471                                DAG.getConstant(0, SourceType);
11472
11473   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11474   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11475
11476   // Populate the new build_vector
11477   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11478     SDValue Cast = N->getOperand(i);
11479     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11480             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11481             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11482     SDValue In;
11483     if (Cast.getOpcode() == ISD::UNDEF)
11484       In = DAG.getUNDEF(SourceType);
11485     else
11486       In = Cast->getOperand(0);
11487     unsigned Index = isLE ? (i * ElemRatio) :
11488                             (i * ElemRatio + (ElemRatio - 1));
11489
11490     assert(Index < Ops.size() && "Invalid index");
11491     Ops[Index] = In;
11492   }
11493
11494   // The type of the new BUILD_VECTOR node.
11495   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11496   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11497          "Invalid vector size");
11498   // Check if the new vector type is legal.
11499   if (!isTypeLegal(VecVT)) return SDValue();
11500
11501   // Make the new BUILD_VECTOR.
11502   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11503
11504   // The new BUILD_VECTOR node has the potential to be further optimized.
11505   AddToWorklist(BV.getNode());
11506   // Bitcast to the desired type.
11507   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11508 }
11509
11510 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11511   EVT VT = N->getValueType(0);
11512
11513   unsigned NumInScalars = N->getNumOperands();
11514   SDLoc dl(N);
11515
11516   EVT SrcVT = MVT::Other;
11517   unsigned Opcode = ISD::DELETED_NODE;
11518   unsigned NumDefs = 0;
11519
11520   for (unsigned i = 0; i != NumInScalars; ++i) {
11521     SDValue In = N->getOperand(i);
11522     unsigned Opc = In.getOpcode();
11523
11524     if (Opc == ISD::UNDEF)
11525       continue;
11526
11527     // If all scalar values are floats and converted from integers.
11528     if (Opcode == ISD::DELETED_NODE &&
11529         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11530       Opcode = Opc;
11531     }
11532
11533     if (Opc != Opcode)
11534       return SDValue();
11535
11536     EVT InVT = In.getOperand(0).getValueType();
11537
11538     // If all scalar values are typed differently, bail out. It's chosen to
11539     // simplify BUILD_VECTOR of integer types.
11540     if (SrcVT == MVT::Other)
11541       SrcVT = InVT;
11542     if (SrcVT != InVT)
11543       return SDValue();
11544     NumDefs++;
11545   }
11546
11547   // If the vector has just one element defined, it's not worth to fold it into
11548   // a vectorized one.
11549   if (NumDefs < 2)
11550     return SDValue();
11551
11552   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11553          && "Should only handle conversion from integer to float.");
11554   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11555
11556   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11557
11558   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11559     return SDValue();
11560
11561   // Just because the floating-point vector type is legal does not necessarily
11562   // mean that the corresponding integer vector type is.
11563   if (!isTypeLegal(NVT))
11564     return SDValue();
11565
11566   SmallVector<SDValue, 8> Opnds;
11567   for (unsigned i = 0; i != NumInScalars; ++i) {
11568     SDValue In = N->getOperand(i);
11569
11570     if (In.getOpcode() == ISD::UNDEF)
11571       Opnds.push_back(DAG.getUNDEF(SrcVT));
11572     else
11573       Opnds.push_back(In.getOperand(0));
11574   }
11575   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11576   AddToWorklist(BV.getNode());
11577
11578   return DAG.getNode(Opcode, dl, VT, BV);
11579 }
11580
11581 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11582   unsigned NumInScalars = N->getNumOperands();
11583   SDLoc dl(N);
11584   EVT VT = N->getValueType(0);
11585
11586   // A vector built entirely of undefs is undef.
11587   if (ISD::allOperandsUndef(N))
11588     return DAG.getUNDEF(VT);
11589
11590   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11591     return V;
11592
11593   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11594     return V;
11595
11596   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11597   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11598   // at most two distinct vectors, turn this into a shuffle node.
11599
11600   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11601   if (!isTypeLegal(VT))
11602     return SDValue();
11603
11604   // May only combine to shuffle after legalize if shuffle is legal.
11605   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11606     return SDValue();
11607
11608   SDValue VecIn1, VecIn2;
11609   bool UsesZeroVector = false;
11610   for (unsigned i = 0; i != NumInScalars; ++i) {
11611     SDValue Op = N->getOperand(i);
11612     // Ignore undef inputs.
11613     if (Op.getOpcode() == ISD::UNDEF) continue;
11614
11615     // See if we can combine this build_vector into a blend with a zero vector.
11616     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11617         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11618         (Op.getOpcode() == ISD::ConstantFP &&
11619         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11620       UsesZeroVector = true;
11621       continue;
11622     }
11623
11624     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11625     // constant index, bail out.
11626     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11627         !isa<ConstantSDNode>(Op.getOperand(1))) {
11628       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11629       break;
11630     }
11631
11632     // We allow up to two distinct input vectors.
11633     SDValue ExtractedFromVec = Op.getOperand(0);
11634     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11635       continue;
11636
11637     if (!VecIn1.getNode()) {
11638       VecIn1 = ExtractedFromVec;
11639     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11640       VecIn2 = ExtractedFromVec;
11641     } else {
11642       // Too many inputs.
11643       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11644       break;
11645     }
11646   }
11647
11648   // If everything is good, we can make a shuffle operation.
11649   if (VecIn1.getNode()) {
11650     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11651     SmallVector<int, 8> Mask;
11652     for (unsigned i = 0; i != NumInScalars; ++i) {
11653       unsigned Opcode = N->getOperand(i).getOpcode();
11654       if (Opcode == ISD::UNDEF) {
11655         Mask.push_back(-1);
11656         continue;
11657       }
11658
11659       // Operands can also be zero.
11660       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11661         assert(UsesZeroVector &&
11662                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11663                "Unexpected node found!");
11664         Mask.push_back(NumInScalars+i);
11665         continue;
11666       }
11667
11668       // If extracting from the first vector, just use the index directly.
11669       SDValue Extract = N->getOperand(i);
11670       SDValue ExtVal = Extract.getOperand(1);
11671       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11672       if (Extract.getOperand(0) == VecIn1) {
11673         Mask.push_back(ExtIndex);
11674         continue;
11675       }
11676
11677       // Otherwise, use InIdx + InputVecSize
11678       Mask.push_back(InNumElements + ExtIndex);
11679     }
11680
11681     // Avoid introducing illegal shuffles with zero.
11682     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11683       return SDValue();
11684
11685     // We can't generate a shuffle node with mismatched input and output types.
11686     // Attempt to transform a single input vector to the correct type.
11687     if ((VT != VecIn1.getValueType())) {
11688       // If the input vector type has a different base type to the output
11689       // vector type, bail out.
11690       EVT VTElemType = VT.getVectorElementType();
11691       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11692           (VecIn2.getNode() &&
11693            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11694         return SDValue();
11695
11696       // If the input vector is too small, widen it.
11697       // We only support widening of vectors which are half the size of the
11698       // output registers. For example XMM->YMM widening on X86 with AVX.
11699       EVT VecInT = VecIn1.getValueType();
11700       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11701         // If we only have one small input, widen it by adding undef values.
11702         if (!VecIn2.getNode())
11703           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11704                                DAG.getUNDEF(VecIn1.getValueType()));
11705         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11706           // If we have two small inputs of the same type, try to concat them.
11707           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11708           VecIn2 = SDValue(nullptr, 0);
11709         } else
11710           return SDValue();
11711       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11712         // If the input vector is too large, try to split it.
11713         // We don't support having two input vectors that are too large.
11714         // If the zero vector was used, we can not split the vector,
11715         // since we'd need 3 inputs.
11716         if (UsesZeroVector || VecIn2.getNode())
11717           return SDValue();
11718
11719         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11720           return SDValue();
11721
11722         // Try to replace VecIn1 with two extract_subvectors
11723         // No need to update the masks, they should still be correct.
11724         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11725           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11726         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11727           DAG.getConstant(0, TLI.getVectorIdxTy()));
11728       } else
11729         return SDValue();
11730     }
11731
11732     if (UsesZeroVector)
11733       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11734                                 DAG.getConstantFP(0.0, VT);
11735     else
11736       // If VecIn2 is unused then change it to undef.
11737       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11738
11739     // Check that we were able to transform all incoming values to the same
11740     // type.
11741     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11742         VecIn1.getValueType() != VT)
11743           return SDValue();
11744
11745     // Return the new VECTOR_SHUFFLE node.
11746     SDValue Ops[2];
11747     Ops[0] = VecIn1;
11748     Ops[1] = VecIn2;
11749     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11750   }
11751
11752   return SDValue();
11753 }
11754
11755 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11757   EVT OpVT = N->getOperand(0).getValueType();
11758
11759   // If the operands are legal vectors, leave them alone.
11760   if (TLI.isTypeLegal(OpVT))
11761     return SDValue();
11762
11763   SDLoc DL(N);
11764   EVT VT = N->getValueType(0);
11765   SmallVector<SDValue, 8> Ops;
11766
11767   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11768   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11769
11770   // Keep track of what we encounter.
11771   bool AnyInteger = false;
11772   bool AnyFP = false;
11773   for (const SDValue &Op : N->ops()) {
11774     if (ISD::BITCAST == Op.getOpcode() &&
11775         !Op.getOperand(0).getValueType().isVector())
11776       Ops.push_back(Op.getOperand(0));
11777     else if (ISD::UNDEF == Op.getOpcode())
11778       Ops.push_back(ScalarUndef);
11779     else
11780       return SDValue();
11781
11782     // Note whether we encounter an integer or floating point scalar.
11783     // If it's neither, bail out, it could be something weird like x86mmx.
11784     EVT LastOpVT = Ops.back().getValueType();
11785     if (LastOpVT.isFloatingPoint())
11786       AnyFP = true;
11787     else if (LastOpVT.isInteger())
11788       AnyInteger = true;
11789     else
11790       return SDValue();
11791   }
11792
11793   // If any of the operands is a floating point scalar bitcast to a vector,
11794   // use floating point types throughout, and bitcast everything.  
11795   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11796   if (AnyFP) {
11797     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11798     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11799     if (AnyInteger) {
11800       for (SDValue &Op : Ops) {
11801         if (Op.getValueType() == SVT)
11802           continue;
11803         if (Op.getOpcode() == ISD::UNDEF)
11804           Op = ScalarUndef;
11805         else
11806           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11807       }
11808     }
11809   }
11810
11811   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11812                                VT.getSizeInBits() / SVT.getSizeInBits());
11813   return DAG.getNode(ISD::BITCAST, DL, VT,
11814                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11815 }
11816
11817 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11818   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11819   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11820   // inputs come from at most two distinct vectors, turn this into a shuffle
11821   // node.
11822
11823   // If we only have one input vector, we don't need to do any concatenation.
11824   if (N->getNumOperands() == 1)
11825     return N->getOperand(0);
11826
11827   // Check if all of the operands are undefs.
11828   EVT VT = N->getValueType(0);
11829   if (ISD::allOperandsUndef(N))
11830     return DAG.getUNDEF(VT);
11831
11832   // Optimize concat_vectors where all but the first of the vectors are undef.
11833   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11834         return Op.getOpcode() == ISD::UNDEF;
11835       })) {
11836     SDValue In = N->getOperand(0);
11837     assert(In.getValueType().isVector() && "Must concat vectors");
11838
11839     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11840     if (In->getOpcode() == ISD::BITCAST &&
11841         !In->getOperand(0)->getValueType(0).isVector()) {
11842       SDValue Scalar = In->getOperand(0);
11843
11844       // If the bitcast type isn't legal, it might be a trunc of a legal type;
11845       // look through the trunc so we can still do the transform:
11846       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11847       if (Scalar->getOpcode() == ISD::TRUNCATE &&
11848           !TLI.isTypeLegal(Scalar.getValueType()) &&
11849           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11850         Scalar = Scalar->getOperand(0);
11851
11852       EVT SclTy = Scalar->getValueType(0);
11853
11854       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11855         return SDValue();
11856
11857       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11858                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11859       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11860         return SDValue();
11861
11862       SDLoc dl = SDLoc(N);
11863       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11864       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11865     }
11866   }
11867
11868   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11869   // We have already tested above for an UNDEF only concatenation.
11870   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11871   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11872   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11873     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11874   };
11875   bool AllBuildVectorsOrUndefs =
11876       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11877   if (AllBuildVectorsOrUndefs) {
11878     SmallVector<SDValue, 8> Opnds;
11879     EVT SVT = VT.getScalarType();
11880
11881     EVT MinVT = SVT;
11882     if (!SVT.isFloatingPoint()) {
11883       // If BUILD_VECTOR are from built from integer, they may have different
11884       // operand types. Get the smallest type and truncate all operands to it.
11885       bool FoundMinVT = false;
11886       for (const SDValue &Op : N->ops())
11887         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11888           EVT OpSVT = Op.getOperand(0)->getValueType(0);
11889           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11890           FoundMinVT = true;
11891         }
11892       assert(FoundMinVT && "Concat vector type mismatch");
11893     }
11894
11895     for (const SDValue &Op : N->ops()) {
11896       EVT OpVT = Op.getValueType();
11897       unsigned NumElts = OpVT.getVectorNumElements();
11898
11899       if (ISD::UNDEF == Op.getOpcode())
11900         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11901
11902       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11903         if (SVT.isFloatingPoint()) {
11904           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11905           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11906         } else {
11907           for (unsigned i = 0; i != NumElts; ++i)
11908             Opnds.push_back(
11909                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11910         }
11911       }
11912     }
11913
11914     assert(VT.getVectorNumElements() == Opnds.size() &&
11915            "Concat vector type mismatch");
11916     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11917   }
11918
11919   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
11920   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
11921     return V;
11922
11923   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11924   // nodes often generate nop CONCAT_VECTOR nodes.
11925   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11926   // place the incoming vectors at the exact same location.
11927   SDValue SingleSource = SDValue();
11928   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11929
11930   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11931     SDValue Op = N->getOperand(i);
11932
11933     if (Op.getOpcode() == ISD::UNDEF)
11934       continue;
11935
11936     // Check if this is the identity extract:
11937     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11938       return SDValue();
11939
11940     // Find the single incoming vector for the extract_subvector.
11941     if (SingleSource.getNode()) {
11942       if (Op.getOperand(0) != SingleSource)
11943         return SDValue();
11944     } else {
11945       SingleSource = Op.getOperand(0);
11946
11947       // Check the source type is the same as the type of the result.
11948       // If not, this concat may extend the vector, so we can not
11949       // optimize it away.
11950       if (SingleSource.getValueType() != N->getValueType(0))
11951         return SDValue();
11952     }
11953
11954     unsigned IdentityIndex = i * PartNumElem;
11955     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11956     // The extract index must be constant.
11957     if (!CS)
11958       return SDValue();
11959
11960     // Check that we are reading from the identity index.
11961     if (CS->getZExtValue() != IdentityIndex)
11962       return SDValue();
11963   }
11964
11965   if (SingleSource.getNode())
11966     return SingleSource;
11967
11968   return SDValue();
11969 }
11970
11971 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11972   EVT NVT = N->getValueType(0);
11973   SDValue V = N->getOperand(0);
11974
11975   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11976     // Combine:
11977     //    (extract_subvec (concat V1, V2, ...), i)
11978     // Into:
11979     //    Vi if possible
11980     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11981     // type.
11982     if (V->getOperand(0).getValueType() != NVT)
11983       return SDValue();
11984     unsigned Idx = N->getConstantOperandVal(1);
11985     unsigned NumElems = NVT.getVectorNumElements();
11986     assert((Idx % NumElems) == 0 &&
11987            "IDX in concat is not a multiple of the result vector length.");
11988     return V->getOperand(Idx / NumElems);
11989   }
11990
11991   // Skip bitcasting
11992   if (V->getOpcode() == ISD::BITCAST)
11993     V = V.getOperand(0);
11994
11995   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11996     SDLoc dl(N);
11997     // Handle only simple case where vector being inserted and vector
11998     // being extracted are of same type, and are half size of larger vectors.
11999     EVT BigVT = V->getOperand(0).getValueType();
12000     EVT SmallVT = V->getOperand(1).getValueType();
12001     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12002       return SDValue();
12003
12004     // Only handle cases where both indexes are constants with the same type.
12005     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12006     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12007
12008     if (InsIdx && ExtIdx &&
12009         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12010         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12011       // Combine:
12012       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12013       // Into:
12014       //    indices are equal or bit offsets are equal => V1
12015       //    otherwise => (extract_subvec V1, ExtIdx)
12016       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12017           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12018         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12019       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12020                          DAG.getNode(ISD::BITCAST, dl,
12021                                      N->getOperand(0).getValueType(),
12022                                      V->getOperand(0)), N->getOperand(1));
12023     }
12024   }
12025
12026   return SDValue();
12027 }
12028
12029 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12030                                                  SDValue V, SelectionDAG &DAG) {
12031   SDLoc DL(V);
12032   EVT VT = V.getValueType();
12033
12034   switch (V.getOpcode()) {
12035   default:
12036     return V;
12037
12038   case ISD::CONCAT_VECTORS: {
12039     EVT OpVT = V->getOperand(0).getValueType();
12040     int OpSize = OpVT.getVectorNumElements();
12041     SmallBitVector OpUsedElements(OpSize, false);
12042     bool FoundSimplification = false;
12043     SmallVector<SDValue, 4> NewOps;
12044     NewOps.reserve(V->getNumOperands());
12045     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12046       SDValue Op = V->getOperand(i);
12047       bool OpUsed = false;
12048       for (int j = 0; j < OpSize; ++j)
12049         if (UsedElements[i * OpSize + j]) {
12050           OpUsedElements[j] = true;
12051           OpUsed = true;
12052         }
12053       NewOps.push_back(
12054           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12055                  : DAG.getUNDEF(OpVT));
12056       FoundSimplification |= Op == NewOps.back();
12057       OpUsedElements.reset();
12058     }
12059     if (FoundSimplification)
12060       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12061     return V;
12062   }
12063
12064   case ISD::INSERT_SUBVECTOR: {
12065     SDValue BaseV = V->getOperand(0);
12066     SDValue SubV = V->getOperand(1);
12067     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12068     if (!IdxN)
12069       return V;
12070
12071     int SubSize = SubV.getValueType().getVectorNumElements();
12072     int Idx = IdxN->getZExtValue();
12073     bool SubVectorUsed = false;
12074     SmallBitVector SubUsedElements(SubSize, false);
12075     for (int i = 0; i < SubSize; ++i)
12076       if (UsedElements[i + Idx]) {
12077         SubVectorUsed = true;
12078         SubUsedElements[i] = true;
12079         UsedElements[i + Idx] = false;
12080       }
12081
12082     // Now recurse on both the base and sub vectors.
12083     SDValue SimplifiedSubV =
12084         SubVectorUsed
12085             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12086             : DAG.getUNDEF(SubV.getValueType());
12087     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12088     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12089       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12090                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12091     return V;
12092   }
12093   }
12094 }
12095
12096 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12097                                        SDValue N1, SelectionDAG &DAG) {
12098   EVT VT = SVN->getValueType(0);
12099   int NumElts = VT.getVectorNumElements();
12100   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12101   for (int M : SVN->getMask())
12102     if (M >= 0 && M < NumElts)
12103       N0UsedElements[M] = true;
12104     else if (M >= NumElts)
12105       N1UsedElements[M - NumElts] = true;
12106
12107   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12108   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12109   if (S0 == N0 && S1 == N1)
12110     return SDValue();
12111
12112   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12113 }
12114
12115 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12116 // or turn a shuffle of a single concat into simpler shuffle then concat.
12117 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12118   EVT VT = N->getValueType(0);
12119   unsigned NumElts = VT.getVectorNumElements();
12120
12121   SDValue N0 = N->getOperand(0);
12122   SDValue N1 = N->getOperand(1);
12123   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12124
12125   SmallVector<SDValue, 4> Ops;
12126   EVT ConcatVT = N0.getOperand(0).getValueType();
12127   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12128   unsigned NumConcats = NumElts / NumElemsPerConcat;
12129
12130   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12131   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12132   // half vector elements.
12133   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12134       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12135                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12136     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12137                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12138     N1 = DAG.getUNDEF(ConcatVT);
12139     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12140   }
12141
12142   // Look at every vector that's inserted. We're looking for exact
12143   // subvector-sized copies from a concatenated vector
12144   for (unsigned I = 0; I != NumConcats; ++I) {
12145     // Make sure we're dealing with a copy.
12146     unsigned Begin = I * NumElemsPerConcat;
12147     bool AllUndef = true, NoUndef = true;
12148     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12149       if (SVN->getMaskElt(J) >= 0)
12150         AllUndef = false;
12151       else
12152         NoUndef = false;
12153     }
12154
12155     if (NoUndef) {
12156       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12157         return SDValue();
12158
12159       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12160         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12161           return SDValue();
12162
12163       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12164       if (FirstElt < N0.getNumOperands())
12165         Ops.push_back(N0.getOperand(FirstElt));
12166       else
12167         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12168
12169     } else if (AllUndef) {
12170       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12171     } else { // Mixed with general masks and undefs, can't do optimization.
12172       return SDValue();
12173     }
12174   }
12175
12176   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12177 }
12178
12179 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12180   EVT VT = N->getValueType(0);
12181   unsigned NumElts = VT.getVectorNumElements();
12182
12183   SDValue N0 = N->getOperand(0);
12184   SDValue N1 = N->getOperand(1);
12185
12186   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12187
12188   // Canonicalize shuffle undef, undef -> undef
12189   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12190     return DAG.getUNDEF(VT);
12191
12192   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12193
12194   // Canonicalize shuffle v, v -> v, undef
12195   if (N0 == N1) {
12196     SmallVector<int, 8> NewMask;
12197     for (unsigned i = 0; i != NumElts; ++i) {
12198       int Idx = SVN->getMaskElt(i);
12199       if (Idx >= (int)NumElts) Idx -= NumElts;
12200       NewMask.push_back(Idx);
12201     }
12202     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12203                                 &NewMask[0]);
12204   }
12205
12206   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12207   if (N0.getOpcode() == ISD::UNDEF) {
12208     SmallVector<int, 8> NewMask;
12209     for (unsigned i = 0; i != NumElts; ++i) {
12210       int Idx = SVN->getMaskElt(i);
12211       if (Idx >= 0) {
12212         if (Idx >= (int)NumElts)
12213           Idx -= NumElts;
12214         else
12215           Idx = -1; // remove reference to lhs
12216       }
12217       NewMask.push_back(Idx);
12218     }
12219     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12220                                 &NewMask[0]);
12221   }
12222
12223   // Remove references to rhs if it is undef
12224   if (N1.getOpcode() == ISD::UNDEF) {
12225     bool Changed = false;
12226     SmallVector<int, 8> NewMask;
12227     for (unsigned i = 0; i != NumElts; ++i) {
12228       int Idx = SVN->getMaskElt(i);
12229       if (Idx >= (int)NumElts) {
12230         Idx = -1;
12231         Changed = true;
12232       }
12233       NewMask.push_back(Idx);
12234     }
12235     if (Changed)
12236       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12237   }
12238
12239   // If it is a splat, check if the argument vector is another splat or a
12240   // build_vector.
12241   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12242     SDNode *V = N0.getNode();
12243
12244     // If this is a bit convert that changes the element type of the vector but
12245     // not the number of vector elements, look through it.  Be careful not to
12246     // look though conversions that change things like v4f32 to v2f64.
12247     if (V->getOpcode() == ISD::BITCAST) {
12248       SDValue ConvInput = V->getOperand(0);
12249       if (ConvInput.getValueType().isVector() &&
12250           ConvInput.getValueType().getVectorNumElements() == NumElts)
12251         V = ConvInput.getNode();
12252     }
12253
12254     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12255       assert(V->getNumOperands() == NumElts &&
12256              "BUILD_VECTOR has wrong number of operands");
12257       SDValue Base;
12258       bool AllSame = true;
12259       for (unsigned i = 0; i != NumElts; ++i) {
12260         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12261           Base = V->getOperand(i);
12262           break;
12263         }
12264       }
12265       // Splat of <u, u, u, u>, return <u, u, u, u>
12266       if (!Base.getNode())
12267         return N0;
12268       for (unsigned i = 0; i != NumElts; ++i) {
12269         if (V->getOperand(i) != Base) {
12270           AllSame = false;
12271           break;
12272         }
12273       }
12274       // Splat of <x, x, x, x>, return <x, x, x, x>
12275       if (AllSame)
12276         return N0;
12277
12278       // Canonicalize any other splat as a build_vector.
12279       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12280       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12281       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12282                                   V->getValueType(0), Ops);
12283
12284       // We may have jumped through bitcasts, so the type of the
12285       // BUILD_VECTOR may not match the type of the shuffle.
12286       if (V->getValueType(0) != VT)
12287         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12288       return NewBV;
12289     }
12290   }
12291
12292   // There are various patterns used to build up a vector from smaller vectors,
12293   // subvectors, or elements. Scan chains of these and replace unused insertions
12294   // or components with undef.
12295   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12296     return S;
12297
12298   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12299       Level < AfterLegalizeVectorOps &&
12300       (N1.getOpcode() == ISD::UNDEF ||
12301       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12302        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12303     SDValue V = partitionShuffleOfConcats(N, DAG);
12304
12305     if (V.getNode())
12306       return V;
12307   }
12308
12309   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12310   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12311   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12312     SmallVector<SDValue, 8> Ops;
12313     for (int M : SVN->getMask()) {
12314       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12315       if (M >= 0) {
12316         int Idx = M % NumElts;
12317         SDValue &S = (M < (int)NumElts ? N0 : N1);
12318         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12319           Op = S.getOperand(Idx);
12320         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12321           if (Idx == 0)
12322             Op = S.getOperand(0);
12323         } else {
12324           // Operand can't be combined - bail out.
12325           break;
12326         }
12327       }
12328       Ops.push_back(Op);
12329     }
12330     if (Ops.size() == VT.getVectorNumElements()) {
12331       // BUILD_VECTOR requires all inputs to be of the same type, find the
12332       // maximum type and extend them all.
12333       EVT SVT = VT.getScalarType();
12334       if (SVT.isInteger())
12335         for (SDValue &Op : Ops)
12336           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12337       if (SVT != VT.getScalarType())
12338         for (SDValue &Op : Ops)
12339           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12340                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12341                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12342       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12343     }
12344   }
12345
12346   // If this shuffle only has a single input that is a bitcasted shuffle,
12347   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12348   // back to their original types.
12349   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12350       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12351       TLI.isTypeLegal(VT)) {
12352
12353     // Peek through the bitcast only if there is one user.
12354     SDValue BC0 = N0;
12355     while (BC0.getOpcode() == ISD::BITCAST) {
12356       if (!BC0.hasOneUse())
12357         break;
12358       BC0 = BC0.getOperand(0);
12359     }
12360
12361     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12362       if (Scale == 1)
12363         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12364
12365       SmallVector<int, 8> NewMask;
12366       for (int M : Mask)
12367         for (int s = 0; s != Scale; ++s)
12368           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12369       return NewMask;
12370     };
12371
12372     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12373       EVT SVT = VT.getScalarType();
12374       EVT InnerVT = BC0->getValueType(0);
12375       EVT InnerSVT = InnerVT.getScalarType();
12376
12377       // Determine which shuffle works with the smaller scalar type.
12378       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12379       EVT ScaleSVT = ScaleVT.getScalarType();
12380
12381       if (TLI.isTypeLegal(ScaleVT) &&
12382           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12383           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12384
12385         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12386         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12387
12388         // Scale the shuffle masks to the smaller scalar type.
12389         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12390         SmallVector<int, 8> InnerMask =
12391             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12392         SmallVector<int, 8> OuterMask =
12393             ScaleShuffleMask(SVN->getMask(), OuterScale);
12394
12395         // Merge the shuffle masks.
12396         SmallVector<int, 8> NewMask;
12397         for (int M : OuterMask)
12398           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12399
12400         // Test for shuffle mask legality over both commutations.
12401         SDValue SV0 = BC0->getOperand(0);
12402         SDValue SV1 = BC0->getOperand(1);
12403         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12404         if (!LegalMask) {
12405           std::swap(SV0, SV1);
12406           ShuffleVectorSDNode::commuteMask(NewMask);
12407           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12408         }
12409
12410         if (LegalMask) {
12411           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12412           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12413           return DAG.getNode(
12414               ISD::BITCAST, SDLoc(N), VT,
12415               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12416         }
12417       }
12418     }
12419   }
12420
12421   // Canonicalize shuffles according to rules:
12422   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12423   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12424   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12425   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12426       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12427       TLI.isTypeLegal(VT)) {
12428     // The incoming shuffle must be of the same type as the result of the
12429     // current shuffle.
12430     assert(N1->getOperand(0).getValueType() == VT &&
12431            "Shuffle types don't match");
12432
12433     SDValue SV0 = N1->getOperand(0);
12434     SDValue SV1 = N1->getOperand(1);
12435     bool HasSameOp0 = N0 == SV0;
12436     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12437     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12438       // Commute the operands of this shuffle so that next rule
12439       // will trigger.
12440       return DAG.getCommutedVectorShuffle(*SVN);
12441   }
12442
12443   // Try to fold according to rules:
12444   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12445   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12446   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12447   // Don't try to fold shuffles with illegal type.
12448   // Only fold if this shuffle is the only user of the other shuffle.
12449   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12450       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12451     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12452
12453     // The incoming shuffle must be of the same type as the result of the
12454     // current shuffle.
12455     assert(OtherSV->getOperand(0).getValueType() == VT &&
12456            "Shuffle types don't match");
12457
12458     SDValue SV0, SV1;
12459     SmallVector<int, 4> Mask;
12460     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12461     // operand, and SV1 as the second operand.
12462     for (unsigned i = 0; i != NumElts; ++i) {
12463       int Idx = SVN->getMaskElt(i);
12464       if (Idx < 0) {
12465         // Propagate Undef.
12466         Mask.push_back(Idx);
12467         continue;
12468       }
12469
12470       SDValue CurrentVec;
12471       if (Idx < (int)NumElts) {
12472         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12473         // shuffle mask to identify which vector is actually referenced.
12474         Idx = OtherSV->getMaskElt(Idx);
12475         if (Idx < 0) {
12476           // Propagate Undef.
12477           Mask.push_back(Idx);
12478           continue;
12479         }
12480
12481         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12482                                            : OtherSV->getOperand(1);
12483       } else {
12484         // This shuffle index references an element within N1.
12485         CurrentVec = N1;
12486       }
12487
12488       // Simple case where 'CurrentVec' is UNDEF.
12489       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12490         Mask.push_back(-1);
12491         continue;
12492       }
12493
12494       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12495       // will be the first or second operand of the combined shuffle.
12496       Idx = Idx % NumElts;
12497       if (!SV0.getNode() || SV0 == CurrentVec) {
12498         // Ok. CurrentVec is the left hand side.
12499         // Update the mask accordingly.
12500         SV0 = CurrentVec;
12501         Mask.push_back(Idx);
12502         continue;
12503       }
12504
12505       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12506       if (SV1.getNode() && SV1 != CurrentVec)
12507         return SDValue();
12508
12509       // Ok. CurrentVec is the right hand side.
12510       // Update the mask accordingly.
12511       SV1 = CurrentVec;
12512       Mask.push_back(Idx + NumElts);
12513     }
12514
12515     // Check if all indices in Mask are Undef. In case, propagate Undef.
12516     bool isUndefMask = true;
12517     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12518       isUndefMask &= Mask[i] < 0;
12519
12520     if (isUndefMask)
12521       return DAG.getUNDEF(VT);
12522
12523     if (!SV0.getNode())
12524       SV0 = DAG.getUNDEF(VT);
12525     if (!SV1.getNode())
12526       SV1 = DAG.getUNDEF(VT);
12527
12528     // Avoid introducing shuffles with illegal mask.
12529     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12530       ShuffleVectorSDNode::commuteMask(Mask);
12531
12532       if (!TLI.isShuffleMaskLegal(Mask, VT))
12533         return SDValue();
12534
12535       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12536       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12537       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12538       std::swap(SV0, SV1);
12539     }
12540
12541     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12542     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12543     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12544     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12545   }
12546
12547   return SDValue();
12548 }
12549
12550 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12551   SDValue InVal = N->getOperand(0);
12552   EVT VT = N->getValueType(0);
12553
12554   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12555   // with a VECTOR_SHUFFLE.
12556   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12557     SDValue InVec = InVal->getOperand(0);
12558     SDValue EltNo = InVal->getOperand(1);
12559
12560     // FIXME: We could support implicit truncation if the shuffle can be
12561     // scaled to a smaller vector scalar type.
12562     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12563     if (C0 && VT == InVec.getValueType() &&
12564         VT.getScalarType() == InVal.getValueType()) {
12565       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12566       int Elt = C0->getZExtValue();
12567       NewMask[0] = Elt;
12568
12569       if (TLI.isShuffleMaskLegal(NewMask, VT))
12570         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12571                                     NewMask);
12572     }
12573   }
12574
12575   return SDValue();
12576 }
12577
12578 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12579   SDValue N0 = N->getOperand(0);
12580   SDValue N2 = N->getOperand(2);
12581
12582   // If the input vector is a concatenation, and the insert replaces
12583   // one of the halves, we can optimize into a single concat_vectors.
12584   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12585       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12586     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12587     EVT VT = N->getValueType(0);
12588
12589     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12590     // (concat_vectors Z, Y)
12591     if (InsIdx == 0)
12592       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12593                          N->getOperand(1), N0.getOperand(1));
12594
12595     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12596     // (concat_vectors X, Z)
12597     if (InsIdx == VT.getVectorNumElements()/2)
12598       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12599                          N0.getOperand(0), N->getOperand(1));
12600   }
12601
12602   return SDValue();
12603 }
12604
12605 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12606   SDValue N0 = N->getOperand(0);
12607
12608   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12609   if (N0->getOpcode() == ISD::FP16_TO_FP)
12610     return N0->getOperand(0);
12611
12612   return SDValue();
12613 }
12614
12615 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12616 /// with the destination vector and a zero vector.
12617 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12618 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12619 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12620   EVT VT = N->getValueType(0);
12621   SDValue LHS = N->getOperand(0);
12622   SDValue RHS = N->getOperand(1);
12623   SDLoc dl(N);
12624
12625   // Make sure we're not running after operation legalization where it 
12626   // may have custom lowered the vector shuffles.
12627   if (LegalOperations)
12628     return SDValue();
12629
12630   if (N->getOpcode() != ISD::AND)
12631     return SDValue();
12632
12633   if (RHS.getOpcode() == ISD::BITCAST)
12634     RHS = RHS.getOperand(0);
12635
12636   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12637     SmallVector<int, 8> Indices;
12638     unsigned NumElts = RHS.getNumOperands();
12639
12640     for (unsigned i = 0; i != NumElts; ++i) {
12641       SDValue Elt = RHS.getOperand(i);
12642       if (!isa<ConstantSDNode>(Elt))
12643         return SDValue();
12644
12645       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12646         Indices.push_back(i);
12647       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12648         Indices.push_back(NumElts+i);
12649       else
12650         return SDValue();
12651     }
12652
12653     // Let's see if the target supports this vector_shuffle.
12654     EVT RVT = RHS.getValueType();
12655     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12656       return SDValue();
12657
12658     // Return the new VECTOR_SHUFFLE node.
12659     EVT EltVT = RVT.getVectorElementType();
12660     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12661                                    DAG.getConstant(0, EltVT));
12662     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12663     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12664     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12665     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12666   }
12667
12668   return SDValue();
12669 }
12670
12671 /// Visit a binary vector operation, like ADD.
12672 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12673   assert(N->getValueType(0).isVector() &&
12674          "SimplifyVBinOp only works on vectors!");
12675
12676   SDValue LHS = N->getOperand(0);
12677   SDValue RHS = N->getOperand(1);
12678
12679   if (SDValue Shuffle = XformToShuffleWithZero(N))
12680     return Shuffle;
12681
12682   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12683   // this operation.
12684   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12685       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12686     // Check if both vectors are constants. If not bail out.
12687     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12688           cast<BuildVectorSDNode>(RHS)->isConstant()))
12689       return SDValue();
12690
12691     SmallVector<SDValue, 8> Ops;
12692     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12693       SDValue LHSOp = LHS.getOperand(i);
12694       SDValue RHSOp = RHS.getOperand(i);
12695
12696       // Can't fold divide by zero.
12697       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12698           N->getOpcode() == ISD::FDIV) {
12699         if ((RHSOp.getOpcode() == ISD::Constant &&
12700              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12701             (RHSOp.getOpcode() == ISD::ConstantFP &&
12702              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12703           break;
12704       }
12705
12706       EVT VT = LHSOp.getValueType();
12707       EVT RVT = RHSOp.getValueType();
12708       if (RVT != VT) {
12709         // Integer BUILD_VECTOR operands may have types larger than the element
12710         // size (e.g., when the element type is not legal).  Prior to type
12711         // legalization, the types may not match between the two BUILD_VECTORS.
12712         // Truncate one of the operands to make them match.
12713         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12714           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12715         } else {
12716           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12717           VT = RVT;
12718         }
12719       }
12720       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12721                                    LHSOp, RHSOp);
12722       if (FoldOp.getOpcode() != ISD::UNDEF &&
12723           FoldOp.getOpcode() != ISD::Constant &&
12724           FoldOp.getOpcode() != ISD::ConstantFP)
12725         break;
12726       Ops.push_back(FoldOp);
12727       AddToWorklist(FoldOp.getNode());
12728     }
12729
12730     if (Ops.size() == LHS.getNumOperands())
12731       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12732   }
12733
12734   // Type legalization might introduce new shuffles in the DAG.
12735   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12736   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12737   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12738       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12739       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12740       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12741     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12742     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12743
12744     if (SVN0->getMask().equals(SVN1->getMask())) {
12745       EVT VT = N->getValueType(0);
12746       SDValue UndefVector = LHS.getOperand(1);
12747       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12748                                      LHS.getOperand(0), RHS.getOperand(0));
12749       AddUsersToWorklist(N);
12750       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12751                                   &SVN0->getMask()[0]);
12752     }
12753   }
12754
12755   return SDValue();
12756 }
12757
12758 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12759                                     SDValue N1, SDValue N2){
12760   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12761
12762   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12763                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12764
12765   // If we got a simplified select_cc node back from SimplifySelectCC, then
12766   // break it down into a new SETCC node, and a new SELECT node, and then return
12767   // the SELECT node, since we were called with a SELECT node.
12768   if (SCC.getNode()) {
12769     // Check to see if we got a select_cc back (to turn into setcc/select).
12770     // Otherwise, just return whatever node we got back, like fabs.
12771     if (SCC.getOpcode() == ISD::SELECT_CC) {
12772       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12773                                   N0.getValueType(),
12774                                   SCC.getOperand(0), SCC.getOperand(1),
12775                                   SCC.getOperand(4));
12776       AddToWorklist(SETCC.getNode());
12777       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12778                            SCC.getOperand(2), SCC.getOperand(3));
12779     }
12780
12781     return SCC;
12782   }
12783   return SDValue();
12784 }
12785
12786 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12787 /// being selected between, see if we can simplify the select.  Callers of this
12788 /// should assume that TheSelect is deleted if this returns true.  As such, they
12789 /// should return the appropriate thing (e.g. the node) back to the top-level of
12790 /// the DAG combiner loop to avoid it being looked at.
12791 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12792                                     SDValue RHS) {
12793
12794   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12795   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12796   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12797     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12798       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12799       SDValue Sqrt = RHS;
12800       ISD::CondCode CC;
12801       SDValue CmpLHS;
12802       const ConstantFPSDNode *NegZero = nullptr;
12803
12804       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12805         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12806         CmpLHS = TheSelect->getOperand(0);
12807         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12808       } else {
12809         // SELECT or VSELECT
12810         SDValue Cmp = TheSelect->getOperand(0);
12811         if (Cmp.getOpcode() == ISD::SETCC) {
12812           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12813           CmpLHS = Cmp.getOperand(0);
12814           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12815         }
12816       }
12817       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12818           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12819           CC == ISD::SETULT || CC == ISD::SETLT)) {
12820         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12821         CombineTo(TheSelect, Sqrt);
12822         return true;
12823       }
12824     }
12825   }
12826   // Cannot simplify select with vector condition
12827   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12828
12829   // If this is a select from two identical things, try to pull the operation
12830   // through the select.
12831   if (LHS.getOpcode() != RHS.getOpcode() ||
12832       !LHS.hasOneUse() || !RHS.hasOneUse())
12833     return false;
12834
12835   // If this is a load and the token chain is identical, replace the select
12836   // of two loads with a load through a select of the address to load from.
12837   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12838   // constants have been dropped into the constant pool.
12839   if (LHS.getOpcode() == ISD::LOAD) {
12840     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12841     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12842
12843     // Token chains must be identical.
12844     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12845         // Do not let this transformation reduce the number of volatile loads.
12846         LLD->isVolatile() || RLD->isVolatile() ||
12847         // FIXME: If either is a pre/post inc/dec load,
12848         // we'd need to split out the address adjustment.
12849         LLD->isIndexed() || RLD->isIndexed() ||
12850         // If this is an EXTLOAD, the VT's must match.
12851         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12852         // If this is an EXTLOAD, the kind of extension must match.
12853         (LLD->getExtensionType() != RLD->getExtensionType() &&
12854          // The only exception is if one of the extensions is anyext.
12855          LLD->getExtensionType() != ISD::EXTLOAD &&
12856          RLD->getExtensionType() != ISD::EXTLOAD) ||
12857         // FIXME: this discards src value information.  This is
12858         // over-conservative. It would be beneficial to be able to remember
12859         // both potential memory locations.  Since we are discarding
12860         // src value info, don't do the transformation if the memory
12861         // locations are not in the default address space.
12862         LLD->getPointerInfo().getAddrSpace() != 0 ||
12863         RLD->getPointerInfo().getAddrSpace() != 0 ||
12864         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12865                                       LLD->getBasePtr().getValueType()))
12866       return false;
12867
12868     // Check that the select condition doesn't reach either load.  If so,
12869     // folding this will induce a cycle into the DAG.  If not, this is safe to
12870     // xform, so create a select of the addresses.
12871     SDValue Addr;
12872     if (TheSelect->getOpcode() == ISD::SELECT) {
12873       SDNode *CondNode = TheSelect->getOperand(0).getNode();
12874       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12875           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12876         return false;
12877       // The loads must not depend on one another.
12878       if (LLD->isPredecessorOf(RLD) ||
12879           RLD->isPredecessorOf(LLD))
12880         return false;
12881       Addr = DAG.getSelect(SDLoc(TheSelect),
12882                            LLD->getBasePtr().getValueType(),
12883                            TheSelect->getOperand(0), LLD->getBasePtr(),
12884                            RLD->getBasePtr());
12885     } else {  // Otherwise SELECT_CC
12886       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12887       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12888
12889       if ((LLD->hasAnyUseOfValue(1) &&
12890            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12891           (RLD->hasAnyUseOfValue(1) &&
12892            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12893         return false;
12894
12895       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12896                          LLD->getBasePtr().getValueType(),
12897                          TheSelect->getOperand(0),
12898                          TheSelect->getOperand(1),
12899                          LLD->getBasePtr(), RLD->getBasePtr(),
12900                          TheSelect->getOperand(4));
12901     }
12902
12903     SDValue Load;
12904     // It is safe to replace the two loads if they have different alignments,
12905     // but the new load must be the minimum (most restrictive) alignment of the
12906     // inputs.
12907     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12908     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12909     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12910       Load = DAG.getLoad(TheSelect->getValueType(0),
12911                          SDLoc(TheSelect),
12912                          // FIXME: Discards pointer and AA info.
12913                          LLD->getChain(), Addr, MachinePointerInfo(),
12914                          LLD->isVolatile(), LLD->isNonTemporal(),
12915                          isInvariant, Alignment);
12916     } else {
12917       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12918                             RLD->getExtensionType() : LLD->getExtensionType(),
12919                             SDLoc(TheSelect),
12920                             TheSelect->getValueType(0),
12921                             // FIXME: Discards pointer and AA info.
12922                             LLD->getChain(), Addr, MachinePointerInfo(),
12923                             LLD->getMemoryVT(), LLD->isVolatile(),
12924                             LLD->isNonTemporal(), isInvariant, Alignment);
12925     }
12926
12927     // Users of the select now use the result of the load.
12928     CombineTo(TheSelect, Load);
12929
12930     // Users of the old loads now use the new load's chain.  We know the
12931     // old-load value is dead now.
12932     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12933     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12934     return true;
12935   }
12936
12937   return false;
12938 }
12939
12940 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12941 /// where 'cond' is the comparison specified by CC.
12942 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12943                                       SDValue N2, SDValue N3,
12944                                       ISD::CondCode CC, bool NotExtCompare) {
12945   // (x ? y : y) -> y.
12946   if (N2 == N3) return N2;
12947
12948   EVT VT = N2.getValueType();
12949   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12950   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12951   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12952
12953   // Determine if the condition we're dealing with is constant
12954   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12955                               N0, N1, CC, DL, false);
12956   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12957   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12958
12959   // fold select_cc true, x, y -> x
12960   if (SCCC && !SCCC->isNullValue())
12961     return N2;
12962   // fold select_cc false, x, y -> y
12963   if (SCCC && SCCC->isNullValue())
12964     return N3;
12965
12966   // Check to see if we can simplify the select into an fabs node
12967   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12968     // Allow either -0.0 or 0.0
12969     if (CFP->getValueAPF().isZero()) {
12970       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12971       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12972           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12973           N2 == N3.getOperand(0))
12974         return DAG.getNode(ISD::FABS, DL, VT, N0);
12975
12976       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12977       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12978           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12979           N2.getOperand(0) == N3)
12980         return DAG.getNode(ISD::FABS, DL, VT, N3);
12981     }
12982   }
12983
12984   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12985   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12986   // in it.  This is a win when the constant is not otherwise available because
12987   // it replaces two constant pool loads with one.  We only do this if the FP
12988   // type is known to be legal, because if it isn't, then we are before legalize
12989   // types an we want the other legalization to happen first (e.g. to avoid
12990   // messing with soft float) and if the ConstantFP is not legal, because if
12991   // it is legal, we may not need to store the FP constant in a constant pool.
12992   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12993     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12994       if (TLI.isTypeLegal(N2.getValueType()) &&
12995           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12996                TargetLowering::Legal &&
12997            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12998            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12999           // If both constants have multiple uses, then we won't need to do an
13000           // extra load, they are likely around in registers for other users.
13001           (TV->hasOneUse() || FV->hasOneUse())) {
13002         Constant *Elts[] = {
13003           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13004           const_cast<ConstantFP*>(TV->getConstantFPValue())
13005         };
13006         Type *FPTy = Elts[0]->getType();
13007         const DataLayout &TD = *TLI.getDataLayout();
13008
13009         // Create a ConstantArray of the two constants.
13010         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13011         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13012                                             TD.getPrefTypeAlignment(FPTy));
13013         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13014
13015         // Get the offsets to the 0 and 1 element of the array so that we can
13016         // select between them.
13017         SDValue Zero = DAG.getIntPtrConstant(0);
13018         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13019         SDValue One = DAG.getIntPtrConstant(EltSize);
13020
13021         SDValue Cond = DAG.getSetCC(DL,
13022                                     getSetCCResultType(N0.getValueType()),
13023                                     N0, N1, CC);
13024         AddToWorklist(Cond.getNode());
13025         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13026                                           Cond, One, Zero);
13027         AddToWorklist(CstOffset.getNode());
13028         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13029                             CstOffset);
13030         AddToWorklist(CPIdx.getNode());
13031         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13032                            MachinePointerInfo::getConstantPool(), false,
13033                            false, false, Alignment);
13034
13035       }
13036     }
13037
13038   // Check to see if we can perform the "gzip trick", transforming
13039   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13040   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13041       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13042        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13043     EVT XType = N0.getValueType();
13044     EVT AType = N2.getValueType();
13045     if (XType.bitsGE(AType)) {
13046       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13047       // single-bit constant.
13048       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
13049         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13050         ShCtV = XType.getSizeInBits()-ShCtV-1;
13051         SDValue ShCt = DAG.getConstant(ShCtV,
13052                                        getShiftAmountTy(N0.getValueType()));
13053         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13054                                     XType, N0, ShCt);
13055         AddToWorklist(Shift.getNode());
13056
13057         if (XType.bitsGT(AType)) {
13058           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13059           AddToWorklist(Shift.getNode());
13060         }
13061
13062         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13063       }
13064
13065       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13066                                   XType, N0,
13067                                   DAG.getConstant(XType.getSizeInBits()-1,
13068                                          getShiftAmountTy(N0.getValueType())));
13069       AddToWorklist(Shift.getNode());
13070
13071       if (XType.bitsGT(AType)) {
13072         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13073         AddToWorklist(Shift.getNode());
13074       }
13075
13076       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13077     }
13078   }
13079
13080   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13081   // where y is has a single bit set.
13082   // A plaintext description would be, we can turn the SELECT_CC into an AND
13083   // when the condition can be materialized as an all-ones register.  Any
13084   // single bit-test can be materialized as an all-ones register with
13085   // shift-left and shift-right-arith.
13086   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13087       N0->getValueType(0) == VT &&
13088       N1C && N1C->isNullValue() &&
13089       N2C && N2C->isNullValue()) {
13090     SDValue AndLHS = N0->getOperand(0);
13091     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13092     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13093       // Shift the tested bit over the sign bit.
13094       APInt AndMask = ConstAndRHS->getAPIntValue();
13095       SDValue ShlAmt =
13096         DAG.getConstant(AndMask.countLeadingZeros(),
13097                         getShiftAmountTy(AndLHS.getValueType()));
13098       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13099
13100       // Now arithmetic right shift it all the way over, so the result is either
13101       // all-ones, or zero.
13102       SDValue ShrAmt =
13103         DAG.getConstant(AndMask.getBitWidth()-1,
13104                         getShiftAmountTy(Shl.getValueType()));
13105       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13106
13107       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13108     }
13109   }
13110
13111   // fold select C, 16, 0 -> shl C, 4
13112   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13113       TLI.getBooleanContents(N0.getValueType()) ==
13114           TargetLowering::ZeroOrOneBooleanContent) {
13115
13116     // If the caller doesn't want us to simplify this into a zext of a compare,
13117     // don't do it.
13118     if (NotExtCompare && N2C->getAPIntValue() == 1)
13119       return SDValue();
13120
13121     // Get a SetCC of the condition
13122     // NOTE: Don't create a SETCC if it's not legal on this target.
13123     if (!LegalOperations ||
13124         TLI.isOperationLegal(ISD::SETCC,
13125           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13126       SDValue Temp, SCC;
13127       // cast from setcc result type to select result type
13128       if (LegalTypes) {
13129         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13130                             N0, N1, CC);
13131         if (N2.getValueType().bitsLT(SCC.getValueType()))
13132           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13133                                         N2.getValueType());
13134         else
13135           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13136                              N2.getValueType(), SCC);
13137       } else {
13138         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13139         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13140                            N2.getValueType(), SCC);
13141       }
13142
13143       AddToWorklist(SCC.getNode());
13144       AddToWorklist(Temp.getNode());
13145
13146       if (N2C->getAPIntValue() == 1)
13147         return Temp;
13148
13149       // shl setcc result by log2 n2c
13150       return DAG.getNode(
13151           ISD::SHL, DL, N2.getValueType(), Temp,
13152           DAG.getConstant(N2C->getAPIntValue().logBase2(),
13153                           getShiftAmountTy(Temp.getValueType())));
13154     }
13155   }
13156
13157   // Check to see if this is the equivalent of setcc
13158   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13159   // otherwise, go ahead with the folds.
13160   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13161     EVT XType = N0.getValueType();
13162     if (!LegalOperations ||
13163         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13164       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13165       if (Res.getValueType() != VT)
13166         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13167       return Res;
13168     }
13169
13170     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13171     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13172         (!LegalOperations ||
13173          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13174       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13175       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13176                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13177                                        getShiftAmountTy(Ctlz.getValueType())));
13178     }
13179     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13180     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13181       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
13182                                   XType, DAG.getConstant(0, XType), N0);
13183       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
13184       return DAG.getNode(ISD::SRL, DL, XType,
13185                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13186                          DAG.getConstant(XType.getSizeInBits()-1,
13187                                          getShiftAmountTy(XType)));
13188     }
13189     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13190     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13191       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
13192                                  DAG.getConstant(XType.getSizeInBits()-1,
13193                                          getShiftAmountTy(N0.getValueType())));
13194       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
13195     }
13196   }
13197
13198   // Check to see if this is an integer abs.
13199   // select_cc setg[te] X,  0,  X, -X ->
13200   // select_cc setgt    X, -1,  X, -X ->
13201   // select_cc setl[te] X,  0, -X,  X ->
13202   // select_cc setlt    X,  1, -X,  X ->
13203   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13204   if (N1C) {
13205     ConstantSDNode *SubC = nullptr;
13206     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13207          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13208         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13209       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13210     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13211               (N1C->isOne() && CC == ISD::SETLT)) &&
13212              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13213       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13214
13215     EVT XType = N0.getValueType();
13216     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13217       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
13218                                   N0,
13219                                   DAG.getConstant(XType.getSizeInBits()-1,
13220                                          getShiftAmountTy(N0.getValueType())));
13221       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
13222                                 XType, N0, Shift);
13223       AddToWorklist(Shift.getNode());
13224       AddToWorklist(Add.getNode());
13225       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13226     }
13227   }
13228
13229   return SDValue();
13230 }
13231
13232 /// This is a stub for TargetLowering::SimplifySetCC.
13233 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13234                                    SDValue N1, ISD::CondCode Cond,
13235                                    SDLoc DL, bool foldBooleans) {
13236   TargetLowering::DAGCombinerInfo
13237     DagCombineInfo(DAG, Level, false, this);
13238   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13239 }
13240
13241 /// Given an ISD::SDIV node expressing a divide by constant, return
13242 /// a DAG expression to select that will generate the same value by multiplying
13243 /// by a magic number.
13244 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13245 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13246   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13247   if (!C)
13248     return SDValue();
13249
13250   // Avoid division by zero.
13251   if (!C->getAPIntValue())
13252     return SDValue();
13253
13254   std::vector<SDNode*> Built;
13255   SDValue S =
13256       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13257
13258   for (SDNode *N : Built)
13259     AddToWorklist(N);
13260   return S;
13261 }
13262
13263 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13264 /// DAG expression that will generate the same value by right shifting.
13265 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13266   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13267   if (!C)
13268     return SDValue();
13269
13270   // Avoid division by zero.
13271   if (!C->getAPIntValue())
13272     return SDValue();
13273
13274   std::vector<SDNode *> Built;
13275   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13276
13277   for (SDNode *N : Built)
13278     AddToWorklist(N);
13279   return S;
13280 }
13281
13282 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13283 /// expression that will generate the same value by multiplying by a magic
13284 /// number.
13285 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13286 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13287   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13288   if (!C)
13289     return SDValue();
13290
13291   // Avoid division by zero.
13292   if (!C->getAPIntValue())
13293     return SDValue();
13294
13295   std::vector<SDNode*> Built;
13296   SDValue S =
13297       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13298
13299   for (SDNode *N : Built)
13300     AddToWorklist(N);
13301   return S;
13302 }
13303
13304 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13305   if (Level >= AfterLegalizeDAG)
13306     return SDValue();
13307
13308   // Expose the DAG combiner to the target combiner implementations.
13309   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13310
13311   unsigned Iterations = 0;
13312   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13313     if (Iterations) {
13314       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13315       // For the reciprocal, we need to find the zero of the function:
13316       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13317       //     =>
13318       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13319       //     does not require additional intermediate precision]
13320       EVT VT = Op.getValueType();
13321       SDLoc DL(Op);
13322       SDValue FPOne = DAG.getConstantFP(1.0, VT);
13323
13324       AddToWorklist(Est.getNode());
13325
13326       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13327       for (unsigned i = 0; i < Iterations; ++i) {
13328         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13329         AddToWorklist(NewEst.getNode());
13330
13331         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13332         AddToWorklist(NewEst.getNode());
13333
13334         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13335         AddToWorklist(NewEst.getNode());
13336
13337         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13338         AddToWorklist(Est.getNode());
13339       }
13340     }
13341     return Est;
13342   }
13343
13344   return SDValue();
13345 }
13346
13347 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13348 /// For the reciprocal sqrt, we need to find the zero of the function:
13349 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13350 ///     =>
13351 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13352 /// As a result, we precompute A/2 prior to the iteration loop.
13353 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13354                                           unsigned Iterations) {
13355   EVT VT = Arg.getValueType();
13356   SDLoc DL(Arg);
13357   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
13358
13359   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13360   // this entire sequence requires only one FP constant.
13361   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13362   AddToWorklist(HalfArg.getNode());
13363
13364   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13365   AddToWorklist(HalfArg.getNode());
13366
13367   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13368   for (unsigned i = 0; i < Iterations; ++i) {
13369     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13370     AddToWorklist(NewEst.getNode());
13371
13372     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13373     AddToWorklist(NewEst.getNode());
13374
13375     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13376     AddToWorklist(NewEst.getNode());
13377
13378     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13379     AddToWorklist(Est.getNode());
13380   }
13381   return Est;
13382 }
13383
13384 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13385 /// For the reciprocal sqrt, we need to find the zero of the function:
13386 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13387 ///     =>
13388 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13389 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13390                                           unsigned Iterations) {
13391   EVT VT = Arg.getValueType();
13392   SDLoc DL(Arg);
13393   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13394   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13395
13396   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13397   for (unsigned i = 0; i < Iterations; ++i) {
13398     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13399     AddToWorklist(HalfEst.getNode());
13400
13401     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13402     AddToWorklist(Est.getNode());
13403
13404     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13405     AddToWorklist(Est.getNode());
13406
13407     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13408     AddToWorklist(Est.getNode());
13409
13410     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13411     AddToWorklist(Est.getNode());
13412   }
13413   return Est;
13414 }
13415
13416 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13417   if (Level >= AfterLegalizeDAG)
13418     return SDValue();
13419
13420   // Expose the DAG combiner to the target combiner implementations.
13421   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13422   unsigned Iterations = 0;
13423   bool UseOneConstNR = false;
13424   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13425     AddToWorklist(Est.getNode());
13426     if (Iterations) {
13427       Est = UseOneConstNR ?
13428         BuildRsqrtNROneConst(Op, Est, Iterations) :
13429         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13430     }
13431     return Est;
13432   }
13433
13434   return SDValue();
13435 }
13436
13437 /// Return true if base is a frame index, which is known not to alias with
13438 /// anything but itself.  Provides base object and offset as results.
13439 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13440                            const GlobalValue *&GV, const void *&CV) {
13441   // Assume it is a primitive operation.
13442   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13443
13444   // If it's an adding a simple constant then integrate the offset.
13445   if (Base.getOpcode() == ISD::ADD) {
13446     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13447       Base = Base.getOperand(0);
13448       Offset += C->getZExtValue();
13449     }
13450   }
13451
13452   // Return the underlying GlobalValue, and update the Offset.  Return false
13453   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13454   // by multiple nodes with different offsets.
13455   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13456     GV = G->getGlobal();
13457     Offset += G->getOffset();
13458     return false;
13459   }
13460
13461   // Return the underlying Constant value, and update the Offset.  Return false
13462   // for ConstantSDNodes since the same constant pool entry may be represented
13463   // by multiple nodes with different offsets.
13464   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13465     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13466                                          : (const void *)C->getConstVal();
13467     Offset += C->getOffset();
13468     return false;
13469   }
13470   // If it's any of the following then it can't alias with anything but itself.
13471   return isa<FrameIndexSDNode>(Base);
13472 }
13473
13474 /// Return true if there is any possibility that the two addresses overlap.
13475 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13476   // If they are the same then they must be aliases.
13477   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13478
13479   // If they are both volatile then they cannot be reordered.
13480   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13481
13482   // Gather base node and offset information.
13483   SDValue Base1, Base2;
13484   int64_t Offset1, Offset2;
13485   const GlobalValue *GV1, *GV2;
13486   const void *CV1, *CV2;
13487   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13488                                       Base1, Offset1, GV1, CV1);
13489   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13490                                       Base2, Offset2, GV2, CV2);
13491
13492   // If they have a same base address then check to see if they overlap.
13493   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13494     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13495              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13496
13497   // It is possible for different frame indices to alias each other, mostly
13498   // when tail call optimization reuses return address slots for arguments.
13499   // To catch this case, look up the actual index of frame indices to compute
13500   // the real alias relationship.
13501   if (isFrameIndex1 && isFrameIndex2) {
13502     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13503     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13504     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13505     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13506              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13507   }
13508
13509   // Otherwise, if we know what the bases are, and they aren't identical, then
13510   // we know they cannot alias.
13511   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13512     return false;
13513
13514   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13515   // compared to the size and offset of the access, we may be able to prove they
13516   // do not alias.  This check is conservative for now to catch cases created by
13517   // splitting vector types.
13518   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13519       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13520       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13521        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13522       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13523     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13524     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13525
13526     // There is no overlap between these relatively aligned accesses of similar
13527     // size, return no alias.
13528     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13529         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13530       return false;
13531   }
13532
13533   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13534                    ? CombinerGlobalAA
13535                    : DAG.getSubtarget().useAA();
13536 #ifndef NDEBUG
13537   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13538       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13539     UseAA = false;
13540 #endif
13541   if (UseAA &&
13542       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13543     // Use alias analysis information.
13544     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13545                                  Op1->getSrcValueOffset());
13546     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13547         Op0->getSrcValueOffset() - MinOffset;
13548     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13549         Op1->getSrcValueOffset() - MinOffset;
13550     AliasAnalysis::AliasResult AAResult =
13551         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13552                                          Overlap1,
13553                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13554                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13555                                          Overlap2,
13556                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13557     if (AAResult == AliasAnalysis::NoAlias)
13558       return false;
13559   }
13560
13561   // Otherwise we have to assume they alias.
13562   return true;
13563 }
13564
13565 /// Walk up chain skipping non-aliasing memory nodes,
13566 /// looking for aliasing nodes and adding them to the Aliases vector.
13567 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13568                                    SmallVectorImpl<SDValue> &Aliases) {
13569   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13570   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13571
13572   // Get alias information for node.
13573   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13574
13575   // Starting off.
13576   Chains.push_back(OriginalChain);
13577   unsigned Depth = 0;
13578
13579   // Look at each chain and determine if it is an alias.  If so, add it to the
13580   // aliases list.  If not, then continue up the chain looking for the next
13581   // candidate.
13582   while (!Chains.empty()) {
13583     SDValue Chain = Chains.back();
13584     Chains.pop_back();
13585
13586     // For TokenFactor nodes, look at each operand and only continue up the
13587     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13588     // find more and revert to original chain since the xform is unlikely to be
13589     // profitable.
13590     //
13591     // FIXME: The depth check could be made to return the last non-aliasing
13592     // chain we found before we hit a tokenfactor rather than the original
13593     // chain.
13594     if (Depth > 6 || Aliases.size() == 2) {
13595       Aliases.clear();
13596       Aliases.push_back(OriginalChain);
13597       return;
13598     }
13599
13600     // Don't bother if we've been before.
13601     if (!Visited.insert(Chain.getNode()).second)
13602       continue;
13603
13604     switch (Chain.getOpcode()) {
13605     case ISD::EntryToken:
13606       // Entry token is ideal chain operand, but handled in FindBetterChain.
13607       break;
13608
13609     case ISD::LOAD:
13610     case ISD::STORE: {
13611       // Get alias information for Chain.
13612       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13613           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13614
13615       // If chain is alias then stop here.
13616       if (!(IsLoad && IsOpLoad) &&
13617           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13618         Aliases.push_back(Chain);
13619       } else {
13620         // Look further up the chain.
13621         Chains.push_back(Chain.getOperand(0));
13622         ++Depth;
13623       }
13624       break;
13625     }
13626
13627     case ISD::TokenFactor:
13628       // We have to check each of the operands of the token factor for "small"
13629       // token factors, so we queue them up.  Adding the operands to the queue
13630       // (stack) in reverse order maintains the original order and increases the
13631       // likelihood that getNode will find a matching token factor (CSE.)
13632       if (Chain.getNumOperands() > 16) {
13633         Aliases.push_back(Chain);
13634         break;
13635       }
13636       for (unsigned n = Chain.getNumOperands(); n;)
13637         Chains.push_back(Chain.getOperand(--n));
13638       ++Depth;
13639       break;
13640
13641     default:
13642       // For all other instructions we will just have to take what we can get.
13643       Aliases.push_back(Chain);
13644       break;
13645     }
13646   }
13647
13648   // We need to be careful here to also search for aliases through the
13649   // value operand of a store, etc. Consider the following situation:
13650   //   Token1 = ...
13651   //   L1 = load Token1, %52
13652   //   S1 = store Token1, L1, %51
13653   //   L2 = load Token1, %52+8
13654   //   S2 = store Token1, L2, %51+8
13655   //   Token2 = Token(S1, S2)
13656   //   L3 = load Token2, %53
13657   //   S3 = store Token2, L3, %52
13658   //   L4 = load Token2, %53+8
13659   //   S4 = store Token2, L4, %52+8
13660   // If we search for aliases of S3 (which loads address %52), and we look
13661   // only through the chain, then we'll miss the trivial dependence on L1
13662   // (which also loads from %52). We then might change all loads and
13663   // stores to use Token1 as their chain operand, which could result in
13664   // copying %53 into %52 before copying %52 into %51 (which should
13665   // happen first).
13666   //
13667   // The problem is, however, that searching for such data dependencies
13668   // can become expensive, and the cost is not directly related to the
13669   // chain depth. Instead, we'll rule out such configurations here by
13670   // insisting that we've visited all chain users (except for users
13671   // of the original chain, which is not necessary). When doing this,
13672   // we need to look through nodes we don't care about (otherwise, things
13673   // like register copies will interfere with trivial cases).
13674
13675   SmallVector<const SDNode *, 16> Worklist;
13676   for (const SDNode *N : Visited)
13677     if (N != OriginalChain.getNode())
13678       Worklist.push_back(N);
13679
13680   while (!Worklist.empty()) {
13681     const SDNode *M = Worklist.pop_back_val();
13682
13683     // We have already visited M, and want to make sure we've visited any uses
13684     // of M that we care about. For uses that we've not visisted, and don't
13685     // care about, queue them to the worklist.
13686
13687     for (SDNode::use_iterator UI = M->use_begin(),
13688          UIE = M->use_end(); UI != UIE; ++UI)
13689       if (UI.getUse().getValueType() == MVT::Other &&
13690           Visited.insert(*UI).second) {
13691         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13692           // We've not visited this use, and we care about it (it could have an
13693           // ordering dependency with the original node).
13694           Aliases.clear();
13695           Aliases.push_back(OriginalChain);
13696           return;
13697         }
13698
13699         // We've not visited this use, but we don't care about it. Mark it as
13700         // visited and enqueue it to the worklist.
13701         Worklist.push_back(*UI);
13702       }
13703   }
13704 }
13705
13706 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13707 /// (aliasing node.)
13708 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13709   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13710
13711   // Accumulate all the aliases to this node.
13712   GatherAllAliases(N, OldChain, Aliases);
13713
13714   // If no operands then chain to entry token.
13715   if (Aliases.size() == 0)
13716     return DAG.getEntryNode();
13717
13718   // If a single operand then chain to it.  We don't need to revisit it.
13719   if (Aliases.size() == 1)
13720     return Aliases[0];
13721
13722   // Construct a custom tailored token factor.
13723   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13724 }
13725
13726 /// This is the entry point for the file.
13727 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13728                            CodeGenOpt::Level OptLevel) {
13729   /// This is the main entry point to this class.
13730   DAGCombiner(*this, AA, OptLevel).Run(Level);
13731 }