DAGCombiner: Continue combining if FoldConstantArithmetic() fails.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitMGATHER(SDNode *N);
311     SDValue visitMSCATTER(SDNode *N);
312     SDValue visitFP_TO_FP16(SDNode *N);
313
314     SDValue visitFADDForFMACombine(SDNode *N);
315     SDValue visitFSUBForFMACombine(SDNode *N);
316
317     SDValue XformToShuffleWithZero(SDNode *N);
318     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
319
320     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
321
322     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326                              SDValue N3, ISD::CondCode CC,
327                              bool NotExtCompare = false);
328     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329                           SDLoc DL, bool foldBooleans = true);
330
331     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332                            SDValue &CC) const;
333     bool isOneUseSetCC(SDValue N) const;
334
335     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
336                                          unsigned HiOp);
337     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338     SDValue CombineExtLoad(SDNode *N);
339     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340     SDValue BuildSDIV(SDNode *N);
341     SDValue BuildSDIVPow2(SDNode *N);
342     SDValue BuildUDIV(SDNode *N);
343     SDValue BuildReciprocalEstimate(SDValue Op);
344     SDValue BuildRsqrtEstimate(SDValue Op);
345     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348                                bool DemandHighBits = true);
349     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351                               SDValue InnerPos, SDValue InnerNeg,
352                               unsigned PosOpcode, unsigned NegOpcode,
353                               SDLoc DL);
354     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355     SDValue ReduceLoadWidth(SDNode *N);
356     SDValue ReduceLoadOpStoreWidth(SDNode *N);
357     SDValue TransformFPLoadStorePair(SDNode *N);
358     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
360
361     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
362
363     /// Walk up chain skipping non-aliasing memory nodes,
364     /// looking for aliasing nodes and adding them to the Aliases vector.
365     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366                           SmallVectorImpl<SDValue> &Aliases);
367
368     /// Return true if there is any possibility that the two addresses overlap.
369     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
370
371     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372     /// chain (aliasing node.)
373     SDValue FindBetterChain(SDNode *N, SDValue Chain);
374
375     /// Holds a pointer to an LSBaseSDNode as well as information on where it
376     /// is located in a sequence of memory operations connected by a chain.
377     struct MemOpLink {
378       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380       // Ptr to the mem node.
381       LSBaseSDNode *MemNode;
382       // Offset from the base ptr.
383       int64_t OffsetFromBase;
384       // What is the sequence number of this mem node.
385       // Lowest mem operand in the DAG starts at zero.
386       unsigned SequenceNum;
387     };
388
389     /// This is a helper function for MergeConsecutiveStores. When the source
390     /// elements of the consecutive stores are all constants or all extracted
391     /// vector elements, try to merge them into one larger store.
392     /// \return True if a merged store was created.
393     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394                                          EVT MemVT, unsigned NumElem,
395                                          bool IsConstantSrc, bool UseVector);
396
397     /// Merge consecutive store operations into a wide store.
398     /// This optimization uses wide integers or vectors when possible.
399     /// \return True if some memory operations were changed.
400     bool MergeConsecutiveStores(StoreSDNode *N);
401
402     /// \brief Try to transform a truncation where C is a constant:
403     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
404     ///
405     /// \p N needs to be a truncation and its first operand an AND. Other
406     /// requirements are checked by the function (e.g. that trunc is
407     /// single-use) and if missed an empty SDValue is returned.
408     SDValue distributeTruncateThroughAnd(SDNode *N);
409
410   public:
411     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414       auto *F = DAG.getMachineFunction().getFunction();
415       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416                     F->hasFnAttribute(Attribute::MinSize);
417     }
418
419     /// Runs the dag combiner on all nodes in the work list
420     void Run(CombineLevel AtLevel);
421
422     SelectionDAG &getDAG() const { return DAG; }
423
424     /// Returns a type large enough to hold any valid shift amount - before type
425     /// legalization these can be huge.
426     EVT getShiftAmountTy(EVT LHSTy) {
427       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428       if (LHSTy.isVector())
429         return LHSTy;
430       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431                         : TLI.getPointerTy();
432     }
433
434     /// This method returns true if we are running before type legalization or
435     /// if the specified VT is legal.
436     bool isTypeLegal(const EVT &VT) {
437       if (!LegalTypes) return true;
438       return TLI.isTypeLegal(VT);
439     }
440
441     /// Convenience wrapper around TargetLowering::getSetCCResultType
442     EVT getSetCCResultType(EVT VT) const {
443       return TLI.getSetCCResultType(*DAG.getContext(), VT);
444     }
445   };
446 }
447
448
449 namespace {
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453   DAGCombiner &DC;
454 public:
455   explicit WorklistRemover(DAGCombiner &dc)
456     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
457
458   void NodeDeleted(SDNode *N, SDNode *E) override {
459     DC.removeFromWorklist(N);
460   }
461 };
462 }
463
464 //===----------------------------------------------------------------------===//
465 //  TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
467
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469   ((DAGCombiner*)DC)->AddToWorklist(N);
470 }
471
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473   ((DAGCombiner*)DC)->removeFromWorklist(N);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 }
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
484 }
485
486
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 }
491
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 }
496
497 //===----------------------------------------------------------------------===//
498 // Helper Functions
499 //===----------------------------------------------------------------------===//
500
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502   removeFromWorklist(N);
503
504   // If the operands of this node are only used by the node, they will now be
505   // dead. Make sure to re-visit them and recursively delete dead nodes.
506   for (const SDValue &Op : N->ops())
507     // For an operand generating multiple values, one of the values may
508     // become dead allowing further simplification (e.g. split index
509     // arithmetic from an indexed load).
510     if (Op->hasOneUse() || Op->getNumValues() > 1)
511       AddToWorklist(Op.getNode());
512
513   DAG.DeleteNode(N);
514 }
515
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520                                const TargetLowering &TLI,
521                                const TargetOptions *Options,
522                                unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return 2;
525
526   // Don't allow anything with multiple uses.
527   if (!Op.hasOneUse()) return 0;
528
529   // Don't recurse exponentially.
530   if (Depth > 6) return 0;
531
532   switch (Op.getOpcode()) {
533   default: return false;
534   case ISD::ConstantFP:
535     // Don't invert constant FP values after legalize.  The negated constant
536     // isn't necessarily legal.
537     return LegalOperations ? 0 : 1;
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     if (!Options->UnsafeFPMath) return 0;
541
542     // After operation legalization, it might not be legal to create new FSUBs.
543     if (LegalOperations &&
544         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
545       return 0;
546
547     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549                                     Options, Depth + 1))
550       return V;
551     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553                               Depth + 1);
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // fold (fneg (fsub A, B)) -> (fsub B, A)
559     return 1;
560
561   case ISD::FMUL:
562   case ISD::FDIV:
563     if (Options->HonorSignDependentRoundingFPMath()) return 0;
564
565     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572
573   case ISD::FP_EXTEND:
574   case ISD::FP_ROUND:
575   case ISD::FSIN:
576     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
577                               Depth + 1);
578   }
579 }
580
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583                                     bool LegalOperations, unsigned Depth = 0) {
584   const TargetOptions &Options = DAG.getTarget().Options;
585   // fneg is removable even if it has multiple uses.
586   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
587
588   // Don't allow anything with multiple uses.
589   assert(Op.hasOneUse() && "Unknown reuse!");
590
591   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592   switch (Op.getOpcode()) {
593   default: llvm_unreachable("Unknown code");
594   case ISD::ConstantFP: {
595     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596     V.changeSign();
597     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598   }
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     assert(Options.UnsafeFPMath);
602
603     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
606       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                          GetNegatedExpression(Op.getOperand(0), DAG,
608                                               LegalOperations, Depth+1),
609                          Op.getOperand(1));
610     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(1), DAG,
613                                             LegalOperations, Depth+1),
614                        Op.getOperand(0));
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fsub 0, B)) -> B
620     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621       if (N0CFP->getValueAPF().isZero())
622         return Op.getOperand(1);
623
624     // fold (fneg (fsub A, B)) -> (fsub B, A)
625     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626                        Op.getOperand(1), Op.getOperand(0));
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     assert(!Options.HonorSignDependentRoundingFPMath());
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
635       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                          GetNegatedExpression(Op.getOperand(0), DAG,
637                                               LegalOperations, Depth+1),
638                          Op.getOperand(1));
639
640     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(0),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1));
645
646   case ISD::FP_EXTEND:
647   case ISD::FSIN:
648     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649                        GetNegatedExpression(Op.getOperand(0), DAG,
650                                             LegalOperations, Depth+1));
651   case ISD::FP_ROUND:
652       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653                          GetNegatedExpression(Op.getOperand(0), DAG,
654                                               LegalOperations, Depth+1),
655                          Op.getOperand(1));
656   }
657 }
658
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665                                     SDValue &CC) const {
666   if (N.getOpcode() == ISD::SETCC) {
667     LHS = N.getOperand(0);
668     RHS = N.getOperand(1);
669     CC  = N.getOperand(2);
670     return true;
671   }
672
673   if (N.getOpcode() != ISD::SELECT_CC ||
674       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676     return false;
677
678   if (TLI.getBooleanContents(N.getValueType()) ==
679       TargetLowering::UndefinedBooleanContent)
680     return false;
681
682   LHS = N.getOperand(0);
683   RHS = N.getOperand(1);
684   CC  = N.getOperand(4);
685   return true;
686 }
687
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
692   SDValue N0, N1, N2;
693   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
694     return true;
695   return false;
696 }
697
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702   if (!C)
703     return false;
704
705   APInt SplatUndef;
706   unsigned SplatBitSize;
707   bool HasAnyUndefs;
708   EVT EltVT = N->getValueType(0).getVectorElementType();
709   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710                              HasAnyUndefs) &&
711           EltVT.getSizeInBits() >= SplatBitSize);
712 }
713
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717   if (isa<ConstantSDNode>(N))
718     return N.getNode();
719   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720     return N.getNode();
721   return nullptr;
722 }
723
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MGATHER:            return visitMGATHER(N);
1388   case ISD::MLOAD:              return visitMLOAD(N);
1389   case ISD::MSCATTER:           return visitMSCATTER(N);
1390   case ISD::MSTORE:             return visitMSTORE(N);
1391   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397   SDValue RV = visit(N);
1398
1399   // If nothing happened, try a target-specific DAG combine.
1400   if (!RV.getNode()) {
1401     assert(N->getOpcode() != ISD::DELETED_NODE &&
1402            "Node was deleted but visit returned NULL!");
1403
1404     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407       // Expose the DAG combiner to the target combiner impls.
1408       TargetLowering::DAGCombinerInfo
1409         DagCombineInfo(DAG, Level, false, this);
1410
1411       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412     }
1413   }
1414
1415   // If nothing happened still, try promoting the operation.
1416   if (!RV.getNode()) {
1417     switch (N->getOpcode()) {
1418     default: break;
1419     case ISD::ADD:
1420     case ISD::SUB:
1421     case ISD::MUL:
1422     case ISD::AND:
1423     case ISD::OR:
1424     case ISD::XOR:
1425       RV = PromoteIntBinOp(SDValue(N, 0));
1426       break;
1427     case ISD::SHL:
1428     case ISD::SRA:
1429     case ISD::SRL:
1430       RV = PromoteIntShiftOp(SDValue(N, 0));
1431       break;
1432     case ISD::SIGN_EXTEND:
1433     case ISD::ZERO_EXTEND:
1434     case ISD::ANY_EXTEND:
1435       RV = PromoteExtend(SDValue(N, 0));
1436       break;
1437     case ISD::LOAD:
1438       if (PromoteLoad(SDValue(N, 0)))
1439         RV = SDValue(N, 0);
1440       break;
1441     }
1442   }
1443
1444   // If N is a commutative binary node, try commuting it to enable more
1445   // sdisel CSE.
1446   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447       N->getNumValues() == 1) {
1448     SDValue N0 = N->getOperand(0);
1449     SDValue N1 = N->getOperand(1);
1450
1451     // Constant operands are canonicalized to RHS.
1452     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453       SDValue Ops[] = {N1, N0};
1454       SDNode *CSENode;
1455       if (const BinaryWithFlagsSDNode *BinNode =
1456               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458                                       BinNode->Flags.hasNoUnsignedWrap(),
1459                                       BinNode->Flags.hasNoSignedWrap(),
1460                                       BinNode->Flags.hasExact());
1461       } else {
1462         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463       }
1464       if (CSENode)
1465         return SDValue(CSENode, 0);
1466     }
1467   }
1468
1469   return RV;
1470 }
1471
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1473 /// sd operand.
1474 static SDValue getInputChainForNode(SDNode *N) {
1475   if (unsigned NumOps = N->getNumOperands()) {
1476     if (N->getOperand(0).getValueType() == MVT::Other)
1477       return N->getOperand(0);
1478     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479       return N->getOperand(NumOps-1);
1480     for (unsigned i = 1; i < NumOps-1; ++i)
1481       if (N->getOperand(i).getValueType() == MVT::Other)
1482         return N->getOperand(i);
1483   }
1484   return SDValue();
1485 }
1486
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488   // If N has two operands, where one has an input chain equal to the other,
1489   // the 'other' chain is redundant.
1490   if (N->getNumOperands() == 2) {
1491     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492       return N->getOperand(0);
1493     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494       return N->getOperand(1);
1495   }
1496
1497   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1498   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1499   SmallPtrSet<SDNode*, 16> SeenOps;
1500   bool Changed = false;             // If we should replace this token factor.
1501
1502   // Start out with this token factor.
1503   TFs.push_back(N);
1504
1505   // Iterate through token factors.  The TFs grows when new token factors are
1506   // encountered.
1507   for (unsigned i = 0; i < TFs.size(); ++i) {
1508     SDNode *TF = TFs[i];
1509
1510     // Check each of the operands.
1511     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512       SDValue Op = TF->getOperand(i);
1513
1514       switch (Op.getOpcode()) {
1515       case ISD::EntryToken:
1516         // Entry tokens don't need to be added to the list. They are
1517         // redundant.
1518         Changed = true;
1519         break;
1520
1521       case ISD::TokenFactor:
1522         if (Op.hasOneUse() &&
1523             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524           // Queue up for processing.
1525           TFs.push_back(Op.getNode());
1526           // Clean up in case the token factor is removed.
1527           AddToWorklist(Op.getNode());
1528           Changed = true;
1529           break;
1530         }
1531         // Fall thru
1532
1533       default:
1534         // Only add if it isn't already in the list.
1535         if (SeenOps.insert(Op.getNode()).second)
1536           Ops.push_back(Op);
1537         else
1538           Changed = true;
1539         break;
1540       }
1541     }
1542   }
1543
1544   SDValue Result;
1545
1546   // If we've changed things around then replace token factor.
1547   if (Changed) {
1548     if (Ops.empty()) {
1549       // The entry token is the only possible outcome.
1550       Result = DAG.getEntryNode();
1551     } else {
1552       // New and improved token factor.
1553       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1554     }
1555
1556     // Add users to worklist if AA is enabled, since it may introduce
1557     // a lot of new chained token factors while removing memory deps.
1558     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559       : DAG.getSubtarget().useAA();
1560     return CombineTo(N, Result, UseAA /*add to worklist*/);
1561   }
1562
1563   return Result;
1564 }
1565
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568   WorklistRemover DeadNodes(*this);
1569   // Replacing results may cause a different MERGE_VALUES to suddenly
1570   // be CSE'd with N, and carry its uses with it. Iterate until no
1571   // uses remain, to ensure that the node can be safely deleted.
1572   // First add the users of this node to the work list so that they
1573   // can be tried again once they have new operands.
1574   AddUsersToWorklist(N);
1575   do {
1576     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578   } while (!N->use_empty());
1579   deleteAndRecombine(N);
1580   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1581 }
1582
1583 static bool isNullConstant(SDValue V) {
1584   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1585   return Const != nullptr && Const->isNullValue();
1586 }
1587
1588 static bool isAllOnesConstant(SDValue V) {
1589   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1590   return Const != nullptr && Const->isAllOnesValue();
1591 }
1592
1593 static bool isOneConstant(SDValue V) {
1594   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1595   return Const != nullptr && Const->isOne();
1596 }
1597
1598 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1599 /// ContantSDNode pointer else nullptr.
1600 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1601   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1602   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1603 }
1604
1605 SDValue DAGCombiner::visitADD(SDNode *N) {
1606   SDValue N0 = N->getOperand(0);
1607   SDValue N1 = N->getOperand(1);
1608   EVT VT = N0.getValueType();
1609
1610   // fold vector ops
1611   if (VT.isVector()) {
1612     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1613       return FoldedVOp;
1614
1615     // fold (add x, 0) -> x, vector edition
1616     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1617       return N0;
1618     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1619       return N1;
1620   }
1621
1622   // fold (add x, undef) -> undef
1623   if (N0.getOpcode() == ISD::UNDEF)
1624     return N0;
1625   if (N1.getOpcode() == ISD::UNDEF)
1626     return N1;
1627   // fold (add c1, c2) -> c1+c2
1628   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1629   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1630   if (N0C && N1C)
1631     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1632   // canonicalize constant to RHS
1633   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1634      !isConstantIntBuildVectorOrConstantInt(N1))
1635     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1636   // fold (add x, 0) -> x
1637   if (isNullConstant(N1))
1638     return N0;
1639   // fold (add Sym, c) -> Sym+c
1640   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1641     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1642         GA->getOpcode() == ISD::GlobalAddress)
1643       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1644                                   GA->getOffset() +
1645                                     (uint64_t)N1C->getSExtValue());
1646   // fold ((c1-A)+c2) -> (c1+c2)-A
1647   if (N1C && N0.getOpcode() == ISD::SUB)
1648     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1649       SDLoc DL(N);
1650       return DAG.getNode(ISD::SUB, DL, VT,
1651                          DAG.getConstant(N1C->getAPIntValue()+
1652                                          N0C->getAPIntValue(), DL, VT),
1653                          N0.getOperand(1));
1654     }
1655   // reassociate add
1656   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1657     return RADD;
1658   // fold ((0-A) + B) -> B-A
1659   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1660     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1661   // fold (A + (0-B)) -> A-B
1662   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1663     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1664   // fold (A+(B-A)) -> B
1665   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1666     return N1.getOperand(0);
1667   // fold ((B-A)+A) -> B
1668   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1669     return N0.getOperand(0);
1670   // fold (A+(B-(A+C))) to (B-C)
1671   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1672       N0 == N1.getOperand(1).getOperand(0))
1673     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1674                        N1.getOperand(1).getOperand(1));
1675   // fold (A+(B-(C+A))) to (B-C)
1676   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1677       N0 == N1.getOperand(1).getOperand(1))
1678     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1679                        N1.getOperand(1).getOperand(0));
1680   // fold (A+((B-A)+or-C)) to (B+or-C)
1681   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1682       N1.getOperand(0).getOpcode() == ISD::SUB &&
1683       N0 == N1.getOperand(0).getOperand(1))
1684     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1685                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1686
1687   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1688   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1689     SDValue N00 = N0.getOperand(0);
1690     SDValue N01 = N0.getOperand(1);
1691     SDValue N10 = N1.getOperand(0);
1692     SDValue N11 = N1.getOperand(1);
1693
1694     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1695       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1696                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1697                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1698   }
1699
1700   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1701     return SDValue(N, 0);
1702
1703   // fold (a+b) -> (a|b) iff a and b share no bits.
1704   if (VT.isInteger() && !VT.isVector()) {
1705     APInt LHSZero, LHSOne;
1706     APInt RHSZero, RHSOne;
1707     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1708
1709     if (LHSZero.getBoolValue()) {
1710       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1711
1712       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1713       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1714       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1715         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1716           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1717       }
1718     }
1719   }
1720
1721   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1722   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1723       isNullConstant(N1.getOperand(0).getOperand(0)))
1724     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1725                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1726                                    N1.getOperand(0).getOperand(1),
1727                                    N1.getOperand(1)));
1728   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1729       isNullConstant(N0.getOperand(0).getOperand(0)))
1730     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1731                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1732                                    N0.getOperand(0).getOperand(1),
1733                                    N0.getOperand(1)));
1734
1735   if (N1.getOpcode() == ISD::AND) {
1736     SDValue AndOp0 = N1.getOperand(0);
1737     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1738     unsigned DestBits = VT.getScalarType().getSizeInBits();
1739
1740     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1741     // and similar xforms where the inner op is either ~0 or 0.
1742     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1743       SDLoc DL(N);
1744       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1745     }
1746   }
1747
1748   // add (sext i1), X -> sub X, (zext i1)
1749   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1750       N0.getOperand(0).getValueType() == MVT::i1 &&
1751       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1752     SDLoc DL(N);
1753     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1754     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1755   }
1756
1757   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1758   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1759     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1760     if (TN->getVT() == MVT::i1) {
1761       SDLoc DL(N);
1762       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1763                                  DAG.getConstant(1, DL, VT));
1764       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1765     }
1766   }
1767
1768   return SDValue();
1769 }
1770
1771 SDValue DAGCombiner::visitADDC(SDNode *N) {
1772   SDValue N0 = N->getOperand(0);
1773   SDValue N1 = N->getOperand(1);
1774   EVT VT = N0.getValueType();
1775
1776   // If the flag result is dead, turn this into an ADD.
1777   if (!N->hasAnyUseOfValue(1))
1778     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1779                      DAG.getNode(ISD::CARRY_FALSE,
1780                                  SDLoc(N), MVT::Glue));
1781
1782   // canonicalize constant to RHS.
1783   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1784   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1785   if (N0C && !N1C)
1786     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1787
1788   // fold (addc x, 0) -> x + no carry out
1789   if (isNullConstant(N1))
1790     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1791                                         SDLoc(N), MVT::Glue));
1792
1793   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1794   APInt LHSZero, LHSOne;
1795   APInt RHSZero, RHSOne;
1796   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1797
1798   if (LHSZero.getBoolValue()) {
1799     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1800
1801     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1802     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1803     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1804       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1805                        DAG.getNode(ISD::CARRY_FALSE,
1806                                    SDLoc(N), MVT::Glue));
1807   }
1808
1809   return SDValue();
1810 }
1811
1812 SDValue DAGCombiner::visitADDE(SDNode *N) {
1813   SDValue N0 = N->getOperand(0);
1814   SDValue N1 = N->getOperand(1);
1815   SDValue CarryIn = N->getOperand(2);
1816
1817   // canonicalize constant to RHS
1818   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1819   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1820   if (N0C && !N1C)
1821     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1822                        N1, N0, CarryIn);
1823
1824   // fold (adde x, y, false) -> (addc x, y)
1825   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1826     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1827
1828   return SDValue();
1829 }
1830
1831 // Since it may not be valid to emit a fold to zero for vector initializers
1832 // check if we can before folding.
1833 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1834                              SelectionDAG &DAG,
1835                              bool LegalOperations, bool LegalTypes) {
1836   if (!VT.isVector())
1837     return DAG.getConstant(0, DL, VT);
1838   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1839     return DAG.getConstant(0, DL, VT);
1840   return SDValue();
1841 }
1842
1843 SDValue DAGCombiner::visitSUB(SDNode *N) {
1844   SDValue N0 = N->getOperand(0);
1845   SDValue N1 = N->getOperand(1);
1846   EVT VT = N0.getValueType();
1847
1848   // fold vector ops
1849   if (VT.isVector()) {
1850     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1851       return FoldedVOp;
1852
1853     // fold (sub x, 0) -> x, vector edition
1854     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1855       return N0;
1856   }
1857
1858   // fold (sub x, x) -> 0
1859   // FIXME: Refactor this and xor and other similar operations together.
1860   if (N0 == N1)
1861     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1862   // fold (sub c1, c2) -> c1-c2
1863   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1864   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1865   if (N0C && N1C)
1866     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1867   // fold (sub x, c) -> (add x, -c)
1868   if (N1C) {
1869     SDLoc DL(N);
1870     return DAG.getNode(ISD::ADD, DL, VT, N0,
1871                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1872   }
1873   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1874   if (isAllOnesConstant(N0))
1875     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1876   // fold A-(A-B) -> B
1877   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1878     return N1.getOperand(1);
1879   // fold (A+B)-A -> B
1880   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1881     return N0.getOperand(1);
1882   // fold (A+B)-B -> A
1883   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1884     return N0.getOperand(0);
1885   // fold C2-(A+C1) -> (C2-C1)-A
1886   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1887     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1888   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1889     SDLoc DL(N);
1890     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1891                                    DL, VT);
1892     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1893                        N1.getOperand(0));
1894   }
1895   // fold ((A+(B+or-C))-B) -> A+or-C
1896   if (N0.getOpcode() == ISD::ADD &&
1897       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1898        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1899       N0.getOperand(1).getOperand(0) == N1)
1900     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1901                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1902   // fold ((A+(C+B))-B) -> A+C
1903   if (N0.getOpcode() == ISD::ADD &&
1904       N0.getOperand(1).getOpcode() == ISD::ADD &&
1905       N0.getOperand(1).getOperand(1) == N1)
1906     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1907                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1908   // fold ((A-(B-C))-C) -> A-B
1909   if (N0.getOpcode() == ISD::SUB &&
1910       N0.getOperand(1).getOpcode() == ISD::SUB &&
1911       N0.getOperand(1).getOperand(1) == N1)
1912     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1913                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1914
1915   // If either operand of a sub is undef, the result is undef
1916   if (N0.getOpcode() == ISD::UNDEF)
1917     return N0;
1918   if (N1.getOpcode() == ISD::UNDEF)
1919     return N1;
1920
1921   // If the relocation model supports it, consider symbol offsets.
1922   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1923     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1924       // fold (sub Sym, c) -> Sym-c
1925       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1926         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1927                                     GA->getOffset() -
1928                                       (uint64_t)N1C->getSExtValue());
1929       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1930       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1931         if (GA->getGlobal() == GB->getGlobal())
1932           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1933                                  SDLoc(N), VT);
1934     }
1935
1936   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1937   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1938     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1939     if (TN->getVT() == MVT::i1) {
1940       SDLoc DL(N);
1941       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1942                                  DAG.getConstant(1, DL, VT));
1943       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1944     }
1945   }
1946
1947   return SDValue();
1948 }
1949
1950 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1951   SDValue N0 = N->getOperand(0);
1952   SDValue N1 = N->getOperand(1);
1953   EVT VT = N0.getValueType();
1954
1955   // If the flag result is dead, turn this into an SUB.
1956   if (!N->hasAnyUseOfValue(1))
1957     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1958                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1959                                  MVT::Glue));
1960
1961   // fold (subc x, x) -> 0 + no borrow
1962   if (N0 == N1) {
1963     SDLoc DL(N);
1964     return CombineTo(N, DAG.getConstant(0, DL, VT),
1965                      DAG.getNode(ISD::CARRY_FALSE, DL,
1966                                  MVT::Glue));
1967   }
1968
1969   // fold (subc x, 0) -> x + no borrow
1970   if (isNullConstant(N1))
1971     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1972                                         MVT::Glue));
1973
1974   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1975   if (isAllOnesConstant(N0))
1976     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1977                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1978                                  MVT::Glue));
1979
1980   return SDValue();
1981 }
1982
1983 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1984   SDValue N0 = N->getOperand(0);
1985   SDValue N1 = N->getOperand(1);
1986   SDValue CarryIn = N->getOperand(2);
1987
1988   // fold (sube x, y, false) -> (subc x, y)
1989   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1990     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1991
1992   return SDValue();
1993 }
1994
1995 SDValue DAGCombiner::visitMUL(SDNode *N) {
1996   SDValue N0 = N->getOperand(0);
1997   SDValue N1 = N->getOperand(1);
1998   EVT VT = N0.getValueType();
1999
2000   // fold (mul x, undef) -> 0
2001   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2002     return DAG.getConstant(0, SDLoc(N), VT);
2003
2004   bool N0IsConst = false;
2005   bool N1IsConst = false;
2006   bool N1IsOpaqueConst = false;
2007   bool N0IsOpaqueConst = false;
2008   APInt ConstValue0, ConstValue1;
2009   // fold vector ops
2010   if (VT.isVector()) {
2011     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2012       return FoldedVOp;
2013
2014     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2015     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2016   } else {
2017     N0IsConst = isa<ConstantSDNode>(N0);
2018     if (N0IsConst) {
2019       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2020       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2021     }
2022     N1IsConst = isa<ConstantSDNode>(N1);
2023     if (N1IsConst) {
2024       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2025       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2026     }
2027   }
2028
2029   // fold (mul c1, c2) -> c1*c2
2030   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2031     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2032                                       N0.getNode(), N1.getNode());
2033
2034   // canonicalize constant to RHS (vector doesn't have to splat)
2035   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2036      !isConstantIntBuildVectorOrConstantInt(N1))
2037     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2038   // fold (mul x, 0) -> 0
2039   if (N1IsConst && ConstValue1 == 0)
2040     return N1;
2041   // We require a splat of the entire scalar bit width for non-contiguous
2042   // bit patterns.
2043   bool IsFullSplat =
2044     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2045   // fold (mul x, 1) -> x
2046   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2047     return N0;
2048   // fold (mul x, -1) -> 0-x
2049   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2050     SDLoc DL(N);
2051     return DAG.getNode(ISD::SUB, DL, VT,
2052                        DAG.getConstant(0, DL, VT), N0);
2053   }
2054   // fold (mul x, (1 << c)) -> x << c
2055   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2056       IsFullSplat) {
2057     SDLoc DL(N);
2058     return DAG.getNode(ISD::SHL, DL, VT, N0,
2059                        DAG.getConstant(ConstValue1.logBase2(), DL,
2060                                        getShiftAmountTy(N0.getValueType())));
2061   }
2062   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2063   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2064       IsFullSplat) {
2065     unsigned Log2Val = (-ConstValue1).logBase2();
2066     SDLoc DL(N);
2067     // FIXME: If the input is something that is easily negated (e.g. a
2068     // single-use add), we should put the negate there.
2069     return DAG.getNode(ISD::SUB, DL, VT,
2070                        DAG.getConstant(0, DL, VT),
2071                        DAG.getNode(ISD::SHL, DL, VT, N0,
2072                             DAG.getConstant(Log2Val, DL,
2073                                       getShiftAmountTy(N0.getValueType()))));
2074   }
2075
2076   APInt Val;
2077   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2078   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2079       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2080                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2081     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2082                              N1, N0.getOperand(1));
2083     AddToWorklist(C3.getNode());
2084     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2085                        N0.getOperand(0), C3);
2086   }
2087
2088   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2089   // use.
2090   {
2091     SDValue Sh(nullptr,0), Y(nullptr,0);
2092     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2093     if (N0.getOpcode() == ISD::SHL &&
2094         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2095                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2096         N0.getNode()->hasOneUse()) {
2097       Sh = N0; Y = N1;
2098     } else if (N1.getOpcode() == ISD::SHL &&
2099                isa<ConstantSDNode>(N1.getOperand(1)) &&
2100                N1.getNode()->hasOneUse()) {
2101       Sh = N1; Y = N0;
2102     }
2103
2104     if (Sh.getNode()) {
2105       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2106                                 Sh.getOperand(0), Y);
2107       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2108                          Mul, Sh.getOperand(1));
2109     }
2110   }
2111
2112   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2113   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2114       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115                      isa<ConstantSDNode>(N0.getOperand(1))))
2116     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2117                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2118                                    N0.getOperand(0), N1),
2119                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2120                                    N0.getOperand(1), N1));
2121
2122   // reassociate mul
2123   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2124     return RMUL;
2125
2126   return SDValue();
2127 }
2128
2129 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2130   SDValue N0 = N->getOperand(0);
2131   SDValue N1 = N->getOperand(1);
2132   EVT VT = N->getValueType(0);
2133
2134   // fold vector ops
2135   if (VT.isVector())
2136     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2137       return FoldedVOp;
2138
2139   // fold (sdiv c1, c2) -> c1/c2
2140   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2141   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2142   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2143     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2144   // fold (sdiv X, 1) -> X
2145   if (N1C && N1C->isOne())
2146     return N0;
2147   // fold (sdiv X, -1) -> 0-X
2148   if (N1C && N1C->isAllOnesValue()) {
2149     SDLoc DL(N);
2150     return DAG.getNode(ISD::SUB, DL, VT,
2151                        DAG.getConstant(0, DL, VT), N0);
2152   }
2153   // If we know the sign bits of both operands are zero, strength reduce to a
2154   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2155   if (!VT.isVector()) {
2156     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2157       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2158                          N0, N1);
2159   }
2160
2161   // fold (sdiv X, pow2) -> simple ops after legalize
2162   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2163       (N1C->getAPIntValue().isPowerOf2() ||
2164        (-N1C->getAPIntValue()).isPowerOf2())) {
2165     // If dividing by powers of two is cheap, then don't perform the following
2166     // fold.
2167     if (TLI.isPow2SDivCheap())
2168       return SDValue();
2169
2170     // Target-specific implementation of sdiv x, pow2.
2171     SDValue Res = BuildSDIVPow2(N);
2172     if (Res.getNode())
2173       return Res;
2174
2175     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2176     SDLoc DL(N);
2177
2178     // Splat the sign bit into the register
2179     SDValue SGN =
2180         DAG.getNode(ISD::SRA, DL, VT, N0,
2181                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2182                                     getShiftAmountTy(N0.getValueType())));
2183     AddToWorklist(SGN.getNode());
2184
2185     // Add (N0 < 0) ? abs2 - 1 : 0;
2186     SDValue SRL =
2187         DAG.getNode(ISD::SRL, DL, VT, SGN,
2188                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2189                                     getShiftAmountTy(SGN.getValueType())));
2190     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2191     AddToWorklist(SRL.getNode());
2192     AddToWorklist(ADD.getNode());    // Divide by pow2
2193     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2194                   DAG.getConstant(lg2, DL,
2195                                   getShiftAmountTy(ADD.getValueType())));
2196
2197     // If we're dividing by a positive value, we're done.  Otherwise, we must
2198     // negate the result.
2199     if (N1C->getAPIntValue().isNonNegative())
2200       return SRA;
2201
2202     AddToWorklist(SRA.getNode());
2203     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2204   }
2205
2206   // If integer divide is expensive and we satisfy the requirements, emit an
2207   // alternate sequence.
2208   if (N1C && !TLI.isIntDivCheap()) {
2209     SDValue Op = BuildSDIV(N);
2210     if (Op.getNode()) return Op;
2211   }
2212
2213   // undef / X -> 0
2214   if (N0.getOpcode() == ISD::UNDEF)
2215     return DAG.getConstant(0, SDLoc(N), VT);
2216   // X / undef -> undef
2217   if (N1.getOpcode() == ISD::UNDEF)
2218     return N1;
2219
2220   return SDValue();
2221 }
2222
2223 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2224   SDValue N0 = N->getOperand(0);
2225   SDValue N1 = N->getOperand(1);
2226   EVT VT = N->getValueType(0);
2227
2228   // fold vector ops
2229   if (VT.isVector())
2230     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2231       return FoldedVOp;
2232
2233   // fold (udiv c1, c2) -> c1/c2
2234   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2235   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2236   if (N0C && N1C)
2237     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2238                                                     N0C, N1C))
2239       return Folded;
2240   // fold (udiv x, (1 << c)) -> x >>u c
2241   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2242     SDLoc DL(N);
2243     return DAG.getNode(ISD::SRL, DL, VT, N0,
2244                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2245                                        getShiftAmountTy(N0.getValueType())));
2246   }
2247   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2248   if (N1.getOpcode() == ISD::SHL) {
2249     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2250       if (SHC->getAPIntValue().isPowerOf2()) {
2251         EVT ADDVT = N1.getOperand(1).getValueType();
2252         SDLoc DL(N);
2253         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2254                                   N1.getOperand(1),
2255                                   DAG.getConstant(SHC->getAPIntValue()
2256                                                                   .logBase2(),
2257                                                   DL, ADDVT));
2258         AddToWorklist(Add.getNode());
2259         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2260       }
2261     }
2262   }
2263   // fold (udiv x, c) -> alternate
2264   if (N1C && !TLI.isIntDivCheap()) {
2265     SDValue Op = BuildUDIV(N);
2266     if (Op.getNode()) return Op;
2267   }
2268
2269   // undef / X -> 0
2270   if (N0.getOpcode() == ISD::UNDEF)
2271     return DAG.getConstant(0, SDLoc(N), VT);
2272   // X / undef -> undef
2273   if (N1.getOpcode() == ISD::UNDEF)
2274     return N1;
2275
2276   return SDValue();
2277 }
2278
2279 SDValue DAGCombiner::visitSREM(SDNode *N) {
2280   SDValue N0 = N->getOperand(0);
2281   SDValue N1 = N->getOperand(1);
2282   EVT VT = N->getValueType(0);
2283
2284   // fold (srem c1, c2) -> c1%c2
2285   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2286   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2287   if (N0C && N1C)
2288     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2289                                                     N0C, N1C))
2290       return Folded;
2291   // If we know the sign bits of both operands are zero, strength reduce to a
2292   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2293   if (!VT.isVector()) {
2294     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2295       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2296   }
2297
2298   // If X/C can be simplified by the division-by-constant logic, lower
2299   // X%C to the equivalent of X-X/C*C.
2300   if (N1C && !N1C->isNullValue()) {
2301     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2302     AddToWorklist(Div.getNode());
2303     SDValue OptimizedDiv = combine(Div.getNode());
2304     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2305       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2306                                 OptimizedDiv, N1);
2307       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2308       AddToWorklist(Mul.getNode());
2309       return Sub;
2310     }
2311   }
2312
2313   // undef % X -> 0
2314   if (N0.getOpcode() == ISD::UNDEF)
2315     return DAG.getConstant(0, SDLoc(N), VT);
2316   // X % undef -> undef
2317   if (N1.getOpcode() == ISD::UNDEF)
2318     return N1;
2319
2320   return SDValue();
2321 }
2322
2323 SDValue DAGCombiner::visitUREM(SDNode *N) {
2324   SDValue N0 = N->getOperand(0);
2325   SDValue N1 = N->getOperand(1);
2326   EVT VT = N->getValueType(0);
2327
2328   // fold (urem c1, c2) -> c1%c2
2329   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2330   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2331   if (N0C && N1C)
2332     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2333                                                     N0C, N1C))
2334       return Folded;
2335   // fold (urem x, pow2) -> (and x, pow2-1)
2336   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2337       N1C->getAPIntValue().isPowerOf2()) {
2338     SDLoc DL(N);
2339     return DAG.getNode(ISD::AND, DL, VT, N0,
2340                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2341   }
2342   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2343   if (N1.getOpcode() == ISD::SHL) {
2344     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2345       if (SHC->getAPIntValue().isPowerOf2()) {
2346         SDLoc DL(N);
2347         SDValue Add =
2348           DAG.getNode(ISD::ADD, DL, VT, N1,
2349                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2350                                  VT));
2351         AddToWorklist(Add.getNode());
2352         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2353       }
2354     }
2355   }
2356
2357   // If X/C can be simplified by the division-by-constant logic, lower
2358   // X%C to the equivalent of X-X/C*C.
2359   if (N1C && !N1C->isNullValue()) {
2360     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2361     AddToWorklist(Div.getNode());
2362     SDValue OptimizedDiv = combine(Div.getNode());
2363     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2364       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2365                                 OptimizedDiv, N1);
2366       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2367       AddToWorklist(Mul.getNode());
2368       return Sub;
2369     }
2370   }
2371
2372   // undef % X -> 0
2373   if (N0.getOpcode() == ISD::UNDEF)
2374     return DAG.getConstant(0, SDLoc(N), VT);
2375   // X % undef -> undef
2376   if (N1.getOpcode() == ISD::UNDEF)
2377     return N1;
2378
2379   return SDValue();
2380 }
2381
2382 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2383   SDValue N0 = N->getOperand(0);
2384   SDValue N1 = N->getOperand(1);
2385   EVT VT = N->getValueType(0);
2386   SDLoc DL(N);
2387
2388   // fold (mulhs x, 0) -> 0
2389   if (isNullConstant(N1))
2390     return N1;
2391   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2392   if (isOneConstant(N1)) {
2393     SDLoc DL(N);
2394     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2395                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2396                                        DL,
2397                                        getShiftAmountTy(N0.getValueType())));
2398   }
2399   // fold (mulhs x, undef) -> 0
2400   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2401     return DAG.getConstant(0, SDLoc(N), VT);
2402
2403   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2404   // plus a shift.
2405   if (VT.isSimple() && !VT.isVector()) {
2406     MVT Simple = VT.getSimpleVT();
2407     unsigned SimpleSize = Simple.getSizeInBits();
2408     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2409     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2410       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2411       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2412       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2413       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2414             DAG.getConstant(SimpleSize, DL,
2415                             getShiftAmountTy(N1.getValueType())));
2416       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2417     }
2418   }
2419
2420   return SDValue();
2421 }
2422
2423 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2424   SDValue N0 = N->getOperand(0);
2425   SDValue N1 = N->getOperand(1);
2426   EVT VT = N->getValueType(0);
2427   SDLoc DL(N);
2428
2429   // fold (mulhu x, 0) -> 0
2430   if (isNullConstant(N1))
2431     return N1;
2432   // fold (mulhu x, 1) -> 0
2433   if (isOneConstant(N1))
2434     return DAG.getConstant(0, DL, N0.getValueType());
2435   // fold (mulhu x, undef) -> 0
2436   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2437     return DAG.getConstant(0, DL, VT);
2438
2439   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2440   // plus a shift.
2441   if (VT.isSimple() && !VT.isVector()) {
2442     MVT Simple = VT.getSimpleVT();
2443     unsigned SimpleSize = Simple.getSizeInBits();
2444     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2445     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2446       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2447       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2448       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2449       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2450             DAG.getConstant(SimpleSize, DL,
2451                             getShiftAmountTy(N1.getValueType())));
2452       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2453     }
2454   }
2455
2456   return SDValue();
2457 }
2458
2459 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2460 /// give the opcodes for the two computations that are being performed. Return
2461 /// true if a simplification was made.
2462 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2463                                                 unsigned HiOp) {
2464   // If the high half is not needed, just compute the low half.
2465   bool HiExists = N->hasAnyUseOfValue(1);
2466   if (!HiExists &&
2467       (!LegalOperations ||
2468        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2469     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2470     return CombineTo(N, Res, Res);
2471   }
2472
2473   // If the low half is not needed, just compute the high half.
2474   bool LoExists = N->hasAnyUseOfValue(0);
2475   if (!LoExists &&
2476       (!LegalOperations ||
2477        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2478     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2479     return CombineTo(N, Res, Res);
2480   }
2481
2482   // If both halves are used, return as it is.
2483   if (LoExists && HiExists)
2484     return SDValue();
2485
2486   // If the two computed results can be simplified separately, separate them.
2487   if (LoExists) {
2488     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2489     AddToWorklist(Lo.getNode());
2490     SDValue LoOpt = combine(Lo.getNode());
2491     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2492         (!LegalOperations ||
2493          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2494       return CombineTo(N, LoOpt, LoOpt);
2495   }
2496
2497   if (HiExists) {
2498     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2499     AddToWorklist(Hi.getNode());
2500     SDValue HiOpt = combine(Hi.getNode());
2501     if (HiOpt.getNode() && HiOpt != Hi &&
2502         (!LegalOperations ||
2503          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2504       return CombineTo(N, HiOpt, HiOpt);
2505   }
2506
2507   return SDValue();
2508 }
2509
2510 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2511   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2512   if (Res.getNode()) return Res;
2513
2514   EVT VT = N->getValueType(0);
2515   SDLoc DL(N);
2516
2517   // If the type is twice as wide is legal, transform the mulhu to a wider
2518   // multiply plus a shift.
2519   if (VT.isSimple() && !VT.isVector()) {
2520     MVT Simple = VT.getSimpleVT();
2521     unsigned SimpleSize = Simple.getSizeInBits();
2522     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2523     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2524       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2525       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2526       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2527       // Compute the high part as N1.
2528       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2529             DAG.getConstant(SimpleSize, DL,
2530                             getShiftAmountTy(Lo.getValueType())));
2531       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2532       // Compute the low part as N0.
2533       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2534       return CombineTo(N, Lo, Hi);
2535     }
2536   }
2537
2538   return SDValue();
2539 }
2540
2541 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2542   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2543   if (Res.getNode()) return Res;
2544
2545   EVT VT = N->getValueType(0);
2546   SDLoc DL(N);
2547
2548   // If the type is twice as wide is legal, transform the mulhu to a wider
2549   // multiply plus a shift.
2550   if (VT.isSimple() && !VT.isVector()) {
2551     MVT Simple = VT.getSimpleVT();
2552     unsigned SimpleSize = Simple.getSizeInBits();
2553     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2554     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2555       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2556       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2557       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2558       // Compute the high part as N1.
2559       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2560             DAG.getConstant(SimpleSize, DL,
2561                             getShiftAmountTy(Lo.getValueType())));
2562       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2563       // Compute the low part as N0.
2564       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2565       return CombineTo(N, Lo, Hi);
2566     }
2567   }
2568
2569   return SDValue();
2570 }
2571
2572 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2573   // (smulo x, 2) -> (saddo x, x)
2574   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2575     if (C2->getAPIntValue() == 2)
2576       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2577                          N->getOperand(0), N->getOperand(0));
2578
2579   return SDValue();
2580 }
2581
2582 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2583   // (umulo x, 2) -> (uaddo x, x)
2584   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2585     if (C2->getAPIntValue() == 2)
2586       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2587                          N->getOperand(0), N->getOperand(0));
2588
2589   return SDValue();
2590 }
2591
2592 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2593   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2594   if (Res.getNode()) return Res;
2595
2596   return SDValue();
2597 }
2598
2599 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2600   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2601   if (Res.getNode()) return Res;
2602
2603   return SDValue();
2604 }
2605
2606 /// If this is a binary operator with two operands of the same opcode, try to
2607 /// simplify it.
2608 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2609   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2610   EVT VT = N0.getValueType();
2611   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2612
2613   // Bail early if none of these transforms apply.
2614   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2615
2616   // For each of OP in AND/OR/XOR:
2617   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2618   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2619   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2620   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2621   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2622   //
2623   // do not sink logical op inside of a vector extend, since it may combine
2624   // into a vsetcc.
2625   EVT Op0VT = N0.getOperand(0).getValueType();
2626   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2627        N0.getOpcode() == ISD::SIGN_EXTEND ||
2628        N0.getOpcode() == ISD::BSWAP ||
2629        // Avoid infinite looping with PromoteIntBinOp.
2630        (N0.getOpcode() == ISD::ANY_EXTEND &&
2631         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2632        (N0.getOpcode() == ISD::TRUNCATE &&
2633         (!TLI.isZExtFree(VT, Op0VT) ||
2634          !TLI.isTruncateFree(Op0VT, VT)) &&
2635         TLI.isTypeLegal(Op0VT))) &&
2636       !VT.isVector() &&
2637       Op0VT == N1.getOperand(0).getValueType() &&
2638       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2639     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2640                                  N0.getOperand(0).getValueType(),
2641                                  N0.getOperand(0), N1.getOperand(0));
2642     AddToWorklist(ORNode.getNode());
2643     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2644   }
2645
2646   // For each of OP in SHL/SRL/SRA/AND...
2647   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2648   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2649   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2650   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2651        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2652       N0.getOperand(1) == N1.getOperand(1)) {
2653     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2654                                  N0.getOperand(0).getValueType(),
2655                                  N0.getOperand(0), N1.getOperand(0));
2656     AddToWorklist(ORNode.getNode());
2657     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2658                        ORNode, N0.getOperand(1));
2659   }
2660
2661   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2662   // Only perform this optimization after type legalization and before
2663   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2664   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2665   // we don't want to undo this promotion.
2666   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2667   // on scalars.
2668   if ((N0.getOpcode() == ISD::BITCAST ||
2669        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2670       Level == AfterLegalizeTypes) {
2671     SDValue In0 = N0.getOperand(0);
2672     SDValue In1 = N1.getOperand(0);
2673     EVT In0Ty = In0.getValueType();
2674     EVT In1Ty = In1.getValueType();
2675     SDLoc DL(N);
2676     // If both incoming values are integers, and the original types are the
2677     // same.
2678     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2679       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2680       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2681       AddToWorklist(Op.getNode());
2682       return BC;
2683     }
2684   }
2685
2686   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2687   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2688   // If both shuffles use the same mask, and both shuffle within a single
2689   // vector, then it is worthwhile to move the swizzle after the operation.
2690   // The type-legalizer generates this pattern when loading illegal
2691   // vector types from memory. In many cases this allows additional shuffle
2692   // optimizations.
2693   // There are other cases where moving the shuffle after the xor/and/or
2694   // is profitable even if shuffles don't perform a swizzle.
2695   // If both shuffles use the same mask, and both shuffles have the same first
2696   // or second operand, then it might still be profitable to move the shuffle
2697   // after the xor/and/or operation.
2698   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2699     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2700     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2701
2702     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2703            "Inputs to shuffles are not the same type");
2704
2705     // Check that both shuffles use the same mask. The masks are known to be of
2706     // the same length because the result vector type is the same.
2707     // Check also that shuffles have only one use to avoid introducing extra
2708     // instructions.
2709     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2710         SVN0->getMask().equals(SVN1->getMask())) {
2711       SDValue ShOp = N0->getOperand(1);
2712
2713       // Don't try to fold this node if it requires introducing a
2714       // build vector of all zeros that might be illegal at this stage.
2715       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2716         if (!LegalTypes)
2717           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2718         else
2719           ShOp = SDValue();
2720       }
2721
2722       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2723       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2724       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2725       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2726         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2727                                       N0->getOperand(0), N1->getOperand(0));
2728         AddToWorklist(NewNode.getNode());
2729         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2730                                     &SVN0->getMask()[0]);
2731       }
2732
2733       // Don't try to fold this node if it requires introducing a
2734       // build vector of all zeros that might be illegal at this stage.
2735       ShOp = N0->getOperand(0);
2736       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2737         if (!LegalTypes)
2738           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2739         else
2740           ShOp = SDValue();
2741       }
2742
2743       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2744       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2745       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2746       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2747         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2748                                       N0->getOperand(1), N1->getOperand(1));
2749         AddToWorklist(NewNode.getNode());
2750         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2751                                     &SVN0->getMask()[0]);
2752       }
2753     }
2754   }
2755
2756   return SDValue();
2757 }
2758
2759 /// This contains all DAGCombine rules which reduce two values combined by
2760 /// an And operation to a single value. This makes them reusable in the context
2761 /// of visitSELECT(). Rules involving constants are not included as
2762 /// visitSELECT() already handles those cases.
2763 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2764                                   SDNode *LocReference) {
2765   EVT VT = N1.getValueType();
2766
2767   // fold (and x, undef) -> 0
2768   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2769     return DAG.getConstant(0, SDLoc(LocReference), VT);
2770   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2771   SDValue LL, LR, RL, RR, CC0, CC1;
2772   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2773     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2774     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2775
2776     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2777         LL.getValueType().isInteger()) {
2778       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2779       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2780         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2781                                      LR.getValueType(), LL, RL);
2782         AddToWorklist(ORNode.getNode());
2783         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2784       }
2785       if (isAllOnesConstant(LR)) {
2786         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2787         if (Op1 == ISD::SETEQ) {
2788           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2789                                         LR.getValueType(), LL, RL);
2790           AddToWorklist(ANDNode.getNode());
2791           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2792         }
2793         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2794         if (Op1 == ISD::SETGT) {
2795           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2796                                        LR.getValueType(), LL, RL);
2797           AddToWorklist(ORNode.getNode());
2798           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2799         }
2800       }
2801     }
2802     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2803     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2804         Op0 == Op1 && LL.getValueType().isInteger() &&
2805       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2806                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2807       SDLoc DL(N0);
2808       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2809                                     LL, DAG.getConstant(1, DL,
2810                                                         LL.getValueType()));
2811       AddToWorklist(ADDNode.getNode());
2812       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2813                           DAG.getConstant(2, DL, LL.getValueType()),
2814                           ISD::SETUGE);
2815     }
2816     // canonicalize equivalent to ll == rl
2817     if (LL == RR && LR == RL) {
2818       Op1 = ISD::getSetCCSwappedOperands(Op1);
2819       std::swap(RL, RR);
2820     }
2821     if (LL == RL && LR == RR) {
2822       bool isInteger = LL.getValueType().isInteger();
2823       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2824       if (Result != ISD::SETCC_INVALID &&
2825           (!LegalOperations ||
2826            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2827             TLI.isOperationLegal(ISD::SETCC,
2828                             getSetCCResultType(N0.getSimpleValueType())))))
2829         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2830                             LL, LR, Result);
2831     }
2832   }
2833
2834   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2835       VT.getSizeInBits() <= 64) {
2836     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2837       APInt ADDC = ADDI->getAPIntValue();
2838       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2839         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2840         // immediate for an add, but it is legal if its top c2 bits are set,
2841         // transform the ADD so the immediate doesn't need to be materialized
2842         // in a register.
2843         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2844           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2845                                              SRLI->getZExtValue());
2846           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2847             ADDC |= Mask;
2848             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2849               SDLoc DL(N0);
2850               SDValue NewAdd =
2851                 DAG.getNode(ISD::ADD, DL, VT,
2852                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2853               CombineTo(N0.getNode(), NewAdd);
2854               // Return N so it doesn't get rechecked!
2855               return SDValue(LocReference, 0);
2856             }
2857           }
2858         }
2859       }
2860     }
2861   }
2862
2863   return SDValue();
2864 }
2865
2866 SDValue DAGCombiner::visitAND(SDNode *N) {
2867   SDValue N0 = N->getOperand(0);
2868   SDValue N1 = N->getOperand(1);
2869   EVT VT = N1.getValueType();
2870
2871   // fold vector ops
2872   if (VT.isVector()) {
2873     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2874       return FoldedVOp;
2875
2876     // fold (and x, 0) -> 0, vector edition
2877     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2878       // do not return N0, because undef node may exist in N0
2879       return DAG.getConstant(
2880           APInt::getNullValue(
2881               N0.getValueType().getScalarType().getSizeInBits()),
2882           SDLoc(N), N0.getValueType());
2883     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2884       // do not return N1, because undef node may exist in N1
2885       return DAG.getConstant(
2886           APInt::getNullValue(
2887               N1.getValueType().getScalarType().getSizeInBits()),
2888           SDLoc(N), N1.getValueType());
2889
2890     // fold (and x, -1) -> x, vector edition
2891     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2892       return N1;
2893     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2894       return N0;
2895   }
2896
2897   // fold (and c1, c2) -> c1&c2
2898   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2899   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2900   if (N0C && N1C && !N1C->isOpaque())
2901     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2902   // canonicalize constant to RHS
2903   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2904      !isConstantIntBuildVectorOrConstantInt(N1))
2905     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2906   // fold (and x, -1) -> x
2907   if (isAllOnesConstant(N1))
2908     return N0;
2909   // if (and x, c) is known to be zero, return 0
2910   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2911   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2912                                    APInt::getAllOnesValue(BitWidth)))
2913     return DAG.getConstant(0, SDLoc(N), VT);
2914   // reassociate and
2915   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2916     return RAND;
2917   // fold (and (or x, C), D) -> D if (C & D) == D
2918   if (N1C && N0.getOpcode() == ISD::OR)
2919     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2920       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2921         return N1;
2922   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2923   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2924     SDValue N0Op0 = N0.getOperand(0);
2925     APInt Mask = ~N1C->getAPIntValue();
2926     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2927     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2928       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2929                                  N0.getValueType(), N0Op0);
2930
2931       // Replace uses of the AND with uses of the Zero extend node.
2932       CombineTo(N, Zext);
2933
2934       // We actually want to replace all uses of the any_extend with the
2935       // zero_extend, to avoid duplicating things.  This will later cause this
2936       // AND to be folded.
2937       CombineTo(N0.getNode(), Zext);
2938       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2939     }
2940   }
2941   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2942   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2943   // already be zero by virtue of the width of the base type of the load.
2944   //
2945   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2946   // more cases.
2947   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2948        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2949       N0.getOpcode() == ISD::LOAD) {
2950     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2951                                          N0 : N0.getOperand(0) );
2952
2953     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2954     // This can be a pure constant or a vector splat, in which case we treat the
2955     // vector as a scalar and use the splat value.
2956     APInt Constant = APInt::getNullValue(1);
2957     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2958       Constant = C->getAPIntValue();
2959     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2960       APInt SplatValue, SplatUndef;
2961       unsigned SplatBitSize;
2962       bool HasAnyUndefs;
2963       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2964                                              SplatBitSize, HasAnyUndefs);
2965       if (IsSplat) {
2966         // Undef bits can contribute to a possible optimisation if set, so
2967         // set them.
2968         SplatValue |= SplatUndef;
2969
2970         // The splat value may be something like "0x00FFFFFF", which means 0 for
2971         // the first vector value and FF for the rest, repeating. We need a mask
2972         // that will apply equally to all members of the vector, so AND all the
2973         // lanes of the constant together.
2974         EVT VT = Vector->getValueType(0);
2975         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2976
2977         // If the splat value has been compressed to a bitlength lower
2978         // than the size of the vector lane, we need to re-expand it to
2979         // the lane size.
2980         if (BitWidth > SplatBitSize)
2981           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2982                SplatBitSize < BitWidth;
2983                SplatBitSize = SplatBitSize * 2)
2984             SplatValue |= SplatValue.shl(SplatBitSize);
2985
2986         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2987         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2988         if (SplatBitSize % BitWidth == 0) {
2989           Constant = APInt::getAllOnesValue(BitWidth);
2990           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2991             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2992         }
2993       }
2994     }
2995
2996     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2997     // actually legal and isn't going to get expanded, else this is a false
2998     // optimisation.
2999     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3000                                                     Load->getValueType(0),
3001                                                     Load->getMemoryVT());
3002
3003     // Resize the constant to the same size as the original memory access before
3004     // extension. If it is still the AllOnesValue then this AND is completely
3005     // unneeded.
3006     Constant =
3007       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3008
3009     bool B;
3010     switch (Load->getExtensionType()) {
3011     default: B = false; break;
3012     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3013     case ISD::ZEXTLOAD:
3014     case ISD::NON_EXTLOAD: B = true; break;
3015     }
3016
3017     if (B && Constant.isAllOnesValue()) {
3018       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3019       // preserve semantics once we get rid of the AND.
3020       SDValue NewLoad(Load, 0);
3021       if (Load->getExtensionType() == ISD::EXTLOAD) {
3022         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3023                               Load->getValueType(0), SDLoc(Load),
3024                               Load->getChain(), Load->getBasePtr(),
3025                               Load->getOffset(), Load->getMemoryVT(),
3026                               Load->getMemOperand());
3027         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3028         if (Load->getNumValues() == 3) {
3029           // PRE/POST_INC loads have 3 values.
3030           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3031                            NewLoad.getValue(2) };
3032           CombineTo(Load, To, 3, true);
3033         } else {
3034           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3035         }
3036       }
3037
3038       // Fold the AND away, taking care not to fold to the old load node if we
3039       // replaced it.
3040       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3041
3042       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3043     }
3044   }
3045
3046   // fold (and (load x), 255) -> (zextload x, i8)
3047   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3048   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3049   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3050               (N0.getOpcode() == ISD::ANY_EXTEND &&
3051                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3052     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3053     LoadSDNode *LN0 = HasAnyExt
3054       ? cast<LoadSDNode>(N0.getOperand(0))
3055       : cast<LoadSDNode>(N0);
3056     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3057         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3058       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3059       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3060         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3061         EVT LoadedVT = LN0->getMemoryVT();
3062         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3063
3064         if (ExtVT == LoadedVT &&
3065             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3066                                                     ExtVT))) {
3067
3068           SDValue NewLoad =
3069             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3070                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3071                            LN0->getMemOperand());
3072           AddToWorklist(N);
3073           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3074           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3075         }
3076
3077         // Do not change the width of a volatile load.
3078         // Do not generate loads of non-round integer types since these can
3079         // be expensive (and would be wrong if the type is not byte sized).
3080         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3081             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3082                                                     ExtVT))) {
3083           EVT PtrType = LN0->getOperand(1).getValueType();
3084
3085           unsigned Alignment = LN0->getAlignment();
3086           SDValue NewPtr = LN0->getBasePtr();
3087
3088           // For big endian targets, we need to add an offset to the pointer
3089           // to load the correct bytes.  For little endian systems, we merely
3090           // need to read fewer bytes from the same pointer.
3091           if (TLI.isBigEndian()) {
3092             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3093             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3094             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3095             SDLoc DL(LN0);
3096             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3097                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3098             Alignment = MinAlign(Alignment, PtrOff);
3099           }
3100
3101           AddToWorklist(NewPtr.getNode());
3102
3103           SDValue Load =
3104             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3105                            LN0->getChain(), NewPtr,
3106                            LN0->getPointerInfo(),
3107                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3108                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3109           AddToWorklist(N);
3110           CombineTo(LN0, Load, Load.getValue(1));
3111           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3112         }
3113       }
3114     }
3115   }
3116
3117   if (SDValue Combined = visitANDLike(N0, N1, N))
3118     return Combined;
3119
3120   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3121   if (N0.getOpcode() == N1.getOpcode()) {
3122     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3123     if (Tmp.getNode()) return Tmp;
3124   }
3125
3126   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3127   // fold (and (sra)) -> (and (srl)) when possible.
3128   if (!VT.isVector() &&
3129       SimplifyDemandedBits(SDValue(N, 0)))
3130     return SDValue(N, 0);
3131
3132   // fold (zext_inreg (extload x)) -> (zextload x)
3133   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3134     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3135     EVT MemVT = LN0->getMemoryVT();
3136     // If we zero all the possible extended bits, then we can turn this into
3137     // a zextload if we are running before legalize or the operation is legal.
3138     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3139     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3140                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3141         ((!LegalOperations && !LN0->isVolatile()) ||
3142          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3143       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3144                                        LN0->getChain(), LN0->getBasePtr(),
3145                                        MemVT, LN0->getMemOperand());
3146       AddToWorklist(N);
3147       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3148       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3149     }
3150   }
3151   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3152   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3153       N0.hasOneUse()) {
3154     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3155     EVT MemVT = LN0->getMemoryVT();
3156     // If we zero all the possible extended bits, then we can turn this into
3157     // a zextload if we are running before legalize or the operation is legal.
3158     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3159     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3160                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3161         ((!LegalOperations && !LN0->isVolatile()) ||
3162          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3163       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3164                                        LN0->getChain(), LN0->getBasePtr(),
3165                                        MemVT, LN0->getMemOperand());
3166       AddToWorklist(N);
3167       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3168       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3169     }
3170   }
3171   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3172   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3173     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3174                                        N0.getOperand(1), false);
3175     if (BSwap.getNode())
3176       return BSwap;
3177   }
3178
3179   return SDValue();
3180 }
3181
3182 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3183 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3184                                         bool DemandHighBits) {
3185   if (!LegalOperations)
3186     return SDValue();
3187
3188   EVT VT = N->getValueType(0);
3189   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3190     return SDValue();
3191   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3192     return SDValue();
3193
3194   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3195   bool LookPassAnd0 = false;
3196   bool LookPassAnd1 = false;
3197   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3198       std::swap(N0, N1);
3199   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3200       std::swap(N0, N1);
3201   if (N0.getOpcode() == ISD::AND) {
3202     if (!N0.getNode()->hasOneUse())
3203       return SDValue();
3204     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205     if (!N01C || N01C->getZExtValue() != 0xFF00)
3206       return SDValue();
3207     N0 = N0.getOperand(0);
3208     LookPassAnd0 = true;
3209   }
3210
3211   if (N1.getOpcode() == ISD::AND) {
3212     if (!N1.getNode()->hasOneUse())
3213       return SDValue();
3214     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3215     if (!N11C || N11C->getZExtValue() != 0xFF)
3216       return SDValue();
3217     N1 = N1.getOperand(0);
3218     LookPassAnd1 = true;
3219   }
3220
3221   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3222     std::swap(N0, N1);
3223   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3224     return SDValue();
3225   if (!N0.getNode()->hasOneUse() ||
3226       !N1.getNode()->hasOneUse())
3227     return SDValue();
3228
3229   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3230   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3231   if (!N01C || !N11C)
3232     return SDValue();
3233   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3234     return SDValue();
3235
3236   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3237   SDValue N00 = N0->getOperand(0);
3238   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3239     if (!N00.getNode()->hasOneUse())
3240       return SDValue();
3241     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3242     if (!N001C || N001C->getZExtValue() != 0xFF)
3243       return SDValue();
3244     N00 = N00.getOperand(0);
3245     LookPassAnd0 = true;
3246   }
3247
3248   SDValue N10 = N1->getOperand(0);
3249   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3250     if (!N10.getNode()->hasOneUse())
3251       return SDValue();
3252     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3253     if (!N101C || N101C->getZExtValue() != 0xFF00)
3254       return SDValue();
3255     N10 = N10.getOperand(0);
3256     LookPassAnd1 = true;
3257   }
3258
3259   if (N00 != N10)
3260     return SDValue();
3261
3262   // Make sure everything beyond the low halfword gets set to zero since the SRL
3263   // 16 will clear the top bits.
3264   unsigned OpSizeInBits = VT.getSizeInBits();
3265   if (DemandHighBits && OpSizeInBits > 16) {
3266     // If the left-shift isn't masked out then the only way this is a bswap is
3267     // if all bits beyond the low 8 are 0. In that case the entire pattern
3268     // reduces to a left shift anyway: leave it for other parts of the combiner.
3269     if (!LookPassAnd0)
3270       return SDValue();
3271
3272     // However, if the right shift isn't masked out then it might be because
3273     // it's not needed. See if we can spot that too.
3274     if (!LookPassAnd1 &&
3275         !DAG.MaskedValueIsZero(
3276             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3277       return SDValue();
3278   }
3279
3280   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3281   if (OpSizeInBits > 16) {
3282     SDLoc DL(N);
3283     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3284                       DAG.getConstant(OpSizeInBits - 16, DL,
3285                                       getShiftAmountTy(VT)));
3286   }
3287   return Res;
3288 }
3289
3290 /// Return true if the specified node is an element that makes up a 32-bit
3291 /// packed halfword byteswap.
3292 /// ((x & 0x000000ff) << 8) |
3293 /// ((x & 0x0000ff00) >> 8) |
3294 /// ((x & 0x00ff0000) << 8) |
3295 /// ((x & 0xff000000) >> 8)
3296 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3297   if (!N.getNode()->hasOneUse())
3298     return false;
3299
3300   unsigned Opc = N.getOpcode();
3301   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3302     return false;
3303
3304   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3305   if (!N1C)
3306     return false;
3307
3308   unsigned Num;
3309   switch (N1C->getZExtValue()) {
3310   default:
3311     return false;
3312   case 0xFF:       Num = 0; break;
3313   case 0xFF00:     Num = 1; break;
3314   case 0xFF0000:   Num = 2; break;
3315   case 0xFF000000: Num = 3; break;
3316   }
3317
3318   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3319   SDValue N0 = N.getOperand(0);
3320   if (Opc == ISD::AND) {
3321     if (Num == 0 || Num == 2) {
3322       // (x >> 8) & 0xff
3323       // (x >> 8) & 0xff0000
3324       if (N0.getOpcode() != ISD::SRL)
3325         return false;
3326       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3327       if (!C || C->getZExtValue() != 8)
3328         return false;
3329     } else {
3330       // (x << 8) & 0xff00
3331       // (x << 8) & 0xff000000
3332       if (N0.getOpcode() != ISD::SHL)
3333         return false;
3334       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3335       if (!C || C->getZExtValue() != 8)
3336         return false;
3337     }
3338   } else if (Opc == ISD::SHL) {
3339     // (x & 0xff) << 8
3340     // (x & 0xff0000) << 8
3341     if (Num != 0 && Num != 2)
3342       return false;
3343     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3344     if (!C || C->getZExtValue() != 8)
3345       return false;
3346   } else { // Opc == ISD::SRL
3347     // (x & 0xff00) >> 8
3348     // (x & 0xff000000) >> 8
3349     if (Num != 1 && Num != 3)
3350       return false;
3351     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3352     if (!C || C->getZExtValue() != 8)
3353       return false;
3354   }
3355
3356   if (Parts[Num])
3357     return false;
3358
3359   Parts[Num] = N0.getOperand(0).getNode();
3360   return true;
3361 }
3362
3363 /// Match a 32-bit packed halfword bswap. That is
3364 /// ((x & 0x000000ff) << 8) |
3365 /// ((x & 0x0000ff00) >> 8) |
3366 /// ((x & 0x00ff0000) << 8) |
3367 /// ((x & 0xff000000) >> 8)
3368 /// => (rotl (bswap x), 16)
3369 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3370   if (!LegalOperations)
3371     return SDValue();
3372
3373   EVT VT = N->getValueType(0);
3374   if (VT != MVT::i32)
3375     return SDValue();
3376   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3377     return SDValue();
3378
3379   // Look for either
3380   // (or (or (and), (and)), (or (and), (and)))
3381   // (or (or (or (and), (and)), (and)), (and))
3382   if (N0.getOpcode() != ISD::OR)
3383     return SDValue();
3384   SDValue N00 = N0.getOperand(0);
3385   SDValue N01 = N0.getOperand(1);
3386   SDNode *Parts[4] = {};
3387
3388   if (N1.getOpcode() == ISD::OR &&
3389       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3390     // (or (or (and), (and)), (or (and), (and)))
3391     SDValue N000 = N00.getOperand(0);
3392     if (!isBSwapHWordElement(N000, Parts))
3393       return SDValue();
3394
3395     SDValue N001 = N00.getOperand(1);
3396     if (!isBSwapHWordElement(N001, Parts))
3397       return SDValue();
3398     SDValue N010 = N01.getOperand(0);
3399     if (!isBSwapHWordElement(N010, Parts))
3400       return SDValue();
3401     SDValue N011 = N01.getOperand(1);
3402     if (!isBSwapHWordElement(N011, Parts))
3403       return SDValue();
3404   } else {
3405     // (or (or (or (and), (and)), (and)), (and))
3406     if (!isBSwapHWordElement(N1, Parts))
3407       return SDValue();
3408     if (!isBSwapHWordElement(N01, Parts))
3409       return SDValue();
3410     if (N00.getOpcode() != ISD::OR)
3411       return SDValue();
3412     SDValue N000 = N00.getOperand(0);
3413     if (!isBSwapHWordElement(N000, Parts))
3414       return SDValue();
3415     SDValue N001 = N00.getOperand(1);
3416     if (!isBSwapHWordElement(N001, Parts))
3417       return SDValue();
3418   }
3419
3420   // Make sure the parts are all coming from the same node.
3421   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3422     return SDValue();
3423
3424   SDLoc DL(N);
3425   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3426                               SDValue(Parts[0], 0));
3427
3428   // Result of the bswap should be rotated by 16. If it's not legal, then
3429   // do  (x << 16) | (x >> 16).
3430   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3431   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3432     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3433   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3434     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3435   return DAG.getNode(ISD::OR, DL, VT,
3436                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3437                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3438 }
3439
3440 /// This contains all DAGCombine rules which reduce two values combined by
3441 /// an Or operation to a single value \see visitANDLike().
3442 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3443   EVT VT = N1.getValueType();
3444   // fold (or x, undef) -> -1
3445   if (!LegalOperations &&
3446       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3447     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3448     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3449                            SDLoc(LocReference), VT);
3450   }
3451   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3452   SDValue LL, LR, RL, RR, CC0, CC1;
3453   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3454     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3455     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3456
3457     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3458       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3459       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3460       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3461         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3462                                      LR.getValueType(), LL, RL);
3463         AddToWorklist(ORNode.getNode());
3464         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3465       }
3466       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3467       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3468       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3469         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3470                                       LR.getValueType(), LL, RL);
3471         AddToWorklist(ANDNode.getNode());
3472         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3473       }
3474     }
3475     // canonicalize equivalent to ll == rl
3476     if (LL == RR && LR == RL) {
3477       Op1 = ISD::getSetCCSwappedOperands(Op1);
3478       std::swap(RL, RR);
3479     }
3480     if (LL == RL && LR == RR) {
3481       bool isInteger = LL.getValueType().isInteger();
3482       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3483       if (Result != ISD::SETCC_INVALID &&
3484           (!LegalOperations ||
3485            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3486             TLI.isOperationLegal(ISD::SETCC,
3487               getSetCCResultType(N0.getValueType())))))
3488         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3489                             LL, LR, Result);
3490     }
3491   }
3492
3493   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3494   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3495       // Don't increase # computations.
3496       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497     // We can only do this xform if we know that bits from X that are set in C2
3498     // but not in C1 are already zero.  Likewise for Y.
3499     if (const ConstantSDNode *N0O1C =
3500         getAsNonOpaqueConstant(N0.getOperand(1))) {
3501       if (const ConstantSDNode *N1O1C =
3502           getAsNonOpaqueConstant(N1.getOperand(1))) {
3503         // We can only do this xform if we know that bits from X that are set in
3504         // C2 but not in C1 are already zero.  Likewise for Y.
3505         const APInt &LHSMask = N0O1C->getAPIntValue();
3506         const APInt &RHSMask = N1O1C->getAPIntValue();
3507
3508         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3509             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3510           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3511                                   N0.getOperand(0), N1.getOperand(0));
3512           SDLoc DL(LocReference);
3513           return DAG.getNode(ISD::AND, DL, VT, X,
3514                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3515         }
3516       }
3517     }
3518   }
3519
3520   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3521   if (N0.getOpcode() == ISD::AND &&
3522       N1.getOpcode() == ISD::AND &&
3523       N0.getOperand(0) == N1.getOperand(0) &&
3524       // Don't increase # computations.
3525       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3526     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3527                             N0.getOperand(1), N1.getOperand(1));
3528     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3529   }
3530
3531   return SDValue();
3532 }
3533
3534 SDValue DAGCombiner::visitOR(SDNode *N) {
3535   SDValue N0 = N->getOperand(0);
3536   SDValue N1 = N->getOperand(1);
3537   EVT VT = N1.getValueType();
3538
3539   // fold vector ops
3540   if (VT.isVector()) {
3541     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3542       return FoldedVOp;
3543
3544     // fold (or x, 0) -> x, vector edition
3545     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3546       return N1;
3547     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3548       return N0;
3549
3550     // fold (or x, -1) -> -1, vector edition
3551     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3552       // do not return N0, because undef node may exist in N0
3553       return DAG.getConstant(
3554           APInt::getAllOnesValue(
3555               N0.getValueType().getScalarType().getSizeInBits()),
3556           SDLoc(N), N0.getValueType());
3557     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3558       // do not return N1, because undef node may exist in N1
3559       return DAG.getConstant(
3560           APInt::getAllOnesValue(
3561               N1.getValueType().getScalarType().getSizeInBits()),
3562           SDLoc(N), N1.getValueType());
3563
3564     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3565     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3566     // Do this only if the resulting shuffle is legal.
3567     if (isa<ShuffleVectorSDNode>(N0) &&
3568         isa<ShuffleVectorSDNode>(N1) &&
3569         // Avoid folding a node with illegal type.
3570         TLI.isTypeLegal(VT) &&
3571         N0->getOperand(1) == N1->getOperand(1) &&
3572         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3573       bool CanFold = true;
3574       unsigned NumElts = VT.getVectorNumElements();
3575       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3576       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3577       // We construct two shuffle masks:
3578       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3579       // and N1 as the second operand.
3580       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3581       // and N0 as the second operand.
3582       // We do this because OR is commutable and therefore there might be
3583       // two ways to fold this node into a shuffle.
3584       SmallVector<int,4> Mask1;
3585       SmallVector<int,4> Mask2;
3586
3587       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3588         int M0 = SV0->getMaskElt(i);
3589         int M1 = SV1->getMaskElt(i);
3590
3591         // Both shuffle indexes are undef. Propagate Undef.
3592         if (M0 < 0 && M1 < 0) {
3593           Mask1.push_back(M0);
3594           Mask2.push_back(M0);
3595           continue;
3596         }
3597
3598         if (M0 < 0 || M1 < 0 ||
3599             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3600             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3601           CanFold = false;
3602           break;
3603         }
3604
3605         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3606         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3607       }
3608
3609       if (CanFold) {
3610         // Fold this sequence only if the resulting shuffle is 'legal'.
3611         if (TLI.isShuffleMaskLegal(Mask1, VT))
3612           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3613                                       N1->getOperand(0), &Mask1[0]);
3614         if (TLI.isShuffleMaskLegal(Mask2, VT))
3615           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3616                                       N0->getOperand(0), &Mask2[0]);
3617       }
3618     }
3619   }
3620
3621   // fold (or c1, c2) -> c1|c2
3622   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3623   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3624   if (N0C && N1C && !N1C->isOpaque())
3625     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3626   // canonicalize constant to RHS
3627   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3628      !isConstantIntBuildVectorOrConstantInt(N1))
3629     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3630   // fold (or x, 0) -> x
3631   if (isNullConstant(N1))
3632     return N0;
3633   // fold (or x, -1) -> -1
3634   if (isAllOnesConstant(N1))
3635     return N1;
3636   // fold (or x, c) -> c iff (x & ~c) == 0
3637   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3638     return N1;
3639
3640   if (SDValue Combined = visitORLike(N0, N1, N))
3641     return Combined;
3642
3643   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3644   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3645   if (BSwap.getNode())
3646     return BSwap;
3647   BSwap = MatchBSwapHWordLow(N, N0, N1);
3648   if (BSwap.getNode())
3649     return BSwap;
3650
3651   // reassociate or
3652   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3653     return ROR;
3654   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3655   // iff (c1 & c2) == 0.
3656   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3657              isa<ConstantSDNode>(N0.getOperand(1))) {
3658     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3659     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3660       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3661                                                    N1C, C1))
3662         return DAG.getNode(
3663             ISD::AND, SDLoc(N), VT,
3664             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3665       return SDValue();
3666     }
3667   }
3668   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3669   if (N0.getOpcode() == N1.getOpcode()) {
3670     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3671     if (Tmp.getNode()) return Tmp;
3672   }
3673
3674   // See if this is some rotate idiom.
3675   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3676     return SDValue(Rot, 0);
3677
3678   // Simplify the operands using demanded-bits information.
3679   if (!VT.isVector() &&
3680       SimplifyDemandedBits(SDValue(N, 0)))
3681     return SDValue(N, 0);
3682
3683   return SDValue();
3684 }
3685
3686 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3687 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3688   if (Op.getOpcode() == ISD::AND) {
3689     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3690       Mask = Op.getOperand(1);
3691       Op = Op.getOperand(0);
3692     } else {
3693       return false;
3694     }
3695   }
3696
3697   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3698     Shift = Op;
3699     return true;
3700   }
3701
3702   return false;
3703 }
3704
3705 // Return true if we can prove that, whenever Neg and Pos are both in the
3706 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3707 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3708 //
3709 //     (or (shift1 X, Neg), (shift2 X, Pos))
3710 //
3711 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3712 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3713 // to consider shift amounts with defined behavior.
3714 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3715   // If OpSize is a power of 2 then:
3716   //
3717   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3718   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3719   //
3720   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3721   // for the stronger condition:
3722   //
3723   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3724   //
3725   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3726   // we can just replace Neg with Neg' for the rest of the function.
3727   //
3728   // In other cases we check for the even stronger condition:
3729   //
3730   //     Neg == OpSize - Pos                                    [B]
3731   //
3732   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3733   // behavior if Pos == 0 (and consequently Neg == OpSize).
3734   //
3735   // We could actually use [A] whenever OpSize is a power of 2, but the
3736   // only extra cases that it would match are those uninteresting ones
3737   // where Neg and Pos are never in range at the same time.  E.g. for
3738   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3739   // as well as (sub 32, Pos), but:
3740   //
3741   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3742   //
3743   // always invokes undefined behavior for 32-bit X.
3744   //
3745   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3746   unsigned MaskLoBits = 0;
3747   if (Neg.getOpcode() == ISD::AND &&
3748       isPowerOf2_64(OpSize) &&
3749       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3750       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3751     Neg = Neg.getOperand(0);
3752     MaskLoBits = Log2_64(OpSize);
3753   }
3754
3755   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3756   if (Neg.getOpcode() != ISD::SUB)
3757     return 0;
3758   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3759   if (!NegC)
3760     return 0;
3761   SDValue NegOp1 = Neg.getOperand(1);
3762
3763   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3764   // Pos'.  The truncation is redundant for the purpose of the equality.
3765   if (MaskLoBits &&
3766       Pos.getOpcode() == ISD::AND &&
3767       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3768       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3769     Pos = Pos.getOperand(0);
3770
3771   // The condition we need is now:
3772   //
3773   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3774   //
3775   // If NegOp1 == Pos then we need:
3776   //
3777   //              OpSize & Mask == NegC & Mask
3778   //
3779   // (because "x & Mask" is a truncation and distributes through subtraction).
3780   APInt Width;
3781   if (Pos == NegOp1)
3782     Width = NegC->getAPIntValue();
3783   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3784   // Then the condition we want to prove becomes:
3785   //
3786   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3787   //
3788   // which, again because "x & Mask" is a truncation, becomes:
3789   //
3790   //                NegC & Mask == (OpSize - PosC) & Mask
3791   //              OpSize & Mask == (NegC + PosC) & Mask
3792   else if (Pos.getOpcode() == ISD::ADD &&
3793            Pos.getOperand(0) == NegOp1 &&
3794            Pos.getOperand(1).getOpcode() == ISD::Constant)
3795     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3796              NegC->getAPIntValue());
3797   else
3798     return false;
3799
3800   // Now we just need to check that OpSize & Mask == Width & Mask.
3801   if (MaskLoBits)
3802     // Opsize & Mask is 0 since Mask is Opsize - 1.
3803     return Width.getLoBits(MaskLoBits) == 0;
3804   return Width == OpSize;
3805 }
3806
3807 // A subroutine of MatchRotate used once we have found an OR of two opposite
3808 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3809 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3810 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3811 // Neg with outer conversions stripped away.
3812 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3813                                        SDValue Neg, SDValue InnerPos,
3814                                        SDValue InnerNeg, unsigned PosOpcode,
3815                                        unsigned NegOpcode, SDLoc DL) {
3816   // fold (or (shl x, (*ext y)),
3817   //          (srl x, (*ext (sub 32, y)))) ->
3818   //   (rotl x, y) or (rotr x, (sub 32, y))
3819   //
3820   // fold (or (shl x, (*ext (sub 32, y))),
3821   //          (srl x, (*ext y))) ->
3822   //   (rotr x, y) or (rotl x, (sub 32, y))
3823   EVT VT = Shifted.getValueType();
3824   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3825     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3826     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3827                        HasPos ? Pos : Neg).getNode();
3828   }
3829
3830   return nullptr;
3831 }
3832
3833 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3834 // idioms for rotate, and if the target supports rotation instructions, generate
3835 // a rot[lr].
3836 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3837   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3838   EVT VT = LHS.getValueType();
3839   if (!TLI.isTypeLegal(VT)) return nullptr;
3840
3841   // The target must have at least one rotate flavor.
3842   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3843   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3844   if (!HasROTL && !HasROTR) return nullptr;
3845
3846   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3847   SDValue LHSShift;   // The shift.
3848   SDValue LHSMask;    // AND value if any.
3849   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3850     return nullptr; // Not part of a rotate.
3851
3852   SDValue RHSShift;   // The shift.
3853   SDValue RHSMask;    // AND value if any.
3854   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3855     return nullptr; // Not part of a rotate.
3856
3857   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3858     return nullptr;   // Not shifting the same value.
3859
3860   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3861     return nullptr;   // Shifts must disagree.
3862
3863   // Canonicalize shl to left side in a shl/srl pair.
3864   if (RHSShift.getOpcode() == ISD::SHL) {
3865     std::swap(LHS, RHS);
3866     std::swap(LHSShift, RHSShift);
3867     std::swap(LHSMask , RHSMask );
3868   }
3869
3870   unsigned OpSizeInBits = VT.getSizeInBits();
3871   SDValue LHSShiftArg = LHSShift.getOperand(0);
3872   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3873   SDValue RHSShiftArg = RHSShift.getOperand(0);
3874   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3875
3876   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3877   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3878   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3879       RHSShiftAmt.getOpcode() == ISD::Constant) {
3880     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3881     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3882     if ((LShVal + RShVal) != OpSizeInBits)
3883       return nullptr;
3884
3885     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3886                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3887
3888     // If there is an AND of either shifted operand, apply it to the result.
3889     if (LHSMask.getNode() || RHSMask.getNode()) {
3890       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3891
3892       if (LHSMask.getNode()) {
3893         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3894         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3895       }
3896       if (RHSMask.getNode()) {
3897         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3898         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3899       }
3900
3901       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3902     }
3903
3904     return Rot.getNode();
3905   }
3906
3907   // If there is a mask here, and we have a variable shift, we can't be sure
3908   // that we're masking out the right stuff.
3909   if (LHSMask.getNode() || RHSMask.getNode())
3910     return nullptr;
3911
3912   // If the shift amount is sign/zext/any-extended just peel it off.
3913   SDValue LExtOp0 = LHSShiftAmt;
3914   SDValue RExtOp0 = RHSShiftAmt;
3915   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3916        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3917        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3918        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3919       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3920        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3921        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3922        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3923     LExtOp0 = LHSShiftAmt.getOperand(0);
3924     RExtOp0 = RHSShiftAmt.getOperand(0);
3925   }
3926
3927   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3928                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3929   if (TryL)
3930     return TryL;
3931
3932   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3933                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3934   if (TryR)
3935     return TryR;
3936
3937   return nullptr;
3938 }
3939
3940 SDValue DAGCombiner::visitXOR(SDNode *N) {
3941   SDValue N0 = N->getOperand(0);
3942   SDValue N1 = N->getOperand(1);
3943   EVT VT = N0.getValueType();
3944
3945   // fold vector ops
3946   if (VT.isVector()) {
3947     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3948       return FoldedVOp;
3949
3950     // fold (xor x, 0) -> x, vector edition
3951     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3952       return N1;
3953     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3954       return N0;
3955   }
3956
3957   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3958   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3959     return DAG.getConstant(0, SDLoc(N), VT);
3960   // fold (xor x, undef) -> undef
3961   if (N0.getOpcode() == ISD::UNDEF)
3962     return N0;
3963   if (N1.getOpcode() == ISD::UNDEF)
3964     return N1;
3965   // fold (xor c1, c2) -> c1^c2
3966   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3967   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3968   if (N0C && N1C)
3969     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3970   // canonicalize constant to RHS
3971   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3972      !isConstantIntBuildVectorOrConstantInt(N1))
3973     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3974   // fold (xor x, 0) -> x
3975   if (isNullConstant(N1))
3976     return N0;
3977   // reassociate xor
3978   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3979     return RXOR;
3980
3981   // fold !(x cc y) -> (x !cc y)
3982   SDValue LHS, RHS, CC;
3983   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3984     bool isInt = LHS.getValueType().isInteger();
3985     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3986                                                isInt);
3987
3988     if (!LegalOperations ||
3989         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3990       switch (N0.getOpcode()) {
3991       default:
3992         llvm_unreachable("Unhandled SetCC Equivalent!");
3993       case ISD::SETCC:
3994         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3995       case ISD::SELECT_CC:
3996         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3997                                N0.getOperand(3), NotCC);
3998       }
3999     }
4000   }
4001
4002   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4003   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4004       N0.getNode()->hasOneUse() &&
4005       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4006     SDValue V = N0.getOperand(0);
4007     SDLoc DL(N0);
4008     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4009                     DAG.getConstant(1, DL, V.getValueType()));
4010     AddToWorklist(V.getNode());
4011     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4012   }
4013
4014   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4015   if (isOneConstant(N1) && VT == MVT::i1 &&
4016       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4017     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4018     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4019       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4020       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4021       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4022       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4023       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4024     }
4025   }
4026   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4027   if (isAllOnesConstant(N1) &&
4028       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4029     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4030     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4031       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4032       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4033       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4034       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4035       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4036     }
4037   }
4038   // fold (xor (and x, y), y) -> (and (not x), y)
4039   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4040       N0->getOperand(1) == N1) {
4041     SDValue X = N0->getOperand(0);
4042     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4043     AddToWorklist(NotX.getNode());
4044     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4045   }
4046   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4047   if (N1C && N0.getOpcode() == ISD::XOR) {
4048     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4049       SDLoc DL(N);
4050       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4051                          DAG.getConstant(N1C->getAPIntValue() ^
4052                                          N00C->getAPIntValue(), DL, VT));
4053     }
4054     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4055       SDLoc DL(N);
4056       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4057                          DAG.getConstant(N1C->getAPIntValue() ^
4058                                          N01C->getAPIntValue(), DL, VT));
4059     }
4060   }
4061   // fold (xor x, x) -> 0
4062   if (N0 == N1)
4063     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4064
4065   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4066   // Here is a concrete example of this equivalence:
4067   // i16   x ==  14
4068   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4069   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4070   //
4071   // =>
4072   //
4073   // i16     ~1      == 0b1111111111111110
4074   // i16 rol(~1, 14) == 0b1011111111111111
4075   //
4076   // Some additional tips to help conceptualize this transform:
4077   // - Try to see the operation as placing a single zero in a value of all ones.
4078   // - There exists no value for x which would allow the result to contain zero.
4079   // - Values of x larger than the bitwidth are undefined and do not require a
4080   //   consistent result.
4081   // - Pushing the zero left requires shifting one bits in from the right.
4082   // A rotate left of ~1 is a nice way of achieving the desired result.
4083   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4084       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4085     SDLoc DL(N);
4086     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4087                        N0.getOperand(1));
4088   }
4089
4090   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4091   if (N0.getOpcode() == N1.getOpcode()) {
4092     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4093     if (Tmp.getNode()) return Tmp;
4094   }
4095
4096   // Simplify the expression using non-local knowledge.
4097   if (!VT.isVector() &&
4098       SimplifyDemandedBits(SDValue(N, 0)))
4099     return SDValue(N, 0);
4100
4101   return SDValue();
4102 }
4103
4104 /// Handle transforms common to the three shifts, when the shift amount is a
4105 /// constant.
4106 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4107   SDNode *LHS = N->getOperand(0).getNode();
4108   if (!LHS->hasOneUse()) return SDValue();
4109
4110   // We want to pull some binops through shifts, so that we have (and (shift))
4111   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4112   // thing happens with address calculations, so it's important to canonicalize
4113   // it.
4114   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4115
4116   switch (LHS->getOpcode()) {
4117   default: return SDValue();
4118   case ISD::OR:
4119   case ISD::XOR:
4120     HighBitSet = false; // We can only transform sra if the high bit is clear.
4121     break;
4122   case ISD::AND:
4123     HighBitSet = true;  // We can only transform sra if the high bit is set.
4124     break;
4125   case ISD::ADD:
4126     if (N->getOpcode() != ISD::SHL)
4127       return SDValue(); // only shl(add) not sr[al](add).
4128     HighBitSet = false; // We can only transform sra if the high bit is clear.
4129     break;
4130   }
4131
4132   // We require the RHS of the binop to be a constant and not opaque as well.
4133   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4134   if (!BinOpCst) return SDValue();
4135
4136   // FIXME: disable this unless the input to the binop is a shift by a constant.
4137   // If it is not a shift, it pessimizes some common cases like:
4138   //
4139   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4140   //    int bar(int *X, int i) { return X[i & 255]; }
4141   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4142   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4143        BinOpLHSVal->getOpcode() != ISD::SRA &&
4144        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4145       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4146     return SDValue();
4147
4148   EVT VT = N->getValueType(0);
4149
4150   // If this is a signed shift right, and the high bit is modified by the
4151   // logical operation, do not perform the transformation. The highBitSet
4152   // boolean indicates the value of the high bit of the constant which would
4153   // cause it to be modified for this operation.
4154   if (N->getOpcode() == ISD::SRA) {
4155     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4156     if (BinOpRHSSignSet != HighBitSet)
4157       return SDValue();
4158   }
4159
4160   if (!TLI.isDesirableToCommuteWithShift(LHS))
4161     return SDValue();
4162
4163   // Fold the constants, shifting the binop RHS by the shift amount.
4164   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4165                                N->getValueType(0),
4166                                LHS->getOperand(1), N->getOperand(1));
4167   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4168
4169   // Create the new shift.
4170   SDValue NewShift = DAG.getNode(N->getOpcode(),
4171                                  SDLoc(LHS->getOperand(0)),
4172                                  VT, LHS->getOperand(0), N->getOperand(1));
4173
4174   // Create the new binop.
4175   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4176 }
4177
4178 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4179   assert(N->getOpcode() == ISD::TRUNCATE);
4180   assert(N->getOperand(0).getOpcode() == ISD::AND);
4181
4182   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4183   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4184     SDValue N01 = N->getOperand(0).getOperand(1);
4185
4186     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4187       if (!N01C->isOpaque()) {
4188         EVT TruncVT = N->getValueType(0);
4189         SDValue N00 = N->getOperand(0).getOperand(0);
4190         APInt TruncC = N01C->getAPIntValue();
4191         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4192         SDLoc DL(N);
4193
4194         return DAG.getNode(ISD::AND, DL, TruncVT,
4195                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4196                            DAG.getConstant(TruncC, DL, TruncVT));
4197       }
4198     }
4199   }
4200
4201   return SDValue();
4202 }
4203
4204 SDValue DAGCombiner::visitRotate(SDNode *N) {
4205   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4206   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4207       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4208     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4209     if (NewOp1.getNode())
4210       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4211                          N->getOperand(0), NewOp1);
4212   }
4213   return SDValue();
4214 }
4215
4216 SDValue DAGCombiner::visitSHL(SDNode *N) {
4217   SDValue N0 = N->getOperand(0);
4218   SDValue N1 = N->getOperand(1);
4219   EVT VT = N0.getValueType();
4220   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4221
4222   // fold vector ops
4223   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4224   if (VT.isVector()) {
4225     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4226       return FoldedVOp;
4227
4228     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4229     // If setcc produces all-one true value then:
4230     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4231     if (N1CV && N1CV->isConstant()) {
4232       if (N0.getOpcode() == ISD::AND) {
4233         SDValue N00 = N0->getOperand(0);
4234         SDValue N01 = N0->getOperand(1);
4235         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4236
4237         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4238             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4239                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4240           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4241                                                      N01CV, N1CV))
4242             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4243         }
4244       } else {
4245         N1C = isConstOrConstSplat(N1);
4246       }
4247     }
4248   }
4249
4250   // fold (shl c1, c2) -> c1<<c2
4251   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4252   if (N0C && N1C && !N1C->isOpaque())
4253     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4254   // fold (shl 0, x) -> 0
4255   if (isNullConstant(N0))
4256     return N0;
4257   // fold (shl x, c >= size(x)) -> undef
4258   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4259     return DAG.getUNDEF(VT);
4260   // fold (shl x, 0) -> x
4261   if (N1C && N1C->isNullValue())
4262     return N0;
4263   // fold (shl undef, x) -> 0
4264   if (N0.getOpcode() == ISD::UNDEF)
4265     return DAG.getConstant(0, SDLoc(N), VT);
4266   // if (shl x, c) is known to be zero, return 0
4267   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4268                             APInt::getAllOnesValue(OpSizeInBits)))
4269     return DAG.getConstant(0, SDLoc(N), VT);
4270   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4271   if (N1.getOpcode() == ISD::TRUNCATE &&
4272       N1.getOperand(0).getOpcode() == ISD::AND) {
4273     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4274     if (NewOp1.getNode())
4275       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4276   }
4277
4278   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4279     return SDValue(N, 0);
4280
4281   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4282   if (N1C && N0.getOpcode() == ISD::SHL) {
4283     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4284       uint64_t c1 = N0C1->getZExtValue();
4285       uint64_t c2 = N1C->getZExtValue();
4286       SDLoc DL(N);
4287       if (c1 + c2 >= OpSizeInBits)
4288         return DAG.getConstant(0, DL, VT);
4289       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4290                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4291     }
4292   }
4293
4294   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4295   // For this to be valid, the second form must not preserve any of the bits
4296   // that are shifted out by the inner shift in the first form.  This means
4297   // the outer shift size must be >= the number of bits added by the ext.
4298   // As a corollary, we don't care what kind of ext it is.
4299   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4300               N0.getOpcode() == ISD::ANY_EXTEND ||
4301               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4302       N0.getOperand(0).getOpcode() == ISD::SHL) {
4303     SDValue N0Op0 = N0.getOperand(0);
4304     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4305       uint64_t c1 = N0Op0C1->getZExtValue();
4306       uint64_t c2 = N1C->getZExtValue();
4307       EVT InnerShiftVT = N0Op0.getValueType();
4308       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4309       if (c2 >= OpSizeInBits - InnerShiftSize) {
4310         SDLoc DL(N0);
4311         if (c1 + c2 >= OpSizeInBits)
4312           return DAG.getConstant(0, DL, VT);
4313         return DAG.getNode(ISD::SHL, DL, VT,
4314                            DAG.getNode(N0.getOpcode(), DL, VT,
4315                                        N0Op0->getOperand(0)),
4316                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4317       }
4318     }
4319   }
4320
4321   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4322   // Only fold this if the inner zext has no other uses to avoid increasing
4323   // the total number of instructions.
4324   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4325       N0.getOperand(0).getOpcode() == ISD::SRL) {
4326     SDValue N0Op0 = N0.getOperand(0);
4327     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4328       uint64_t c1 = N0Op0C1->getZExtValue();
4329       if (c1 < VT.getScalarSizeInBits()) {
4330         uint64_t c2 = N1C->getZExtValue();
4331         if (c1 == c2) {
4332           SDValue NewOp0 = N0.getOperand(0);
4333           EVT CountVT = NewOp0.getOperand(1).getValueType();
4334           SDLoc DL(N);
4335           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4336                                        NewOp0,
4337                                        DAG.getConstant(c2, DL, CountVT));
4338           AddToWorklist(NewSHL.getNode());
4339           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4340         }
4341       }
4342     }
4343   }
4344
4345   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4346   //                               (and (srl x, (sub c1, c2), MASK)
4347   // Only fold this if the inner shift has no other uses -- if it does, folding
4348   // this will increase the total number of instructions.
4349   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4350     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4351       uint64_t c1 = N0C1->getZExtValue();
4352       if (c1 < OpSizeInBits) {
4353         uint64_t c2 = N1C->getZExtValue();
4354         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4355         SDValue Shift;
4356         if (c2 > c1) {
4357           Mask = Mask.shl(c2 - c1);
4358           SDLoc DL(N);
4359           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4360                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4361         } else {
4362           Mask = Mask.lshr(c1 - c2);
4363           SDLoc DL(N);
4364           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4365                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4366         }
4367         SDLoc DL(N0);
4368         return DAG.getNode(ISD::AND, DL, VT, Shift,
4369                            DAG.getConstant(Mask, DL, VT));
4370       }
4371     }
4372   }
4373   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4374   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4375     unsigned BitSize = VT.getScalarSizeInBits();
4376     SDLoc DL(N);
4377     SDValue HiBitsMask =
4378       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4379                                             BitSize - N1C->getZExtValue()),
4380                       DL, VT);
4381     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4382                        HiBitsMask);
4383   }
4384
4385   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4386   // Variant of version done on multiply, except mul by a power of 2 is turned
4387   // into a shift.
4388   APInt Val;
4389   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4390       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4391        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4392     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4393     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4394     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4395   }
4396
4397   if (N1C && !N1C->isOpaque()) {
4398     SDValue NewSHL = visitShiftByConstant(N, N1C);
4399     if (NewSHL.getNode())
4400       return NewSHL;
4401   }
4402
4403   return SDValue();
4404 }
4405
4406 SDValue DAGCombiner::visitSRA(SDNode *N) {
4407   SDValue N0 = N->getOperand(0);
4408   SDValue N1 = N->getOperand(1);
4409   EVT VT = N0.getValueType();
4410   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4411
4412   // fold vector ops
4413   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4414   if (VT.isVector()) {
4415     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4416       return FoldedVOp;
4417
4418     N1C = isConstOrConstSplat(N1);
4419   }
4420
4421   // fold (sra c1, c2) -> (sra c1, c2)
4422   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4423   if (N0C && N1C && !N1C->isOpaque())
4424     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4425   // fold (sra 0, x) -> 0
4426   if (isNullConstant(N0))
4427     return N0;
4428   // fold (sra -1, x) -> -1
4429   if (isAllOnesConstant(N0))
4430     return N0;
4431   // fold (sra x, (setge c, size(x))) -> undef
4432   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4433     return DAG.getUNDEF(VT);
4434   // fold (sra x, 0) -> x
4435   if (N1C && N1C->isNullValue())
4436     return N0;
4437   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4438   // sext_inreg.
4439   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4440     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4441     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4442     if (VT.isVector())
4443       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4444                                ExtVT, VT.getVectorNumElements());
4445     if ((!LegalOperations ||
4446          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4447       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4448                          N0.getOperand(0), DAG.getValueType(ExtVT));
4449   }
4450
4451   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4452   if (N1C && N0.getOpcode() == ISD::SRA) {
4453     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4454       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4455       if (Sum >= OpSizeInBits)
4456         Sum = OpSizeInBits - 1;
4457       SDLoc DL(N);
4458       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4459                          DAG.getConstant(Sum, DL, N1.getValueType()));
4460     }
4461   }
4462
4463   // fold (sra (shl X, m), (sub result_size, n))
4464   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4465   // result_size - n != m.
4466   // If truncate is free for the target sext(shl) is likely to result in better
4467   // code.
4468   if (N0.getOpcode() == ISD::SHL && N1C) {
4469     // Get the two constanst of the shifts, CN0 = m, CN = n.
4470     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4471     if (N01C) {
4472       LLVMContext &Ctx = *DAG.getContext();
4473       // Determine what the truncate's result bitsize and type would be.
4474       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4475
4476       if (VT.isVector())
4477         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4478
4479       // Determine the residual right-shift amount.
4480       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4481
4482       // If the shift is not a no-op (in which case this should be just a sign
4483       // extend already), the truncated to type is legal, sign_extend is legal
4484       // on that type, and the truncate to that type is both legal and free,
4485       // perform the transform.
4486       if ((ShiftAmt > 0) &&
4487           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4488           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4489           TLI.isTruncateFree(VT, TruncVT)) {
4490
4491         SDLoc DL(N);
4492         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4493             getShiftAmountTy(N0.getOperand(0).getValueType()));
4494         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4495                                     N0.getOperand(0), Amt);
4496         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4497                                     Shift);
4498         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4499                            N->getValueType(0), Trunc);
4500       }
4501     }
4502   }
4503
4504   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4505   if (N1.getOpcode() == ISD::TRUNCATE &&
4506       N1.getOperand(0).getOpcode() == ISD::AND) {
4507     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4508     if (NewOp1.getNode())
4509       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4510   }
4511
4512   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4513   //      if c1 is equal to the number of bits the trunc removes
4514   if (N0.getOpcode() == ISD::TRUNCATE &&
4515       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4516        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4517       N0.getOperand(0).hasOneUse() &&
4518       N0.getOperand(0).getOperand(1).hasOneUse() &&
4519       N1C) {
4520     SDValue N0Op0 = N0.getOperand(0);
4521     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4522       unsigned LargeShiftVal = LargeShift->getZExtValue();
4523       EVT LargeVT = N0Op0.getValueType();
4524
4525       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4526         SDLoc DL(N);
4527         SDValue Amt =
4528           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4529                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4530         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4531                                   N0Op0.getOperand(0), Amt);
4532         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4533       }
4534     }
4535   }
4536
4537   // Simplify, based on bits shifted out of the LHS.
4538   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4539     return SDValue(N, 0);
4540
4541
4542   // If the sign bit is known to be zero, switch this to a SRL.
4543   if (DAG.SignBitIsZero(N0))
4544     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4545
4546   if (N1C && !N1C->isOpaque()) {
4547     SDValue NewSRA = visitShiftByConstant(N, N1C);
4548     if (NewSRA.getNode())
4549       return NewSRA;
4550   }
4551
4552   return SDValue();
4553 }
4554
4555 SDValue DAGCombiner::visitSRL(SDNode *N) {
4556   SDValue N0 = N->getOperand(0);
4557   SDValue N1 = N->getOperand(1);
4558   EVT VT = N0.getValueType();
4559   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4560
4561   // fold vector ops
4562   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4563   if (VT.isVector()) {
4564     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4565       return FoldedVOp;
4566
4567     N1C = isConstOrConstSplat(N1);
4568   }
4569
4570   // fold (srl c1, c2) -> c1 >>u c2
4571   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4572   if (N0C && N1C && !N1C->isOpaque())
4573     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4574   // fold (srl 0, x) -> 0
4575   if (isNullConstant(N0))
4576     return N0;
4577   // fold (srl x, c >= size(x)) -> undef
4578   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4579     return DAG.getUNDEF(VT);
4580   // fold (srl x, 0) -> x
4581   if (N1C && N1C->isNullValue())
4582     return N0;
4583   // if (srl x, c) is known to be zero, return 0
4584   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4585                                    APInt::getAllOnesValue(OpSizeInBits)))
4586     return DAG.getConstant(0, SDLoc(N), VT);
4587
4588   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4589   if (N1C && N0.getOpcode() == ISD::SRL) {
4590     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4591       uint64_t c1 = N01C->getZExtValue();
4592       uint64_t c2 = N1C->getZExtValue();
4593       SDLoc DL(N);
4594       if (c1 + c2 >= OpSizeInBits)
4595         return DAG.getConstant(0, DL, VT);
4596       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4597                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4598     }
4599   }
4600
4601   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4602   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4603       N0.getOperand(0).getOpcode() == ISD::SRL &&
4604       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4605     uint64_t c1 =
4606       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4607     uint64_t c2 = N1C->getZExtValue();
4608     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4609     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4610     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4611     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4612     if (c1 + OpSizeInBits == InnerShiftSize) {
4613       SDLoc DL(N0);
4614       if (c1 + c2 >= InnerShiftSize)
4615         return DAG.getConstant(0, DL, VT);
4616       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4617                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4618                                      N0.getOperand(0)->getOperand(0),
4619                                      DAG.getConstant(c1 + c2, DL,
4620                                                      ShiftCountVT)));
4621     }
4622   }
4623
4624   // fold (srl (shl x, c), c) -> (and x, cst2)
4625   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4626     unsigned BitSize = N0.getScalarValueSizeInBits();
4627     if (BitSize <= 64) {
4628       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4629       SDLoc DL(N);
4630       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4631                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4632     }
4633   }
4634
4635   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4636   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4637     // Shifting in all undef bits?
4638     EVT SmallVT = N0.getOperand(0).getValueType();
4639     unsigned BitSize = SmallVT.getScalarSizeInBits();
4640     if (N1C->getZExtValue() >= BitSize)
4641       return DAG.getUNDEF(VT);
4642
4643     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4644       uint64_t ShiftAmt = N1C->getZExtValue();
4645       SDLoc DL0(N0);
4646       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4647                                        N0.getOperand(0),
4648                           DAG.getConstant(ShiftAmt, DL0,
4649                                           getShiftAmountTy(SmallVT)));
4650       AddToWorklist(SmallShift.getNode());
4651       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4652       SDLoc DL(N);
4653       return DAG.getNode(ISD::AND, DL, VT,
4654                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4655                          DAG.getConstant(Mask, DL, VT));
4656     }
4657   }
4658
4659   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4660   // bit, which is unmodified by sra.
4661   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4662     if (N0.getOpcode() == ISD::SRA)
4663       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4664   }
4665
4666   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4667   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4668       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4669     APInt KnownZero, KnownOne;
4670     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4671
4672     // If any of the input bits are KnownOne, then the input couldn't be all
4673     // zeros, thus the result of the srl will always be zero.
4674     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4675
4676     // If all of the bits input the to ctlz node are known to be zero, then
4677     // the result of the ctlz is "32" and the result of the shift is one.
4678     APInt UnknownBits = ~KnownZero;
4679     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4680
4681     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4682     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4683       // Okay, we know that only that the single bit specified by UnknownBits
4684       // could be set on input to the CTLZ node. If this bit is set, the SRL
4685       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4686       // to an SRL/XOR pair, which is likely to simplify more.
4687       unsigned ShAmt = UnknownBits.countTrailingZeros();
4688       SDValue Op = N0.getOperand(0);
4689
4690       if (ShAmt) {
4691         SDLoc DL(N0);
4692         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4693                   DAG.getConstant(ShAmt, DL,
4694                                   getShiftAmountTy(Op.getValueType())));
4695         AddToWorklist(Op.getNode());
4696       }
4697
4698       SDLoc DL(N);
4699       return DAG.getNode(ISD::XOR, DL, VT,
4700                          Op, DAG.getConstant(1, DL, VT));
4701     }
4702   }
4703
4704   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4705   if (N1.getOpcode() == ISD::TRUNCATE &&
4706       N1.getOperand(0).getOpcode() == ISD::AND) {
4707     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4708     if (NewOp1.getNode())
4709       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4710   }
4711
4712   // fold operands of srl based on knowledge that the low bits are not
4713   // demanded.
4714   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4715     return SDValue(N, 0);
4716
4717   if (N1C && !N1C->isOpaque()) {
4718     SDValue NewSRL = visitShiftByConstant(N, N1C);
4719     if (NewSRL.getNode())
4720       return NewSRL;
4721   }
4722
4723   // Attempt to convert a srl of a load into a narrower zero-extending load.
4724   SDValue NarrowLoad = ReduceLoadWidth(N);
4725   if (NarrowLoad.getNode())
4726     return NarrowLoad;
4727
4728   // Here is a common situation. We want to optimize:
4729   //
4730   //   %a = ...
4731   //   %b = and i32 %a, 2
4732   //   %c = srl i32 %b, 1
4733   //   brcond i32 %c ...
4734   //
4735   // into
4736   //
4737   //   %a = ...
4738   //   %b = and %a, 2
4739   //   %c = setcc eq %b, 0
4740   //   brcond %c ...
4741   //
4742   // However when after the source operand of SRL is optimized into AND, the SRL
4743   // itself may not be optimized further. Look for it and add the BRCOND into
4744   // the worklist.
4745   if (N->hasOneUse()) {
4746     SDNode *Use = *N->use_begin();
4747     if (Use->getOpcode() == ISD::BRCOND)
4748       AddToWorklist(Use);
4749     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4750       // Also look pass the truncate.
4751       Use = *Use->use_begin();
4752       if (Use->getOpcode() == ISD::BRCOND)
4753         AddToWorklist(Use);
4754     }
4755   }
4756
4757   return SDValue();
4758 }
4759
4760 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4761   SDValue N0 = N->getOperand(0);
4762   EVT VT = N->getValueType(0);
4763
4764   // fold (ctlz c1) -> c2
4765   if (isa<ConstantSDNode>(N0))
4766     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4767   return SDValue();
4768 }
4769
4770 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4771   SDValue N0 = N->getOperand(0);
4772   EVT VT = N->getValueType(0);
4773
4774   // fold (ctlz_zero_undef c1) -> c2
4775   if (isa<ConstantSDNode>(N0))
4776     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4777   return SDValue();
4778 }
4779
4780 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4781   SDValue N0 = N->getOperand(0);
4782   EVT VT = N->getValueType(0);
4783
4784   // fold (cttz c1) -> c2
4785   if (isa<ConstantSDNode>(N0))
4786     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4787   return SDValue();
4788 }
4789
4790 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4791   SDValue N0 = N->getOperand(0);
4792   EVT VT = N->getValueType(0);
4793
4794   // fold (cttz_zero_undef c1) -> c2
4795   if (isa<ConstantSDNode>(N0))
4796     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4797   return SDValue();
4798 }
4799
4800 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4801   SDValue N0 = N->getOperand(0);
4802   EVT VT = N->getValueType(0);
4803
4804   // fold (ctpop c1) -> c2
4805   if (isa<ConstantSDNode>(N0))
4806     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4807   return SDValue();
4808 }
4809
4810
4811 /// \brief Generate Min/Max node
4812 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4813                                    SDValue True, SDValue False,
4814                                    ISD::CondCode CC, const TargetLowering &TLI,
4815                                    SelectionDAG &DAG) {
4816   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4817     return SDValue();
4818
4819   switch (CC) {
4820   case ISD::SETOLT:
4821   case ISD::SETOLE:
4822   case ISD::SETLT:
4823   case ISD::SETLE:
4824   case ISD::SETULT:
4825   case ISD::SETULE: {
4826     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4827     if (TLI.isOperationLegal(Opcode, VT))
4828       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4829     return SDValue();
4830   }
4831   case ISD::SETOGT:
4832   case ISD::SETOGE:
4833   case ISD::SETGT:
4834   case ISD::SETGE:
4835   case ISD::SETUGT:
4836   case ISD::SETUGE: {
4837     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4838     if (TLI.isOperationLegal(Opcode, VT))
4839       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4840     return SDValue();
4841   }
4842   default:
4843     return SDValue();
4844   }
4845 }
4846
4847 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4848   SDValue N0 = N->getOperand(0);
4849   SDValue N1 = N->getOperand(1);
4850   SDValue N2 = N->getOperand(2);
4851   EVT VT = N->getValueType(0);
4852   EVT VT0 = N0.getValueType();
4853
4854   // fold (select C, X, X) -> X
4855   if (N1 == N2)
4856     return N1;
4857   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4858     // fold (select true, X, Y) -> X
4859     // fold (select false, X, Y) -> Y
4860     return !N0C->isNullValue() ? N1 : N2;
4861   }
4862   // fold (select C, 1, X) -> (or C, X)
4863   if (VT == MVT::i1 && isOneConstant(N1))
4864     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4865   // fold (select C, 0, 1) -> (xor C, 1)
4866   // We can't do this reliably if integer based booleans have different contents
4867   // to floating point based booleans. This is because we can't tell whether we
4868   // have an integer-based boolean or a floating-point-based boolean unless we
4869   // can find the SETCC that produced it and inspect its operands. This is
4870   // fairly easy if C is the SETCC node, but it can potentially be
4871   // undiscoverable (or not reasonably discoverable). For example, it could be
4872   // in another basic block or it could require searching a complicated
4873   // expression.
4874   if (VT.isInteger() &&
4875       (VT0 == MVT::i1 || (VT0.isInteger() &&
4876                           TLI.getBooleanContents(false, false) ==
4877                               TLI.getBooleanContents(false, true) &&
4878                           TLI.getBooleanContents(false, false) ==
4879                               TargetLowering::ZeroOrOneBooleanContent)) &&
4880       isNullConstant(N1) && isOneConstant(N2)) {
4881     SDValue XORNode;
4882     if (VT == VT0) {
4883       SDLoc DL(N);
4884       return DAG.getNode(ISD::XOR, DL, VT0,
4885                          N0, DAG.getConstant(1, DL, VT0));
4886     }
4887     SDLoc DL0(N0);
4888     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4889                           N0, DAG.getConstant(1, DL0, VT0));
4890     AddToWorklist(XORNode.getNode());
4891     if (VT.bitsGT(VT0))
4892       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4893     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4894   }
4895   // fold (select C, 0, X) -> (and (not C), X)
4896   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4897     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4898     AddToWorklist(NOTNode.getNode());
4899     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4900   }
4901   // fold (select C, X, 1) -> (or (not C), X)
4902   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4903     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4904     AddToWorklist(NOTNode.getNode());
4905     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4906   }
4907   // fold (select C, X, 0) -> (and C, X)
4908   if (VT == MVT::i1 && isNullConstant(N2))
4909     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4910   // fold (select X, X, Y) -> (or X, Y)
4911   // fold (select X, 1, Y) -> (or X, Y)
4912   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4913     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4914   // fold (select X, Y, X) -> (and X, Y)
4915   // fold (select X, Y, 0) -> (and X, Y)
4916   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4917     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4918
4919   // If we can fold this based on the true/false value, do so.
4920   if (SimplifySelectOps(N, N1, N2))
4921     return SDValue(N, 0);  // Don't revisit N.
4922
4923   // fold selects based on a setcc into other things, such as min/max/abs
4924   if (N0.getOpcode() == ISD::SETCC) {
4925     // select x, y (fcmp lt x, y) -> fminnum x, y
4926     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4927     //
4928     // This is OK if we don't care about what happens if either operand is a
4929     // NaN.
4930     //
4931
4932     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4933     // no signed zeros as well as no nans.
4934     const TargetOptions &Options = DAG.getTarget().Options;
4935     if (Options.UnsafeFPMath &&
4936         VT.isFloatingPoint() && N0.hasOneUse() &&
4937         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4938       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4939
4940       SDValue FMinMax =
4941           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4942                               N1, N2, CC, TLI, DAG);
4943       if (FMinMax)
4944         return FMinMax;
4945     }
4946
4947     if ((!LegalOperations &&
4948          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4949         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4950       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4951                          N0.getOperand(0), N0.getOperand(1),
4952                          N1, N2, N0.getOperand(2));
4953     return SimplifySelect(SDLoc(N), N0, N1, N2);
4954   }
4955
4956   if (VT0 == MVT::i1) {
4957     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4958       // select (and Cond0, Cond1), X, Y
4959       //   -> select Cond0, (select Cond1, X, Y), Y
4960       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4961         SDValue Cond0 = N0->getOperand(0);
4962         SDValue Cond1 = N0->getOperand(1);
4963         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4964                                           N1.getValueType(), Cond1, N1, N2);
4965         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4966                            InnerSelect, N2);
4967       }
4968       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4969       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4970         SDValue Cond0 = N0->getOperand(0);
4971         SDValue Cond1 = N0->getOperand(1);
4972         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4973                                           N1.getValueType(), Cond1, N1, N2);
4974         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4975                            InnerSelect);
4976       }
4977     }
4978
4979     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4980     if (N1->getOpcode() == ISD::SELECT) {
4981       SDValue N1_0 = N1->getOperand(0);
4982       SDValue N1_1 = N1->getOperand(1);
4983       SDValue N1_2 = N1->getOperand(2);
4984       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4985         // Create the actual and node if we can generate good code for it.
4986         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4987           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4988                                     N0, N1_0);
4989           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4990                              N1_1, N2);
4991         }
4992         // Otherwise see if we can optimize the "and" to a better pattern.
4993         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4994           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4995                              N1_1, N2);
4996       }
4997     }
4998     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4999     if (N2->getOpcode() == ISD::SELECT) {
5000       SDValue N2_0 = N2->getOperand(0);
5001       SDValue N2_1 = N2->getOperand(1);
5002       SDValue N2_2 = N2->getOperand(2);
5003       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5004         // Create the actual or node if we can generate good code for it.
5005         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5006           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5007                                    N0, N2_0);
5008           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5009                              N1, N2_2);
5010         }
5011         // Otherwise see if we can optimize to a better pattern.
5012         if (SDValue Combined = visitORLike(N0, N2_0, N))
5013           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5014                              N1, N2_2);
5015       }
5016     }
5017   }
5018
5019   return SDValue();
5020 }
5021
5022 static
5023 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5024   SDLoc DL(N);
5025   EVT LoVT, HiVT;
5026   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5027
5028   // Split the inputs.
5029   SDValue Lo, Hi, LL, LH, RL, RH;
5030   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5031   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5032
5033   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5034   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5035
5036   return std::make_pair(Lo, Hi);
5037 }
5038
5039 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5040 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5041 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5042   SDLoc dl(N);
5043   SDValue Cond = N->getOperand(0);
5044   SDValue LHS = N->getOperand(1);
5045   SDValue RHS = N->getOperand(2);
5046   EVT VT = N->getValueType(0);
5047   int NumElems = VT.getVectorNumElements();
5048   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5049          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5050          Cond.getOpcode() == ISD::BUILD_VECTOR);
5051
5052   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5053   // binary ones here.
5054   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5055     return SDValue();
5056
5057   // We're sure we have an even number of elements due to the
5058   // concat_vectors we have as arguments to vselect.
5059   // Skip BV elements until we find one that's not an UNDEF
5060   // After we find an UNDEF element, keep looping until we get to half the
5061   // length of the BV and see if all the non-undef nodes are the same.
5062   ConstantSDNode *BottomHalf = nullptr;
5063   for (int i = 0; i < NumElems / 2; ++i) {
5064     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5065       continue;
5066
5067     if (BottomHalf == nullptr)
5068       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5069     else if (Cond->getOperand(i).getNode() != BottomHalf)
5070       return SDValue();
5071   }
5072
5073   // Do the same for the second half of the BuildVector
5074   ConstantSDNode *TopHalf = nullptr;
5075   for (int i = NumElems / 2; i < NumElems; ++i) {
5076     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5077       continue;
5078
5079     if (TopHalf == nullptr)
5080       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5081     else if (Cond->getOperand(i).getNode() != TopHalf)
5082       return SDValue();
5083   }
5084
5085   assert(TopHalf && BottomHalf &&
5086          "One half of the selector was all UNDEFs and the other was all the "
5087          "same value. This should have been addressed before this function.");
5088   return DAG.getNode(
5089       ISD::CONCAT_VECTORS, dl, VT,
5090       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5091       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5092 }
5093
5094 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5095
5096   if (Level >= AfterLegalizeTypes)
5097     return SDValue();
5098
5099   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5100   SDValue Mask = MSC->getMask();
5101   SDValue Data  = MSC->getValue();
5102   SDLoc DL(N);
5103
5104   // If the MSCATTER data type requires splitting and the mask is provided by a
5105   // SETCC, then split both nodes and its operands before legalization. This
5106   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5107   // and enables future optimizations (e.g. min/max pattern matching on X86).
5108   if (Mask.getOpcode() != ISD::SETCC)
5109     return SDValue();
5110
5111   // Check if any splitting is required.
5112   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5113       TargetLowering::TypeSplitVector)
5114     return SDValue();
5115   SDValue MaskLo, MaskHi, Lo, Hi;
5116   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5117
5118   EVT LoVT, HiVT;
5119   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5120
5121   SDValue Chain = MSC->getChain();
5122
5123   EVT MemoryVT = MSC->getMemoryVT();
5124   unsigned Alignment = MSC->getOriginalAlignment();
5125
5126   EVT LoMemVT, HiMemVT;
5127   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5128
5129   SDValue DataLo, DataHi;
5130   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5131
5132   SDValue BasePtr = MSC->getBasePtr();
5133   SDValue IndexLo, IndexHi;
5134   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5135
5136   MachineMemOperand *MMO = DAG.getMachineFunction().
5137     getMachineMemOperand(MSC->getPointerInfo(), 
5138                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5139                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5140
5141   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5142   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5143                             DL, OpsLo, MMO);
5144
5145   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5146   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5147                             DL, OpsHi, MMO);
5148
5149   AddToWorklist(Lo.getNode());
5150   AddToWorklist(Hi.getNode());
5151
5152   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5153 }
5154
5155 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5156
5157   if (Level >= AfterLegalizeTypes)
5158     return SDValue();
5159
5160   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5161   SDValue Mask = MST->getMask();
5162   SDValue Data  = MST->getValue();
5163   SDLoc DL(N);
5164
5165   // If the MSTORE data type requires splitting and the mask is provided by a
5166   // SETCC, then split both nodes and its operands before legalization. This
5167   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5168   // and enables future optimizations (e.g. min/max pattern matching on X86).
5169   if (Mask.getOpcode() == ISD::SETCC) {
5170
5171     // Check if any splitting is required.
5172     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5173         TargetLowering::TypeSplitVector)
5174       return SDValue();
5175
5176     SDValue MaskLo, MaskHi, Lo, Hi;
5177     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5178
5179     EVT LoVT, HiVT;
5180     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5181
5182     SDValue Chain = MST->getChain();
5183     SDValue Ptr   = MST->getBasePtr();
5184
5185     EVT MemoryVT = MST->getMemoryVT();
5186     unsigned Alignment = MST->getOriginalAlignment();
5187
5188     // if Alignment is equal to the vector size,
5189     // take the half of it for the second part
5190     unsigned SecondHalfAlignment =
5191       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5192          Alignment/2 : Alignment;
5193
5194     EVT LoMemVT, HiMemVT;
5195     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5196
5197     SDValue DataLo, DataHi;
5198     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5199
5200     MachineMemOperand *MMO = DAG.getMachineFunction().
5201       getMachineMemOperand(MST->getPointerInfo(),
5202                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5203                            Alignment, MST->getAAInfo(), MST->getRanges());
5204
5205     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5206                             MST->isTruncatingStore());
5207
5208     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5209     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5210                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5211
5212     MMO = DAG.getMachineFunction().
5213       getMachineMemOperand(MST->getPointerInfo(),
5214                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5215                            SecondHalfAlignment, MST->getAAInfo(),
5216                            MST->getRanges());
5217
5218     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5219                             MST->isTruncatingStore());
5220
5221     AddToWorklist(Lo.getNode());
5222     AddToWorklist(Hi.getNode());
5223
5224     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5225   }
5226   return SDValue();
5227 }
5228
5229 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5230
5231   if (Level >= AfterLegalizeTypes)
5232     return SDValue();
5233
5234   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5235   SDValue Mask = MGT->getMask();
5236   SDLoc DL(N);
5237
5238   // If the MGATHER result requires splitting and the mask is provided by a
5239   // SETCC, then split both nodes and its operands before legalization. This
5240   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5241   // and enables future optimizations (e.g. min/max pattern matching on X86).
5242
5243   if (Mask.getOpcode() != ISD::SETCC)
5244     return SDValue();
5245
5246   EVT VT = N->getValueType(0);
5247
5248   // Check if any splitting is required.
5249   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5250       TargetLowering::TypeSplitVector)
5251     return SDValue();
5252
5253   SDValue MaskLo, MaskHi, Lo, Hi;
5254   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5255
5256   SDValue Src0 = MGT->getValue();
5257   SDValue Src0Lo, Src0Hi;
5258   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5259
5260   EVT LoVT, HiVT;
5261   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5262
5263   SDValue Chain = MGT->getChain();
5264   EVT MemoryVT = MGT->getMemoryVT();
5265   unsigned Alignment = MGT->getOriginalAlignment();
5266
5267   EVT LoMemVT, HiMemVT;
5268   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5269
5270   SDValue BasePtr = MGT->getBasePtr();
5271   SDValue Index = MGT->getIndex();
5272   SDValue IndexLo, IndexHi;
5273   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5274
5275   MachineMemOperand *MMO = DAG.getMachineFunction().
5276     getMachineMemOperand(MGT->getPointerInfo(), 
5277                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5278                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5279
5280   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5281   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5282                             MMO);
5283
5284   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5285   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5286                             MMO);
5287
5288   AddToWorklist(Lo.getNode());
5289   AddToWorklist(Hi.getNode());
5290
5291   // Build a factor node to remember that this load is independent of the
5292   // other one.
5293   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5294                       Hi.getValue(1));
5295
5296   // Legalized the chain result - switch anything that used the old chain to
5297   // use the new one.
5298   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5299
5300   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5301
5302   SDValue RetOps[] = { GatherRes, Chain };
5303   return DAG.getMergeValues(RetOps, DL);
5304 }
5305
5306 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5307
5308   if (Level >= AfterLegalizeTypes)
5309     return SDValue();
5310
5311   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5312   SDValue Mask = MLD->getMask();
5313   SDLoc DL(N);
5314
5315   // If the MLOAD result requires splitting and the mask is provided by a
5316   // SETCC, then split both nodes and its operands before legalization. This
5317   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5318   // and enables future optimizations (e.g. min/max pattern matching on X86).
5319
5320   if (Mask.getOpcode() == ISD::SETCC) {
5321     EVT VT = N->getValueType(0);
5322
5323     // Check if any splitting is required.
5324     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5325         TargetLowering::TypeSplitVector)
5326       return SDValue();
5327
5328     SDValue MaskLo, MaskHi, Lo, Hi;
5329     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5330
5331     SDValue Src0 = MLD->getSrc0();
5332     SDValue Src0Lo, Src0Hi;
5333     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5334
5335     EVT LoVT, HiVT;
5336     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5337
5338     SDValue Chain = MLD->getChain();
5339     SDValue Ptr   = MLD->getBasePtr();
5340     EVT MemoryVT = MLD->getMemoryVT();
5341     unsigned Alignment = MLD->getOriginalAlignment();
5342
5343     // if Alignment is equal to the vector size,
5344     // take the half of it for the second part
5345     unsigned SecondHalfAlignment =
5346       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5347          Alignment/2 : Alignment;
5348
5349     EVT LoMemVT, HiMemVT;
5350     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5351
5352     MachineMemOperand *MMO = DAG.getMachineFunction().
5353     getMachineMemOperand(MLD->getPointerInfo(),
5354                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5355                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5356
5357     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5358                            ISD::NON_EXTLOAD);
5359
5360     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5361     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5362                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5363
5364     MMO = DAG.getMachineFunction().
5365     getMachineMemOperand(MLD->getPointerInfo(),
5366                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5367                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5368
5369     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5370                            ISD::NON_EXTLOAD);
5371
5372     AddToWorklist(Lo.getNode());
5373     AddToWorklist(Hi.getNode());
5374
5375     // Build a factor node to remember that this load is independent of the
5376     // other one.
5377     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5378                         Hi.getValue(1));
5379
5380     // Legalized the chain result - switch anything that used the old chain to
5381     // use the new one.
5382     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5383
5384     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5385
5386     SDValue RetOps[] = { LoadRes, Chain };
5387     return DAG.getMergeValues(RetOps, DL);
5388   }
5389   return SDValue();
5390 }
5391
5392 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5393   SDValue N0 = N->getOperand(0);
5394   SDValue N1 = N->getOperand(1);
5395   SDValue N2 = N->getOperand(2);
5396   SDLoc DL(N);
5397
5398   // Canonicalize integer abs.
5399   // vselect (setg[te] X,  0),  X, -X ->
5400   // vselect (setgt    X, -1),  X, -X ->
5401   // vselect (setl[te] X,  0), -X,  X ->
5402   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5403   if (N0.getOpcode() == ISD::SETCC) {
5404     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5405     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5406     bool isAbs = false;
5407     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5408
5409     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5410          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5411         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5412       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5413     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5414              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5415       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5416
5417     if (isAbs) {
5418       EVT VT = LHS.getValueType();
5419       SDValue Shift = DAG.getNode(
5420           ISD::SRA, DL, VT, LHS,
5421           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5422       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5423       AddToWorklist(Shift.getNode());
5424       AddToWorklist(Add.getNode());
5425       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5426     }
5427   }
5428
5429   if (SimplifySelectOps(N, N1, N2))
5430     return SDValue(N, 0);  // Don't revisit N.
5431
5432   // If the VSELECT result requires splitting and the mask is provided by a
5433   // SETCC, then split both nodes and its operands before legalization. This
5434   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5435   // and enables future optimizations (e.g. min/max pattern matching on X86).
5436   if (N0.getOpcode() == ISD::SETCC) {
5437     EVT VT = N->getValueType(0);
5438
5439     // Check if any splitting is required.
5440     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5441         TargetLowering::TypeSplitVector)
5442       return SDValue();
5443
5444     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5445     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5446     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5447     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5448
5449     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5450     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5451
5452     // Add the new VSELECT nodes to the work list in case they need to be split
5453     // again.
5454     AddToWorklist(Lo.getNode());
5455     AddToWorklist(Hi.getNode());
5456
5457     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5458   }
5459
5460   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5461   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5462     return N1;
5463   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5464   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5465     return N2;
5466
5467   // The ConvertSelectToConcatVector function is assuming both the above
5468   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5469   // and addressed.
5470   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5471       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5472       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5473     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5474     if (CV.getNode())
5475       return CV;
5476   }
5477
5478   return SDValue();
5479 }
5480
5481 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5482   SDValue N0 = N->getOperand(0);
5483   SDValue N1 = N->getOperand(1);
5484   SDValue N2 = N->getOperand(2);
5485   SDValue N3 = N->getOperand(3);
5486   SDValue N4 = N->getOperand(4);
5487   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5488
5489   // fold select_cc lhs, rhs, x, x, cc -> x
5490   if (N2 == N3)
5491     return N2;
5492
5493   // Determine if the condition we're dealing with is constant
5494   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5495                               N0, N1, CC, SDLoc(N), false);
5496   if (SCC.getNode()) {
5497     AddToWorklist(SCC.getNode());
5498
5499     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5500       if (!SCCC->isNullValue())
5501         return N2;    // cond always true -> true val
5502       else
5503         return N3;    // cond always false -> false val
5504     } else if (SCC->getOpcode() == ISD::UNDEF) {
5505       // When the condition is UNDEF, just return the first operand. This is
5506       // coherent the DAG creation, no setcc node is created in this case
5507       return N2;
5508     } else if (SCC.getOpcode() == ISD::SETCC) {
5509       // Fold to a simpler select_cc
5510       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5511                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5512                          SCC.getOperand(2));
5513     }
5514   }
5515
5516   // If we can fold this based on the true/false value, do so.
5517   if (SimplifySelectOps(N, N2, N3))
5518     return SDValue(N, 0);  // Don't revisit N.
5519
5520   // fold select_cc into other things, such as min/max/abs
5521   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5522 }
5523
5524 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5525   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5526                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5527                        SDLoc(N));
5528 }
5529
5530 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5531 // dag node into a ConstantSDNode or a build_vector of constants.
5532 // This function is called by the DAGCombiner when visiting sext/zext/aext
5533 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5534 // Vector extends are not folded if operations are legal; this is to
5535 // avoid introducing illegal build_vector dag nodes.
5536 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5537                                          SelectionDAG &DAG, bool LegalTypes,
5538                                          bool LegalOperations) {
5539   unsigned Opcode = N->getOpcode();
5540   SDValue N0 = N->getOperand(0);
5541   EVT VT = N->getValueType(0);
5542
5543   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5544          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5545
5546   // fold (sext c1) -> c1
5547   // fold (zext c1) -> c1
5548   // fold (aext c1) -> c1
5549   if (isa<ConstantSDNode>(N0))
5550     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5551
5552   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5553   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5554   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5555   EVT SVT = VT.getScalarType();
5556   if (!(VT.isVector() &&
5557       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5558       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5559     return nullptr;
5560
5561   // We can fold this node into a build_vector.
5562   unsigned VTBits = SVT.getSizeInBits();
5563   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5564   unsigned ShAmt = VTBits - EVTBits;
5565   SmallVector<SDValue, 8> Elts;
5566   unsigned NumElts = N0->getNumOperands();
5567   SDLoc DL(N);
5568
5569   for (unsigned i=0; i != NumElts; ++i) {
5570     SDValue Op = N0->getOperand(i);
5571     if (Op->getOpcode() == ISD::UNDEF) {
5572       Elts.push_back(DAG.getUNDEF(SVT));
5573       continue;
5574     }
5575
5576     SDLoc DL(Op);
5577     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5578     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5579     if (Opcode == ISD::SIGN_EXTEND)
5580       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5581                                      DL, SVT));
5582     else
5583       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5584                                      DL, SVT));
5585   }
5586
5587   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5588 }
5589
5590 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5591 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5592 // transformation. Returns true if extension are possible and the above
5593 // mentioned transformation is profitable.
5594 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5595                                     unsigned ExtOpc,
5596                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5597                                     const TargetLowering &TLI) {
5598   bool HasCopyToRegUses = false;
5599   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5600   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5601                             UE = N0.getNode()->use_end();
5602        UI != UE; ++UI) {
5603     SDNode *User = *UI;
5604     if (User == N)
5605       continue;
5606     if (UI.getUse().getResNo() != N0.getResNo())
5607       continue;
5608     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5609     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5610       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5611       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5612         // Sign bits will be lost after a zext.
5613         return false;
5614       bool Add = false;
5615       for (unsigned i = 0; i != 2; ++i) {
5616         SDValue UseOp = User->getOperand(i);
5617         if (UseOp == N0)
5618           continue;
5619         if (!isa<ConstantSDNode>(UseOp))
5620           return false;
5621         Add = true;
5622       }
5623       if (Add)
5624         ExtendNodes.push_back(User);
5625       continue;
5626     }
5627     // If truncates aren't free and there are users we can't
5628     // extend, it isn't worthwhile.
5629     if (!isTruncFree)
5630       return false;
5631     // Remember if this value is live-out.
5632     if (User->getOpcode() == ISD::CopyToReg)
5633       HasCopyToRegUses = true;
5634   }
5635
5636   if (HasCopyToRegUses) {
5637     bool BothLiveOut = false;
5638     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5639          UI != UE; ++UI) {
5640       SDUse &Use = UI.getUse();
5641       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5642         BothLiveOut = true;
5643         break;
5644       }
5645     }
5646     if (BothLiveOut)
5647       // Both unextended and extended values are live out. There had better be
5648       // a good reason for the transformation.
5649       return ExtendNodes.size();
5650   }
5651   return true;
5652 }
5653
5654 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5655                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5656                                   ISD::NodeType ExtType) {
5657   // Extend SetCC uses if necessary.
5658   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5659     SDNode *SetCC = SetCCs[i];
5660     SmallVector<SDValue, 4> Ops;
5661
5662     for (unsigned j = 0; j != 2; ++j) {
5663       SDValue SOp = SetCC->getOperand(j);
5664       if (SOp == Trunc)
5665         Ops.push_back(ExtLoad);
5666       else
5667         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5668     }
5669
5670     Ops.push_back(SetCC->getOperand(2));
5671     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5672   }
5673 }
5674
5675 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5676 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5677   SDValue N0 = N->getOperand(0);
5678   EVT DstVT = N->getValueType(0);
5679   EVT SrcVT = N0.getValueType();
5680
5681   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5682           N->getOpcode() == ISD::ZERO_EXTEND) &&
5683          "Unexpected node type (not an extend)!");
5684
5685   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5686   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5687   //   (v8i32 (sext (v8i16 (load x))))
5688   // into:
5689   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5690   //                          (v4i32 (sextload (x + 16)))))
5691   // Where uses of the original load, i.e.:
5692   //   (v8i16 (load x))
5693   // are replaced with:
5694   //   (v8i16 (truncate
5695   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5696   //                            (v4i32 (sextload (x + 16)))))))
5697   //
5698   // This combine is only applicable to illegal, but splittable, vectors.
5699   // All legal types, and illegal non-vector types, are handled elsewhere.
5700   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5701   //
5702   if (N0->getOpcode() != ISD::LOAD)
5703     return SDValue();
5704
5705   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5706
5707   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5708       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5709       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5710     return SDValue();
5711
5712   SmallVector<SDNode *, 4> SetCCs;
5713   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5714     return SDValue();
5715
5716   ISD::LoadExtType ExtType =
5717       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5718
5719   // Try to split the vector types to get down to legal types.
5720   EVT SplitSrcVT = SrcVT;
5721   EVT SplitDstVT = DstVT;
5722   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5723          SplitSrcVT.getVectorNumElements() > 1) {
5724     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5725     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5726   }
5727
5728   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5729     return SDValue();
5730
5731   SDLoc DL(N);
5732   const unsigned NumSplits =
5733       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5734   const unsigned Stride = SplitSrcVT.getStoreSize();
5735   SmallVector<SDValue, 4> Loads;
5736   SmallVector<SDValue, 4> Chains;
5737
5738   SDValue BasePtr = LN0->getBasePtr();
5739   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5740     const unsigned Offset = Idx * Stride;
5741     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5742
5743     SDValue SplitLoad = DAG.getExtLoad(
5744         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5745         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5746         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5747         Align, LN0->getAAInfo());
5748
5749     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5750                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5751
5752     Loads.push_back(SplitLoad.getValue(0));
5753     Chains.push_back(SplitLoad.getValue(1));
5754   }
5755
5756   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5757   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5758
5759   CombineTo(N, NewValue);
5760
5761   // Replace uses of the original load (before extension)
5762   // with a truncate of the concatenated sextloaded vectors.
5763   SDValue Trunc =
5764       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5765   CombineTo(N0.getNode(), Trunc, NewChain);
5766   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5767                   (ISD::NodeType)N->getOpcode());
5768   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5769 }
5770
5771 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5772   SDValue N0 = N->getOperand(0);
5773   EVT VT = N->getValueType(0);
5774
5775   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5776                                               LegalOperations))
5777     return SDValue(Res, 0);
5778
5779   // fold (sext (sext x)) -> (sext x)
5780   // fold (sext (aext x)) -> (sext x)
5781   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5782     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5783                        N0.getOperand(0));
5784
5785   if (N0.getOpcode() == ISD::TRUNCATE) {
5786     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5787     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5788     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5789     if (NarrowLoad.getNode()) {
5790       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5791       if (NarrowLoad.getNode() != N0.getNode()) {
5792         CombineTo(N0.getNode(), NarrowLoad);
5793         // CombineTo deleted the truncate, if needed, but not what's under it.
5794         AddToWorklist(oye);
5795       }
5796       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5797     }
5798
5799     // See if the value being truncated is already sign extended.  If so, just
5800     // eliminate the trunc/sext pair.
5801     SDValue Op = N0.getOperand(0);
5802     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5803     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5804     unsigned DestBits = VT.getScalarType().getSizeInBits();
5805     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5806
5807     if (OpBits == DestBits) {
5808       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5809       // bits, it is already ready.
5810       if (NumSignBits > DestBits-MidBits)
5811         return Op;
5812     } else if (OpBits < DestBits) {
5813       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5814       // bits, just sext from i32.
5815       if (NumSignBits > OpBits-MidBits)
5816         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5817     } else {
5818       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5819       // bits, just truncate to i32.
5820       if (NumSignBits > OpBits-MidBits)
5821         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5822     }
5823
5824     // fold (sext (truncate x)) -> (sextinreg x).
5825     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5826                                                  N0.getValueType())) {
5827       if (OpBits < DestBits)
5828         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5829       else if (OpBits > DestBits)
5830         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5831       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5832                          DAG.getValueType(N0.getValueType()));
5833     }
5834   }
5835
5836   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5837   // Only generate vector extloads when 1) they're legal, and 2) they are
5838   // deemed desirable by the target.
5839   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5840       ((!LegalOperations && !VT.isVector() &&
5841         !cast<LoadSDNode>(N0)->isVolatile()) ||
5842        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5843     bool DoXform = true;
5844     SmallVector<SDNode*, 4> SetCCs;
5845     if (!N0.hasOneUse())
5846       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5847     if (VT.isVector())
5848       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5849     if (DoXform) {
5850       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5851       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5852                                        LN0->getChain(),
5853                                        LN0->getBasePtr(), N0.getValueType(),
5854                                        LN0->getMemOperand());
5855       CombineTo(N, ExtLoad);
5856       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5857                                   N0.getValueType(), ExtLoad);
5858       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5859       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5860                       ISD::SIGN_EXTEND);
5861       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5862     }
5863   }
5864
5865   // fold (sext (load x)) to multiple smaller sextloads.
5866   // Only on illegal but splittable vectors.
5867   if (SDValue ExtLoad = CombineExtLoad(N))
5868     return ExtLoad;
5869
5870   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5871   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5872   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5873       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5874     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5875     EVT MemVT = LN0->getMemoryVT();
5876     if ((!LegalOperations && !LN0->isVolatile()) ||
5877         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5878       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5879                                        LN0->getChain(),
5880                                        LN0->getBasePtr(), MemVT,
5881                                        LN0->getMemOperand());
5882       CombineTo(N, ExtLoad);
5883       CombineTo(N0.getNode(),
5884                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5885                             N0.getValueType(), ExtLoad),
5886                 ExtLoad.getValue(1));
5887       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5888     }
5889   }
5890
5891   // fold (sext (and/or/xor (load x), cst)) ->
5892   //      (and/or/xor (sextload x), (sext cst))
5893   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5894        N0.getOpcode() == ISD::XOR) &&
5895       isa<LoadSDNode>(N0.getOperand(0)) &&
5896       N0.getOperand(1).getOpcode() == ISD::Constant &&
5897       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5898       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5899     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5900     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5901       bool DoXform = true;
5902       SmallVector<SDNode*, 4> SetCCs;
5903       if (!N0.hasOneUse())
5904         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5905                                           SetCCs, TLI);
5906       if (DoXform) {
5907         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5908                                          LN0->getChain(), LN0->getBasePtr(),
5909                                          LN0->getMemoryVT(),
5910                                          LN0->getMemOperand());
5911         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5912         Mask = Mask.sext(VT.getSizeInBits());
5913         SDLoc DL(N);
5914         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5915                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5916         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5917                                     SDLoc(N0.getOperand(0)),
5918                                     N0.getOperand(0).getValueType(), ExtLoad);
5919         CombineTo(N, And);
5920         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5921         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5922                         ISD::SIGN_EXTEND);
5923         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5924       }
5925     }
5926   }
5927
5928   if (N0.getOpcode() == ISD::SETCC) {
5929     EVT N0VT = N0.getOperand(0).getValueType();
5930     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5931     // Only do this before legalize for now.
5932     if (VT.isVector() && !LegalOperations &&
5933         TLI.getBooleanContents(N0VT) ==
5934             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5935       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5936       // of the same size as the compared operands. Only optimize sext(setcc())
5937       // if this is the case.
5938       EVT SVT = getSetCCResultType(N0VT);
5939
5940       // We know that the # elements of the results is the same as the
5941       // # elements of the compare (and the # elements of the compare result
5942       // for that matter).  Check to see that they are the same size.  If so,
5943       // we know that the element size of the sext'd result matches the
5944       // element size of the compare operands.
5945       if (VT.getSizeInBits() == SVT.getSizeInBits())
5946         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5947                              N0.getOperand(1),
5948                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5949
5950       // If the desired elements are smaller or larger than the source
5951       // elements we can use a matching integer vector type and then
5952       // truncate/sign extend
5953       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5954       if (SVT == MatchingVectorType) {
5955         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5956                                N0.getOperand(0), N0.getOperand(1),
5957                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5958         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5959       }
5960     }
5961
5962     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5963     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5964     SDLoc DL(N);
5965     SDValue NegOne =
5966       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5967     SDValue SCC =
5968       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5969                        NegOne, DAG.getConstant(0, DL, VT),
5970                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5971     if (SCC.getNode()) return SCC;
5972
5973     if (!VT.isVector()) {
5974       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5975       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5976         SDLoc DL(N);
5977         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5978         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5979                                      N0.getOperand(0), N0.getOperand(1), CC);
5980         return DAG.getSelect(DL, VT, SetCC,
5981                              NegOne, DAG.getConstant(0, DL, VT));
5982       }
5983     }
5984   }
5985
5986   // fold (sext x) -> (zext x) if the sign bit is known zero.
5987   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5988       DAG.SignBitIsZero(N0))
5989     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5990
5991   return SDValue();
5992 }
5993
5994 // isTruncateOf - If N is a truncate of some other value, return true, record
5995 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5996 // This function computes KnownZero to avoid a duplicated call to
5997 // computeKnownBits in the caller.
5998 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5999                          APInt &KnownZero) {
6000   APInt KnownOne;
6001   if (N->getOpcode() == ISD::TRUNCATE) {
6002     Op = N->getOperand(0);
6003     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6004     return true;
6005   }
6006
6007   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6008       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6009     return false;
6010
6011   SDValue Op0 = N->getOperand(0);
6012   SDValue Op1 = N->getOperand(1);
6013   assert(Op0.getValueType() == Op1.getValueType());
6014
6015   if (isNullConstant(Op0))
6016     Op = Op1;
6017   else if (isNullConstant(Op1))
6018     Op = Op0;
6019   else
6020     return false;
6021
6022   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6023
6024   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6025     return false;
6026
6027   return true;
6028 }
6029
6030 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6031   SDValue N0 = N->getOperand(0);
6032   EVT VT = N->getValueType(0);
6033
6034   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6035                                               LegalOperations))
6036     return SDValue(Res, 0);
6037
6038   // fold (zext (zext x)) -> (zext x)
6039   // fold (zext (aext x)) -> (zext x)
6040   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6041     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6042                        N0.getOperand(0));
6043
6044   // fold (zext (truncate x)) -> (zext x) or
6045   //      (zext (truncate x)) -> (truncate x)
6046   // This is valid when the truncated bits of x are already zero.
6047   // FIXME: We should extend this to work for vectors too.
6048   SDValue Op;
6049   APInt KnownZero;
6050   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6051     APInt TruncatedBits =
6052       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6053       APInt(Op.getValueSizeInBits(), 0) :
6054       APInt::getBitsSet(Op.getValueSizeInBits(),
6055                         N0.getValueSizeInBits(),
6056                         std::min(Op.getValueSizeInBits(),
6057                                  VT.getSizeInBits()));
6058     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6059       if (VT.bitsGT(Op.getValueType()))
6060         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6061       if (VT.bitsLT(Op.getValueType()))
6062         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6063
6064       return Op;
6065     }
6066   }
6067
6068   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6069   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6070   if (N0.getOpcode() == ISD::TRUNCATE) {
6071     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6072     if (NarrowLoad.getNode()) {
6073       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6074       if (NarrowLoad.getNode() != N0.getNode()) {
6075         CombineTo(N0.getNode(), NarrowLoad);
6076         // CombineTo deleted the truncate, if needed, but not what's under it.
6077         AddToWorklist(oye);
6078       }
6079       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6080     }
6081   }
6082
6083   // fold (zext (truncate x)) -> (and x, mask)
6084   if (N0.getOpcode() == ISD::TRUNCATE &&
6085       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6086
6087     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6088     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6089     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6090     if (NarrowLoad.getNode()) {
6091       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6092       if (NarrowLoad.getNode() != N0.getNode()) {
6093         CombineTo(N0.getNode(), NarrowLoad);
6094         // CombineTo deleted the truncate, if needed, but not what's under it.
6095         AddToWorklist(oye);
6096       }
6097       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6098     }
6099
6100     SDValue Op = N0.getOperand(0);
6101     if (Op.getValueType().bitsLT(VT)) {
6102       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6103       AddToWorklist(Op.getNode());
6104     } else if (Op.getValueType().bitsGT(VT)) {
6105       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6106       AddToWorklist(Op.getNode());
6107     }
6108     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6109                                   N0.getValueType().getScalarType());
6110   }
6111
6112   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6113   // if either of the casts is not free.
6114   if (N0.getOpcode() == ISD::AND &&
6115       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6116       N0.getOperand(1).getOpcode() == ISD::Constant &&
6117       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6118                            N0.getValueType()) ||
6119        !TLI.isZExtFree(N0.getValueType(), VT))) {
6120     SDValue X = N0.getOperand(0).getOperand(0);
6121     if (X.getValueType().bitsLT(VT)) {
6122       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6123     } else if (X.getValueType().bitsGT(VT)) {
6124       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6125     }
6126     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6127     Mask = Mask.zext(VT.getSizeInBits());
6128     SDLoc DL(N);
6129     return DAG.getNode(ISD::AND, DL, VT,
6130                        X, DAG.getConstant(Mask, DL, VT));
6131   }
6132
6133   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6134   // Only generate vector extloads when 1) they're legal, and 2) they are
6135   // deemed desirable by the target.
6136   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6137       ((!LegalOperations && !VT.isVector() &&
6138         !cast<LoadSDNode>(N0)->isVolatile()) ||
6139        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6140     bool DoXform = true;
6141     SmallVector<SDNode*, 4> SetCCs;
6142     if (!N0.hasOneUse())
6143       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6144     if (VT.isVector())
6145       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6146     if (DoXform) {
6147       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6148       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6149                                        LN0->getChain(),
6150                                        LN0->getBasePtr(), N0.getValueType(),
6151                                        LN0->getMemOperand());
6152       CombineTo(N, ExtLoad);
6153       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6154                                   N0.getValueType(), ExtLoad);
6155       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6156
6157       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6158                       ISD::ZERO_EXTEND);
6159       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6160     }
6161   }
6162
6163   // fold (zext (load x)) to multiple smaller zextloads.
6164   // Only on illegal but splittable vectors.
6165   if (SDValue ExtLoad = CombineExtLoad(N))
6166     return ExtLoad;
6167
6168   // fold (zext (and/or/xor (load x), cst)) ->
6169   //      (and/or/xor (zextload x), (zext cst))
6170   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6171        N0.getOpcode() == ISD::XOR) &&
6172       isa<LoadSDNode>(N0.getOperand(0)) &&
6173       N0.getOperand(1).getOpcode() == ISD::Constant &&
6174       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6175       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6176     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6177     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6178       bool DoXform = true;
6179       SmallVector<SDNode*, 4> SetCCs;
6180       if (!N0.hasOneUse())
6181         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6182                                           SetCCs, TLI);
6183       if (DoXform) {
6184         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6185                                          LN0->getChain(), LN0->getBasePtr(),
6186                                          LN0->getMemoryVT(),
6187                                          LN0->getMemOperand());
6188         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6189         Mask = Mask.zext(VT.getSizeInBits());
6190         SDLoc DL(N);
6191         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6192                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6193         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6194                                     SDLoc(N0.getOperand(0)),
6195                                     N0.getOperand(0).getValueType(), ExtLoad);
6196         CombineTo(N, And);
6197         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6198         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6199                         ISD::ZERO_EXTEND);
6200         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6201       }
6202     }
6203   }
6204
6205   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6206   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6207   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6208       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6209     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6210     EVT MemVT = LN0->getMemoryVT();
6211     if ((!LegalOperations && !LN0->isVolatile()) ||
6212         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6213       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6214                                        LN0->getChain(),
6215                                        LN0->getBasePtr(), MemVT,
6216                                        LN0->getMemOperand());
6217       CombineTo(N, ExtLoad);
6218       CombineTo(N0.getNode(),
6219                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6220                             ExtLoad),
6221                 ExtLoad.getValue(1));
6222       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6223     }
6224   }
6225
6226   if (N0.getOpcode() == ISD::SETCC) {
6227     if (!LegalOperations && VT.isVector() &&
6228         N0.getValueType().getVectorElementType() == MVT::i1) {
6229       EVT N0VT = N0.getOperand(0).getValueType();
6230       if (getSetCCResultType(N0VT) == N0.getValueType())
6231         return SDValue();
6232
6233       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6234       // Only do this before legalize for now.
6235       EVT EltVT = VT.getVectorElementType();
6236       SDLoc DL(N);
6237       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6238                                     DAG.getConstant(1, DL, EltVT));
6239       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6240         // We know that the # elements of the results is the same as the
6241         // # elements of the compare (and the # elements of the compare result
6242         // for that matter).  Check to see that they are the same size.  If so,
6243         // we know that the element size of the sext'd result matches the
6244         // element size of the compare operands.
6245         return DAG.getNode(ISD::AND, DL, VT,
6246                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6247                                          N0.getOperand(1),
6248                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6249                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6250                                        OneOps));
6251
6252       // If the desired elements are smaller or larger than the source
6253       // elements we can use a matching integer vector type and then
6254       // truncate/sign extend
6255       EVT MatchingElementType =
6256         EVT::getIntegerVT(*DAG.getContext(),
6257                           N0VT.getScalarType().getSizeInBits());
6258       EVT MatchingVectorType =
6259         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6260                          N0VT.getVectorNumElements());
6261       SDValue VsetCC =
6262         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6263                       N0.getOperand(1),
6264                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6265       return DAG.getNode(ISD::AND, DL, VT,
6266                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6267                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6268     }
6269
6270     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6271     SDLoc DL(N);
6272     SDValue SCC =
6273       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6274                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6275                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6276     if (SCC.getNode()) return SCC;
6277   }
6278
6279   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6280   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6281       isa<ConstantSDNode>(N0.getOperand(1)) &&
6282       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6283       N0.hasOneUse()) {
6284     SDValue ShAmt = N0.getOperand(1);
6285     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6286     if (N0.getOpcode() == ISD::SHL) {
6287       SDValue InnerZExt = N0.getOperand(0);
6288       // If the original shl may be shifting out bits, do not perform this
6289       // transformation.
6290       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6291         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6292       if (ShAmtVal > KnownZeroBits)
6293         return SDValue();
6294     }
6295
6296     SDLoc DL(N);
6297
6298     // Ensure that the shift amount is wide enough for the shifted value.
6299     if (VT.getSizeInBits() >= 256)
6300       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6301
6302     return DAG.getNode(N0.getOpcode(), DL, VT,
6303                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6304                        ShAmt);
6305   }
6306
6307   return SDValue();
6308 }
6309
6310 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6311   SDValue N0 = N->getOperand(0);
6312   EVT VT = N->getValueType(0);
6313
6314   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6315                                               LegalOperations))
6316     return SDValue(Res, 0);
6317
6318   // fold (aext (aext x)) -> (aext x)
6319   // fold (aext (zext x)) -> (zext x)
6320   // fold (aext (sext x)) -> (sext x)
6321   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6322       N0.getOpcode() == ISD::ZERO_EXTEND ||
6323       N0.getOpcode() == ISD::SIGN_EXTEND)
6324     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6325
6326   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6327   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6328   if (N0.getOpcode() == ISD::TRUNCATE) {
6329     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6330     if (NarrowLoad.getNode()) {
6331       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6332       if (NarrowLoad.getNode() != N0.getNode()) {
6333         CombineTo(N0.getNode(), NarrowLoad);
6334         // CombineTo deleted the truncate, if needed, but not what's under it.
6335         AddToWorklist(oye);
6336       }
6337       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6338     }
6339   }
6340
6341   // fold (aext (truncate x))
6342   if (N0.getOpcode() == ISD::TRUNCATE) {
6343     SDValue TruncOp = N0.getOperand(0);
6344     if (TruncOp.getValueType() == VT)
6345       return TruncOp; // x iff x size == zext size.
6346     if (TruncOp.getValueType().bitsGT(VT))
6347       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6348     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6349   }
6350
6351   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6352   // if the trunc is not free.
6353   if (N0.getOpcode() == ISD::AND &&
6354       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6355       N0.getOperand(1).getOpcode() == ISD::Constant &&
6356       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6357                           N0.getValueType())) {
6358     SDValue X = N0.getOperand(0).getOperand(0);
6359     if (X.getValueType().bitsLT(VT)) {
6360       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6361     } else if (X.getValueType().bitsGT(VT)) {
6362       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6363     }
6364     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6365     Mask = Mask.zext(VT.getSizeInBits());
6366     SDLoc DL(N);
6367     return DAG.getNode(ISD::AND, DL, VT,
6368                        X, DAG.getConstant(Mask, DL, VT));
6369   }
6370
6371   // fold (aext (load x)) -> (aext (truncate (extload x)))
6372   // None of the supported targets knows how to perform load and any_ext
6373   // on vectors in one instruction.  We only perform this transformation on
6374   // scalars.
6375   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6376       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6377       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6378     bool DoXform = true;
6379     SmallVector<SDNode*, 4> SetCCs;
6380     if (!N0.hasOneUse())
6381       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6382     if (DoXform) {
6383       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6384       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6385                                        LN0->getChain(),
6386                                        LN0->getBasePtr(), N0.getValueType(),
6387                                        LN0->getMemOperand());
6388       CombineTo(N, ExtLoad);
6389       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6390                                   N0.getValueType(), ExtLoad);
6391       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6392       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6393                       ISD::ANY_EXTEND);
6394       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6395     }
6396   }
6397
6398   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6399   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6400   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6401   if (N0.getOpcode() == ISD::LOAD &&
6402       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6403       N0.hasOneUse()) {
6404     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6405     ISD::LoadExtType ExtType = LN0->getExtensionType();
6406     EVT MemVT = LN0->getMemoryVT();
6407     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6408       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6409                                        VT, LN0->getChain(), LN0->getBasePtr(),
6410                                        MemVT, LN0->getMemOperand());
6411       CombineTo(N, ExtLoad);
6412       CombineTo(N0.getNode(),
6413                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6414                             N0.getValueType(), ExtLoad),
6415                 ExtLoad.getValue(1));
6416       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6417     }
6418   }
6419
6420   if (N0.getOpcode() == ISD::SETCC) {
6421     // For vectors:
6422     // aext(setcc) -> vsetcc
6423     // aext(setcc) -> truncate(vsetcc)
6424     // aext(setcc) -> aext(vsetcc)
6425     // Only do this before legalize for now.
6426     if (VT.isVector() && !LegalOperations) {
6427       EVT N0VT = N0.getOperand(0).getValueType();
6428         // We know that the # elements of the results is the same as the
6429         // # elements of the compare (and the # elements of the compare result
6430         // for that matter).  Check to see that they are the same size.  If so,
6431         // we know that the element size of the sext'd result matches the
6432         // element size of the compare operands.
6433       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6434         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6435                              N0.getOperand(1),
6436                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6437       // If the desired elements are smaller or larger than the source
6438       // elements we can use a matching integer vector type and then
6439       // truncate/any extend
6440       else {
6441         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6442         SDValue VsetCC =
6443           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6444                         N0.getOperand(1),
6445                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6446         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6447       }
6448     }
6449
6450     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6451     SDLoc DL(N);
6452     SDValue SCC =
6453       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6454                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6455                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6456     if (SCC.getNode())
6457       return SCC;
6458   }
6459
6460   return SDValue();
6461 }
6462
6463 /// See if the specified operand can be simplified with the knowledge that only
6464 /// the bits specified by Mask are used.  If so, return the simpler operand,
6465 /// otherwise return a null SDValue.
6466 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6467   switch (V.getOpcode()) {
6468   default: break;
6469   case ISD::Constant: {
6470     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6471     assert(CV && "Const value should be ConstSDNode.");
6472     const APInt &CVal = CV->getAPIntValue();
6473     APInt NewVal = CVal & Mask;
6474     if (NewVal != CVal)
6475       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6476     break;
6477   }
6478   case ISD::OR:
6479   case ISD::XOR:
6480     // If the LHS or RHS don't contribute bits to the or, drop them.
6481     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6482       return V.getOperand(1);
6483     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6484       return V.getOperand(0);
6485     break;
6486   case ISD::SRL:
6487     // Only look at single-use SRLs.
6488     if (!V.getNode()->hasOneUse())
6489       break;
6490     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6491       // See if we can recursively simplify the LHS.
6492       unsigned Amt = RHSC->getZExtValue();
6493
6494       // Watch out for shift count overflow though.
6495       if (Amt >= Mask.getBitWidth()) break;
6496       APInt NewMask = Mask << Amt;
6497       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6498       if (SimplifyLHS.getNode())
6499         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6500                            SimplifyLHS, V.getOperand(1));
6501     }
6502   }
6503   return SDValue();
6504 }
6505
6506 /// If the result of a wider load is shifted to right of N  bits and then
6507 /// truncated to a narrower type and where N is a multiple of number of bits of
6508 /// the narrower type, transform it to a narrower load from address + N / num of
6509 /// bits of new type. If the result is to be extended, also fold the extension
6510 /// to form a extending load.
6511 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6512   unsigned Opc = N->getOpcode();
6513
6514   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6515   SDValue N0 = N->getOperand(0);
6516   EVT VT = N->getValueType(0);
6517   EVT ExtVT = VT;
6518
6519   // This transformation isn't valid for vector loads.
6520   if (VT.isVector())
6521     return SDValue();
6522
6523   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6524   // extended to VT.
6525   if (Opc == ISD::SIGN_EXTEND_INREG) {
6526     ExtType = ISD::SEXTLOAD;
6527     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6528   } else if (Opc == ISD::SRL) {
6529     // Another special-case: SRL is basically zero-extending a narrower value.
6530     ExtType = ISD::ZEXTLOAD;
6531     N0 = SDValue(N, 0);
6532     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6533     if (!N01) return SDValue();
6534     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6535                               VT.getSizeInBits() - N01->getZExtValue());
6536   }
6537   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6538     return SDValue();
6539
6540   unsigned EVTBits = ExtVT.getSizeInBits();
6541
6542   // Do not generate loads of non-round integer types since these can
6543   // be expensive (and would be wrong if the type is not byte sized).
6544   if (!ExtVT.isRound())
6545     return SDValue();
6546
6547   unsigned ShAmt = 0;
6548   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6549     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6550       ShAmt = N01->getZExtValue();
6551       // Is the shift amount a multiple of size of VT?
6552       if ((ShAmt & (EVTBits-1)) == 0) {
6553         N0 = N0.getOperand(0);
6554         // Is the load width a multiple of size of VT?
6555         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6556           return SDValue();
6557       }
6558
6559       // At this point, we must have a load or else we can't do the transform.
6560       if (!isa<LoadSDNode>(N0)) return SDValue();
6561
6562       // Because a SRL must be assumed to *need* to zero-extend the high bits
6563       // (as opposed to anyext the high bits), we can't combine the zextload
6564       // lowering of SRL and an sextload.
6565       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6566         return SDValue();
6567
6568       // If the shift amount is larger than the input type then we're not
6569       // accessing any of the loaded bytes.  If the load was a zextload/extload
6570       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6571       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6572         return SDValue();
6573     }
6574   }
6575
6576   // If the load is shifted left (and the result isn't shifted back right),
6577   // we can fold the truncate through the shift.
6578   unsigned ShLeftAmt = 0;
6579   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6580       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6581     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6582       ShLeftAmt = N01->getZExtValue();
6583       N0 = N0.getOperand(0);
6584     }
6585   }
6586
6587   // If we haven't found a load, we can't narrow it.  Don't transform one with
6588   // multiple uses, this would require adding a new load.
6589   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6590     return SDValue();
6591
6592   // Don't change the width of a volatile load.
6593   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6594   if (LN0->isVolatile())
6595     return SDValue();
6596
6597   // Verify that we are actually reducing a load width here.
6598   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6599     return SDValue();
6600
6601   // For the transform to be legal, the load must produce only two values
6602   // (the value loaded and the chain).  Don't transform a pre-increment
6603   // load, for example, which produces an extra value.  Otherwise the
6604   // transformation is not equivalent, and the downstream logic to replace
6605   // uses gets things wrong.
6606   if (LN0->getNumValues() > 2)
6607     return SDValue();
6608
6609   // If the load that we're shrinking is an extload and we're not just
6610   // discarding the extension we can't simply shrink the load. Bail.
6611   // TODO: It would be possible to merge the extensions in some cases.
6612   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6613       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6614     return SDValue();
6615
6616   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6617     return SDValue();
6618
6619   EVT PtrType = N0.getOperand(1).getValueType();
6620
6621   if (PtrType == MVT::Untyped || PtrType.isExtended())
6622     // It's not possible to generate a constant of extended or untyped type.
6623     return SDValue();
6624
6625   // For big endian targets, we need to adjust the offset to the pointer to
6626   // load the correct bytes.
6627   if (TLI.isBigEndian()) {
6628     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6629     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6630     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6631   }
6632
6633   uint64_t PtrOff = ShAmt / 8;
6634   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6635   SDLoc DL(LN0);
6636   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6637                                PtrType, LN0->getBasePtr(),
6638                                DAG.getConstant(PtrOff, DL, PtrType));
6639   AddToWorklist(NewPtr.getNode());
6640
6641   SDValue Load;
6642   if (ExtType == ISD::NON_EXTLOAD)
6643     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6644                         LN0->getPointerInfo().getWithOffset(PtrOff),
6645                         LN0->isVolatile(), LN0->isNonTemporal(),
6646                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6647   else
6648     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6649                           LN0->getPointerInfo().getWithOffset(PtrOff),
6650                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6651                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6652
6653   // Replace the old load's chain with the new load's chain.
6654   WorklistRemover DeadNodes(*this);
6655   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6656
6657   // Shift the result left, if we've swallowed a left shift.
6658   SDValue Result = Load;
6659   if (ShLeftAmt != 0) {
6660     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6661     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6662       ShImmTy = VT;
6663     // If the shift amount is as large as the result size (but, presumably,
6664     // no larger than the source) then the useful bits of the result are
6665     // zero; we can't simply return the shortened shift, because the result
6666     // of that operation is undefined.
6667     SDLoc DL(N0);
6668     if (ShLeftAmt >= VT.getSizeInBits())
6669       Result = DAG.getConstant(0, DL, VT);
6670     else
6671       Result = DAG.getNode(ISD::SHL, DL, VT,
6672                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6673   }
6674
6675   // Return the new loaded value.
6676   return Result;
6677 }
6678
6679 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6680   SDValue N0 = N->getOperand(0);
6681   SDValue N1 = N->getOperand(1);
6682   EVT VT = N->getValueType(0);
6683   EVT EVT = cast<VTSDNode>(N1)->getVT();
6684   unsigned VTBits = VT.getScalarType().getSizeInBits();
6685   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6686
6687   // fold (sext_in_reg c1) -> c1
6688   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6689     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6690
6691   // If the input is already sign extended, just drop the extension.
6692   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6693     return N0;
6694
6695   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6696   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6697       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6698     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6699                        N0.getOperand(0), N1);
6700
6701   // fold (sext_in_reg (sext x)) -> (sext x)
6702   // fold (sext_in_reg (aext x)) -> (sext x)
6703   // if x is small enough.
6704   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6705     SDValue N00 = N0.getOperand(0);
6706     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6707         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6708       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6709   }
6710
6711   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6712   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6713     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6714
6715   // fold operands of sext_in_reg based on knowledge that the top bits are not
6716   // demanded.
6717   if (SimplifyDemandedBits(SDValue(N, 0)))
6718     return SDValue(N, 0);
6719
6720   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6721   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6722   SDValue NarrowLoad = ReduceLoadWidth(N);
6723   if (NarrowLoad.getNode())
6724     return NarrowLoad;
6725
6726   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6727   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6728   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6729   if (N0.getOpcode() == ISD::SRL) {
6730     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6731       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6732         // We can turn this into an SRA iff the input to the SRL is already sign
6733         // extended enough.
6734         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6735         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6736           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6737                              N0.getOperand(0), N0.getOperand(1));
6738       }
6739   }
6740
6741   // fold (sext_inreg (extload x)) -> (sextload x)
6742   if (ISD::isEXTLoad(N0.getNode()) &&
6743       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6744       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6745       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6746        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6747     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6748     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6749                                      LN0->getChain(),
6750                                      LN0->getBasePtr(), EVT,
6751                                      LN0->getMemOperand());
6752     CombineTo(N, ExtLoad);
6753     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6754     AddToWorklist(ExtLoad.getNode());
6755     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6756   }
6757   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6758   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6759       N0.hasOneUse() &&
6760       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6761       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6762        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6763     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6764     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6765                                      LN0->getChain(),
6766                                      LN0->getBasePtr(), EVT,
6767                                      LN0->getMemOperand());
6768     CombineTo(N, ExtLoad);
6769     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6770     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6771   }
6772
6773   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6774   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6775     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6776                                        N0.getOperand(1), false);
6777     if (BSwap.getNode())
6778       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6779                          BSwap, N1);
6780   }
6781
6782   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6783   // into a build_vector.
6784   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6785     SmallVector<SDValue, 8> Elts;
6786     unsigned NumElts = N0->getNumOperands();
6787     unsigned ShAmt = VTBits - EVTBits;
6788
6789     for (unsigned i = 0; i != NumElts; ++i) {
6790       SDValue Op = N0->getOperand(i);
6791       if (Op->getOpcode() == ISD::UNDEF) {
6792         Elts.push_back(Op);
6793         continue;
6794       }
6795
6796       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6797       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6798       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6799                                      SDLoc(Op), Op.getValueType()));
6800     }
6801
6802     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6803   }
6804
6805   return SDValue();
6806 }
6807
6808 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6809   SDValue N0 = N->getOperand(0);
6810   EVT VT = N->getValueType(0);
6811   bool isLE = TLI.isLittleEndian();
6812
6813   // noop truncate
6814   if (N0.getValueType() == N->getValueType(0))
6815     return N0;
6816   // fold (truncate c1) -> c1
6817   if (isConstantIntBuildVectorOrConstantInt(N0))
6818     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6819   // fold (truncate (truncate x)) -> (truncate x)
6820   if (N0.getOpcode() == ISD::TRUNCATE)
6821     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6822   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6823   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6824       N0.getOpcode() == ISD::SIGN_EXTEND ||
6825       N0.getOpcode() == ISD::ANY_EXTEND) {
6826     if (N0.getOperand(0).getValueType().bitsLT(VT))
6827       // if the source is smaller than the dest, we still need an extend
6828       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6829                          N0.getOperand(0));
6830     if (N0.getOperand(0).getValueType().bitsGT(VT))
6831       // if the source is larger than the dest, than we just need the truncate
6832       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6833     // if the source and dest are the same type, we can drop both the extend
6834     // and the truncate.
6835     return N0.getOperand(0);
6836   }
6837
6838   // Fold extract-and-trunc into a narrow extract. For example:
6839   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6840   //   i32 y = TRUNCATE(i64 x)
6841   //        -- becomes --
6842   //   v16i8 b = BITCAST (v2i64 val)
6843   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6844   //
6845   // Note: We only run this optimization after type legalization (which often
6846   // creates this pattern) and before operation legalization after which
6847   // we need to be more careful about the vector instructions that we generate.
6848   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6849       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6850
6851     EVT VecTy = N0.getOperand(0).getValueType();
6852     EVT ExTy = N0.getValueType();
6853     EVT TrTy = N->getValueType(0);
6854
6855     unsigned NumElem = VecTy.getVectorNumElements();
6856     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6857
6858     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6859     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6860
6861     SDValue EltNo = N0->getOperand(1);
6862     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6863       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6864       EVT IndexTy = TLI.getVectorIdxTy();
6865       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6866
6867       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6868                               NVT, N0.getOperand(0));
6869
6870       SDLoc DL(N);
6871       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6872                          DL, TrTy, V,
6873                          DAG.getConstant(Index, DL, IndexTy));
6874     }
6875   }
6876
6877   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6878   if (N0.getOpcode() == ISD::SELECT) {
6879     EVT SrcVT = N0.getValueType();
6880     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6881         TLI.isTruncateFree(SrcVT, VT)) {
6882       SDLoc SL(N0);
6883       SDValue Cond = N0.getOperand(0);
6884       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6885       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6886       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6887     }
6888   }
6889
6890   // Fold a series of buildvector, bitcast, and truncate if possible.
6891   // For example fold
6892   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6893   //   (2xi32 (buildvector x, y)).
6894   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6895       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6896       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6897       N0.getOperand(0).hasOneUse()) {
6898
6899     SDValue BuildVect = N0.getOperand(0);
6900     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6901     EVT TruncVecEltTy = VT.getVectorElementType();
6902
6903     // Check that the element types match.
6904     if (BuildVectEltTy == TruncVecEltTy) {
6905       // Now we only need to compute the offset of the truncated elements.
6906       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6907       unsigned TruncVecNumElts = VT.getVectorNumElements();
6908       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6909
6910       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6911              "Invalid number of elements");
6912
6913       SmallVector<SDValue, 8> Opnds;
6914       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6915         Opnds.push_back(BuildVect.getOperand(i));
6916
6917       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6918     }
6919   }
6920
6921   // See if we can simplify the input to this truncate through knowledge that
6922   // only the low bits are being used.
6923   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6924   // Currently we only perform this optimization on scalars because vectors
6925   // may have different active low bits.
6926   if (!VT.isVector()) {
6927     SDValue Shorter =
6928       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6929                                                VT.getSizeInBits()));
6930     if (Shorter.getNode())
6931       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6932   }
6933   // fold (truncate (load x)) -> (smaller load x)
6934   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6935   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6936     SDValue Reduced = ReduceLoadWidth(N);
6937     if (Reduced.getNode())
6938       return Reduced;
6939     // Handle the case where the load remains an extending load even
6940     // after truncation.
6941     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6942       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6943       if (!LN0->isVolatile() &&
6944           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6945         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6946                                          VT, LN0->getChain(), LN0->getBasePtr(),
6947                                          LN0->getMemoryVT(),
6948                                          LN0->getMemOperand());
6949         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6950         return NewLoad;
6951       }
6952     }
6953   }
6954   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6955   // where ... are all 'undef'.
6956   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6957     SmallVector<EVT, 8> VTs;
6958     SDValue V;
6959     unsigned Idx = 0;
6960     unsigned NumDefs = 0;
6961
6962     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6963       SDValue X = N0.getOperand(i);
6964       if (X.getOpcode() != ISD::UNDEF) {
6965         V = X;
6966         Idx = i;
6967         NumDefs++;
6968       }
6969       // Stop if more than one members are non-undef.
6970       if (NumDefs > 1)
6971         break;
6972       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6973                                      VT.getVectorElementType(),
6974                                      X.getValueType().getVectorNumElements()));
6975     }
6976
6977     if (NumDefs == 0)
6978       return DAG.getUNDEF(VT);
6979
6980     if (NumDefs == 1) {
6981       assert(V.getNode() && "The single defined operand is empty!");
6982       SmallVector<SDValue, 8> Opnds;
6983       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6984         if (i != Idx) {
6985           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6986           continue;
6987         }
6988         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6989         AddToWorklist(NV.getNode());
6990         Opnds.push_back(NV);
6991       }
6992       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6993     }
6994   }
6995
6996   // Simplify the operands using demanded-bits information.
6997   if (!VT.isVector() &&
6998       SimplifyDemandedBits(SDValue(N, 0)))
6999     return SDValue(N, 0);
7000
7001   return SDValue();
7002 }
7003
7004 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7005   SDValue Elt = N->getOperand(i);
7006   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7007     return Elt.getNode();
7008   return Elt.getOperand(Elt.getResNo()).getNode();
7009 }
7010
7011 /// build_pair (load, load) -> load
7012 /// if load locations are consecutive.
7013 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7014   assert(N->getOpcode() == ISD::BUILD_PAIR);
7015
7016   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7017   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7018   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7019       LD1->getAddressSpace() != LD2->getAddressSpace())
7020     return SDValue();
7021   EVT LD1VT = LD1->getValueType(0);
7022
7023   if (ISD::isNON_EXTLoad(LD2) &&
7024       LD2->hasOneUse() &&
7025       // If both are volatile this would reduce the number of volatile loads.
7026       // If one is volatile it might be ok, but play conservative and bail out.
7027       !LD1->isVolatile() &&
7028       !LD2->isVolatile() &&
7029       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7030     unsigned Align = LD1->getAlignment();
7031     unsigned NewAlign = TLI.getDataLayout()->
7032       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7033
7034     if (NewAlign <= Align &&
7035         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7036       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7037                          LD1->getBasePtr(), LD1->getPointerInfo(),
7038                          false, false, false, Align);
7039   }
7040
7041   return SDValue();
7042 }
7043
7044 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7045   SDValue N0 = N->getOperand(0);
7046   EVT VT = N->getValueType(0);
7047
7048   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7049   // Only do this before legalize, since afterward the target may be depending
7050   // on the bitconvert.
7051   // First check to see if this is all constant.
7052   if (!LegalTypes &&
7053       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7054       VT.isVector()) {
7055     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7056
7057     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7058     assert(!DestEltVT.isVector() &&
7059            "Element type of vector ValueType must not be vector!");
7060     if (isSimple)
7061       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7062   }
7063
7064   // If the input is a constant, let getNode fold it.
7065   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7066     // If we can't allow illegal operations, we need to check that this is just
7067     // a fp -> int or int -> conversion and that the resulting operation will
7068     // be legal.
7069     if (!LegalOperations ||
7070         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7071          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7072         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7073          TLI.isOperationLegal(ISD::Constant, VT)))
7074       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7075   }
7076
7077   // (conv (conv x, t1), t2) -> (conv x, t2)
7078   if (N0.getOpcode() == ISD::BITCAST)
7079     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7080                        N0.getOperand(0));
7081
7082   // fold (conv (load x)) -> (load (conv*)x)
7083   // If the resultant load doesn't need a higher alignment than the original!
7084   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7085       // Do not change the width of a volatile load.
7086       !cast<LoadSDNode>(N0)->isVolatile() &&
7087       // Do not remove the cast if the types differ in endian layout.
7088       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7089       TLI.hasBigEndianPartOrdering(VT) &&
7090       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7091       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7092     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7093     unsigned Align = TLI.getDataLayout()->
7094       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7095     unsigned OrigAlign = LN0->getAlignment();
7096
7097     if (Align <= OrigAlign) {
7098       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7099                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7100                                  LN0->isVolatile(), LN0->isNonTemporal(),
7101                                  LN0->isInvariant(), OrigAlign,
7102                                  LN0->getAAInfo());
7103       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7104       return Load;
7105     }
7106   }
7107
7108   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7109   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7110   // This often reduces constant pool loads.
7111   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7112        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7113       N0.getNode()->hasOneUse() && VT.isInteger() &&
7114       !VT.isVector() && !N0.getValueType().isVector()) {
7115     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7116                                   N0.getOperand(0));
7117     AddToWorklist(NewConv.getNode());
7118
7119     SDLoc DL(N);
7120     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7121     if (N0.getOpcode() == ISD::FNEG)
7122       return DAG.getNode(ISD::XOR, DL, VT,
7123                          NewConv, DAG.getConstant(SignBit, DL, VT));
7124     assert(N0.getOpcode() == ISD::FABS);
7125     return DAG.getNode(ISD::AND, DL, VT,
7126                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7127   }
7128
7129   // fold (bitconvert (fcopysign cst, x)) ->
7130   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7131   // Note that we don't handle (copysign x, cst) because this can always be
7132   // folded to an fneg or fabs.
7133   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7134       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7135       VT.isInteger() && !VT.isVector()) {
7136     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7137     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7138     if (isTypeLegal(IntXVT)) {
7139       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7140                               IntXVT, N0.getOperand(1));
7141       AddToWorklist(X.getNode());
7142
7143       // If X has a different width than the result/lhs, sext it or truncate it.
7144       unsigned VTWidth = VT.getSizeInBits();
7145       if (OrigXWidth < VTWidth) {
7146         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7147         AddToWorklist(X.getNode());
7148       } else if (OrigXWidth > VTWidth) {
7149         // To get the sign bit in the right place, we have to shift it right
7150         // before truncating.
7151         SDLoc DL(X);
7152         X = DAG.getNode(ISD::SRL, DL,
7153                         X.getValueType(), X,
7154                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7155                                         X.getValueType()));
7156         AddToWorklist(X.getNode());
7157         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7158         AddToWorklist(X.getNode());
7159       }
7160
7161       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7162       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7163                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7164       AddToWorklist(X.getNode());
7165
7166       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7167                                 VT, N0.getOperand(0));
7168       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7169                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7170       AddToWorklist(Cst.getNode());
7171
7172       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7173     }
7174   }
7175
7176   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7177   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7178     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7179     if (CombineLD.getNode())
7180       return CombineLD;
7181   }
7182
7183   // Remove double bitcasts from shuffles - this is often a legacy of
7184   // XformToShuffleWithZero being used to combine bitmaskings (of
7185   // float vectors bitcast to integer vectors) into shuffles.
7186   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7187   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7188       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7189       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7190       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7191     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7192
7193     // If operands are a bitcast, peek through if it casts the original VT.
7194     // If operands are a UNDEF or constant, just bitcast back to original VT.
7195     auto PeekThroughBitcast = [&](SDValue Op) {
7196       if (Op.getOpcode() == ISD::BITCAST &&
7197           Op.getOperand(0)->getValueType(0) == VT)
7198         return SDValue(Op.getOperand(0));
7199       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7200           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7201         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7202       return SDValue();
7203     };
7204
7205     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7206     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7207     if (!(SV0 && SV1))
7208       return SDValue();
7209
7210     int MaskScale =
7211         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7212     SmallVector<int, 8> NewMask;
7213     for (int M : SVN->getMask())
7214       for (int i = 0; i != MaskScale; ++i)
7215         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7216
7217     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7218     if (!LegalMask) {
7219       std::swap(SV0, SV1);
7220       ShuffleVectorSDNode::commuteMask(NewMask);
7221       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7222     }
7223
7224     if (LegalMask)
7225       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7226   }
7227
7228   return SDValue();
7229 }
7230
7231 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7232   EVT VT = N->getValueType(0);
7233   return CombineConsecutiveLoads(N, VT);
7234 }
7235
7236 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7237 /// operands. DstEltVT indicates the destination element value type.
7238 SDValue DAGCombiner::
7239 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7240   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7241
7242   // If this is already the right type, we're done.
7243   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7244
7245   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7246   unsigned DstBitSize = DstEltVT.getSizeInBits();
7247
7248   // If this is a conversion of N elements of one type to N elements of another
7249   // type, convert each element.  This handles FP<->INT cases.
7250   if (SrcBitSize == DstBitSize) {
7251     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7252                               BV->getValueType(0).getVectorNumElements());
7253
7254     // Due to the FP element handling below calling this routine recursively,
7255     // we can end up with a scalar-to-vector node here.
7256     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7257       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7258                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7259                                      DstEltVT, BV->getOperand(0)));
7260
7261     SmallVector<SDValue, 8> Ops;
7262     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7263       SDValue Op = BV->getOperand(i);
7264       // If the vector element type is not legal, the BUILD_VECTOR operands
7265       // are promoted and implicitly truncated.  Make that explicit here.
7266       if (Op.getValueType() != SrcEltVT)
7267         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7268       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7269                                 DstEltVT, Op));
7270       AddToWorklist(Ops.back().getNode());
7271     }
7272     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7273   }
7274
7275   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7276   // handle annoying details of growing/shrinking FP values, we convert them to
7277   // int first.
7278   if (SrcEltVT.isFloatingPoint()) {
7279     // Convert the input float vector to a int vector where the elements are the
7280     // same sizes.
7281     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7282     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7283     SrcEltVT = IntVT;
7284   }
7285
7286   // Now we know the input is an integer vector.  If the output is a FP type,
7287   // convert to integer first, then to FP of the right size.
7288   if (DstEltVT.isFloatingPoint()) {
7289     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7290     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7291
7292     // Next, convert to FP elements of the same size.
7293     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7294   }
7295
7296   SDLoc DL(BV);
7297
7298   // Okay, we know the src/dst types are both integers of differing types.
7299   // Handling growing first.
7300   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7301   if (SrcBitSize < DstBitSize) {
7302     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7303
7304     SmallVector<SDValue, 8> Ops;
7305     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7306          i += NumInputsPerOutput) {
7307       bool isLE = TLI.isLittleEndian();
7308       APInt NewBits = APInt(DstBitSize, 0);
7309       bool EltIsUndef = true;
7310       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7311         // Shift the previously computed bits over.
7312         NewBits <<= SrcBitSize;
7313         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7314         if (Op.getOpcode() == ISD::UNDEF) continue;
7315         EltIsUndef = false;
7316
7317         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7318                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7319       }
7320
7321       if (EltIsUndef)
7322         Ops.push_back(DAG.getUNDEF(DstEltVT));
7323       else
7324         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7325     }
7326
7327     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7328     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7329   }
7330
7331   // Finally, this must be the case where we are shrinking elements: each input
7332   // turns into multiple outputs.
7333   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7334   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7335                             NumOutputsPerInput*BV->getNumOperands());
7336   SmallVector<SDValue, 8> Ops;
7337
7338   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7339     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7340       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7341       continue;
7342     }
7343
7344     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7345                   getAPIntValue().zextOrTrunc(SrcBitSize);
7346
7347     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7348       APInt ThisVal = OpVal.trunc(DstBitSize);
7349       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7350       OpVal = OpVal.lshr(DstBitSize);
7351     }
7352
7353     // For big endian targets, swap the order of the pieces of each element.
7354     if (TLI.isBigEndian())
7355       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7356   }
7357
7358   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7359 }
7360
7361 /// Try to perform FMA combining on a given FADD node.
7362 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7363   SDValue N0 = N->getOperand(0);
7364   SDValue N1 = N->getOperand(1);
7365   EVT VT = N->getValueType(0);
7366   SDLoc SL(N);
7367
7368   const TargetOptions &Options = DAG.getTarget().Options;
7369   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7370                        Options.UnsafeFPMath);
7371
7372   // Floating-point multiply-add with intermediate rounding.
7373   bool HasFMAD = (LegalOperations &&
7374                   TLI.isOperationLegal(ISD::FMAD, VT));
7375
7376   // Floating-point multiply-add without intermediate rounding.
7377   bool HasFMA = ((!LegalOperations ||
7378                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7379                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7380                  UnsafeFPMath);
7381
7382   // No valid opcode, do not combine.
7383   if (!HasFMAD && !HasFMA)
7384     return SDValue();
7385
7386   // Always prefer FMAD to FMA for precision.
7387   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7388   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7389   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7390
7391   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7392   if (N0.getOpcode() == ISD::FMUL &&
7393       (Aggressive || N0->hasOneUse())) {
7394     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7395                        N0.getOperand(0), N0.getOperand(1), N1);
7396   }
7397
7398   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7399   // Note: Commutes FADD operands.
7400   if (N1.getOpcode() == ISD::FMUL &&
7401       (Aggressive || N1->hasOneUse())) {
7402     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7403                        N1.getOperand(0), N1.getOperand(1), N0);
7404   }
7405
7406   // Look through FP_EXTEND nodes to do more combining.
7407   if (UnsafeFPMath && LookThroughFPExt) {
7408     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7409     if (N0.getOpcode() == ISD::FP_EXTEND) {
7410       SDValue N00 = N0.getOperand(0);
7411       if (N00.getOpcode() == ISD::FMUL)
7412         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7414                                        N00.getOperand(0)),
7415                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416                                        N00.getOperand(1)), N1);
7417     }
7418
7419     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7420     // Note: Commutes FADD operands.
7421     if (N1.getOpcode() == ISD::FP_EXTEND) {
7422       SDValue N10 = N1.getOperand(0);
7423       if (N10.getOpcode() == ISD::FMUL)
7424         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7425                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7426                                        N10.getOperand(0)),
7427                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7428                                        N10.getOperand(1)), N0);
7429     }
7430   }
7431
7432   // More folding opportunities when target permits.
7433   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7434     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7435     if (N0.getOpcode() == PreferredFusedOpcode &&
7436         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7437       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7438                          N0.getOperand(0), N0.getOperand(1),
7439                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7440                                      N0.getOperand(2).getOperand(0),
7441                                      N0.getOperand(2).getOperand(1),
7442                                      N1));
7443     }
7444
7445     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7446     if (N1->getOpcode() == PreferredFusedOpcode &&
7447         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7448       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7449                          N1.getOperand(0), N1.getOperand(1),
7450                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7451                                      N1.getOperand(2).getOperand(0),
7452                                      N1.getOperand(2).getOperand(1),
7453                                      N0));
7454     }
7455
7456     if (UnsafeFPMath && LookThroughFPExt) {
7457       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7458       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7459       auto FoldFAddFMAFPExtFMul = [&] (
7460           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7461         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7462                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7463                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7464                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7465                                        Z));
7466       };
7467       if (N0.getOpcode() == PreferredFusedOpcode) {
7468         SDValue N02 = N0.getOperand(2);
7469         if (N02.getOpcode() == ISD::FP_EXTEND) {
7470           SDValue N020 = N02.getOperand(0);
7471           if (N020.getOpcode() == ISD::FMUL)
7472             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7473                                         N020.getOperand(0), N020.getOperand(1),
7474                                         N1);
7475         }
7476       }
7477
7478       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7479       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7480       // FIXME: This turns two single-precision and one double-precision
7481       // operation into two double-precision operations, which might not be
7482       // interesting for all targets, especially GPUs.
7483       auto FoldFAddFPExtFMAFMul = [&] (
7484           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7485         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7486                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7487                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7488                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7489                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7490                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7491                                        Z));
7492       };
7493       if (N0.getOpcode() == ISD::FP_EXTEND) {
7494         SDValue N00 = N0.getOperand(0);
7495         if (N00.getOpcode() == PreferredFusedOpcode) {
7496           SDValue N002 = N00.getOperand(2);
7497           if (N002.getOpcode() == ISD::FMUL)
7498             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7499                                         N002.getOperand(0), N002.getOperand(1),
7500                                         N1);
7501         }
7502       }
7503
7504       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7505       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7506       if (N1.getOpcode() == PreferredFusedOpcode) {
7507         SDValue N12 = N1.getOperand(2);
7508         if (N12.getOpcode() == ISD::FP_EXTEND) {
7509           SDValue N120 = N12.getOperand(0);
7510           if (N120.getOpcode() == ISD::FMUL)
7511             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7512                                         N120.getOperand(0), N120.getOperand(1),
7513                                         N0);
7514         }
7515       }
7516
7517       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7518       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7519       // FIXME: This turns two single-precision and one double-precision
7520       // operation into two double-precision operations, which might not be
7521       // interesting for all targets, especially GPUs.
7522       if (N1.getOpcode() == ISD::FP_EXTEND) {
7523         SDValue N10 = N1.getOperand(0);
7524         if (N10.getOpcode() == PreferredFusedOpcode) {
7525           SDValue N102 = N10.getOperand(2);
7526           if (N102.getOpcode() == ISD::FMUL)
7527             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7528                                         N102.getOperand(0), N102.getOperand(1),
7529                                         N0);
7530         }
7531       }
7532     }
7533   }
7534
7535   return SDValue();
7536 }
7537
7538 /// Try to perform FMA combining on a given FSUB node.
7539 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7540   SDValue N0 = N->getOperand(0);
7541   SDValue N1 = N->getOperand(1);
7542   EVT VT = N->getValueType(0);
7543   SDLoc SL(N);
7544
7545   const TargetOptions &Options = DAG.getTarget().Options;
7546   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7547                        Options.UnsafeFPMath);
7548
7549   // Floating-point multiply-add with intermediate rounding.
7550   bool HasFMAD = (LegalOperations &&
7551                   TLI.isOperationLegal(ISD::FMAD, VT));
7552
7553   // Floating-point multiply-add without intermediate rounding.
7554   bool HasFMA = ((!LegalOperations ||
7555                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7556                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7557                  UnsafeFPMath);
7558
7559   // No valid opcode, do not combine.
7560   if (!HasFMAD && !HasFMA)
7561     return SDValue();
7562
7563   // Always prefer FMAD to FMA for precision.
7564   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7565   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7566   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7567
7568   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7569   if (N0.getOpcode() == ISD::FMUL &&
7570       (Aggressive || N0->hasOneUse())) {
7571     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7572                        N0.getOperand(0), N0.getOperand(1),
7573                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7574   }
7575
7576   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7577   // Note: Commutes FSUB operands.
7578   if (N1.getOpcode() == ISD::FMUL &&
7579       (Aggressive || N1->hasOneUse()))
7580     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7581                        DAG.getNode(ISD::FNEG, SL, VT,
7582                                    N1.getOperand(0)),
7583                        N1.getOperand(1), N0);
7584
7585   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7586   if (N0.getOpcode() == ISD::FNEG &&
7587       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7588       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7589     SDValue N00 = N0.getOperand(0).getOperand(0);
7590     SDValue N01 = N0.getOperand(0).getOperand(1);
7591     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7593                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7594   }
7595
7596   // Look through FP_EXTEND nodes to do more combining.
7597   if (UnsafeFPMath && LookThroughFPExt) {
7598     // fold (fsub (fpext (fmul x, y)), z)
7599     //   -> (fma (fpext x), (fpext y), (fneg z))
7600     if (N0.getOpcode() == ISD::FP_EXTEND) {
7601       SDValue N00 = N0.getOperand(0);
7602       if (N00.getOpcode() == ISD::FMUL)
7603         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7604                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7605                                        N00.getOperand(0)),
7606                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7607                                        N00.getOperand(1)),
7608                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7609     }
7610
7611     // fold (fsub x, (fpext (fmul y, z)))
7612     //   -> (fma (fneg (fpext y)), (fpext z), x)
7613     // Note: Commutes FSUB operands.
7614     if (N1.getOpcode() == ISD::FP_EXTEND) {
7615       SDValue N10 = N1.getOperand(0);
7616       if (N10.getOpcode() == ISD::FMUL)
7617         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7618                            DAG.getNode(ISD::FNEG, SL, VT,
7619                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7620                                                    N10.getOperand(0))),
7621                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7622                                        N10.getOperand(1)),
7623                            N0);
7624     }
7625
7626     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7627     //   -> (fneg (fma (fpext x), (fpext y), z))
7628     // Note: This could be removed with appropriate canonicalization of the
7629     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7630     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7631     // from implementing the canonicalization in visitFSUB.
7632     if (N0.getOpcode() == ISD::FP_EXTEND) {
7633       SDValue N00 = N0.getOperand(0);
7634       if (N00.getOpcode() == ISD::FNEG) {
7635         SDValue N000 = N00.getOperand(0);
7636         if (N000.getOpcode() == ISD::FMUL) {
7637           return DAG.getNode(ISD::FNEG, SL, VT,
7638                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7639                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640                                                      N000.getOperand(0)),
7641                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642                                                      N000.getOperand(1)),
7643                                          N1));
7644         }
7645       }
7646     }
7647
7648     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7649     //   -> (fneg (fma (fpext x)), (fpext y), z)
7650     // Note: This could be removed with appropriate canonicalization of the
7651     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7652     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7653     // from implementing the canonicalization in visitFSUB.
7654     if (N0.getOpcode() == ISD::FNEG) {
7655       SDValue N00 = N0.getOperand(0);
7656       if (N00.getOpcode() == ISD::FP_EXTEND) {
7657         SDValue N000 = N00.getOperand(0);
7658         if (N000.getOpcode() == ISD::FMUL) {
7659           return DAG.getNode(ISD::FNEG, SL, VT,
7660                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7661                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7662                                                      N000.getOperand(0)),
7663                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7664                                                      N000.getOperand(1)),
7665                                          N1));
7666         }
7667       }
7668     }
7669
7670   }
7671
7672   // More folding opportunities when target permits.
7673   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7674     // fold (fsub (fma x, y, (fmul u, v)), z)
7675     //   -> (fma x, y (fma u, v, (fneg z)))
7676     if (N0.getOpcode() == PreferredFusedOpcode &&
7677         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7678       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7679                          N0.getOperand(0), N0.getOperand(1),
7680                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7681                                      N0.getOperand(2).getOperand(0),
7682                                      N0.getOperand(2).getOperand(1),
7683                                      DAG.getNode(ISD::FNEG, SL, VT,
7684                                                  N1)));
7685     }
7686
7687     // fold (fsub x, (fma y, z, (fmul u, v)))
7688     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7689     if (N1.getOpcode() == PreferredFusedOpcode &&
7690         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7691       SDValue N20 = N1.getOperand(2).getOperand(0);
7692       SDValue N21 = N1.getOperand(2).getOperand(1);
7693       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7694                          DAG.getNode(ISD::FNEG, SL, VT,
7695                                      N1.getOperand(0)),
7696                          N1.getOperand(1),
7697                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7698                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7699
7700                                      N21, N0));
7701     }
7702
7703     if (UnsafeFPMath && LookThroughFPExt) {
7704       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7705       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7706       if (N0.getOpcode() == PreferredFusedOpcode) {
7707         SDValue N02 = N0.getOperand(2);
7708         if (N02.getOpcode() == ISD::FP_EXTEND) {
7709           SDValue N020 = N02.getOperand(0);
7710           if (N020.getOpcode() == ISD::FMUL)
7711             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7712                                N0.getOperand(0), N0.getOperand(1),
7713                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7714                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7715                                                        N020.getOperand(0)),
7716                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7717                                                        N020.getOperand(1)),
7718                                            DAG.getNode(ISD::FNEG, SL, VT,
7719                                                        N1)));
7720         }
7721       }
7722
7723       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7724       //   -> (fma (fpext x), (fpext y),
7725       //           (fma (fpext u), (fpext v), (fneg z)))
7726       // FIXME: This turns two single-precision and one double-precision
7727       // operation into two double-precision operations, which might not be
7728       // interesting for all targets, especially GPUs.
7729       if (N0.getOpcode() == ISD::FP_EXTEND) {
7730         SDValue N00 = N0.getOperand(0);
7731         if (N00.getOpcode() == PreferredFusedOpcode) {
7732           SDValue N002 = N00.getOperand(2);
7733           if (N002.getOpcode() == ISD::FMUL)
7734             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7735                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7736                                            N00.getOperand(0)),
7737                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7738                                            N00.getOperand(1)),
7739                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7741                                                        N002.getOperand(0)),
7742                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743                                                        N002.getOperand(1)),
7744                                            DAG.getNode(ISD::FNEG, SL, VT,
7745                                                        N1)));
7746         }
7747       }
7748
7749       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7750       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7751       if (N1.getOpcode() == PreferredFusedOpcode &&
7752         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7753         SDValue N120 = N1.getOperand(2).getOperand(0);
7754         if (N120.getOpcode() == ISD::FMUL) {
7755           SDValue N1200 = N120.getOperand(0);
7756           SDValue N1201 = N120.getOperand(1);
7757           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7758                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7759                              N1.getOperand(1),
7760                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7761                                          DAG.getNode(ISD::FNEG, SL, VT,
7762                                              DAG.getNode(ISD::FP_EXTEND, SL,
7763                                                          VT, N1200)),
7764                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                                      N1201),
7766                                          N0));
7767         }
7768       }
7769
7770       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7771       //   -> (fma (fneg (fpext y)), (fpext z),
7772       //           (fma (fneg (fpext u)), (fpext v), x))
7773       // FIXME: This turns two single-precision and one double-precision
7774       // operation into two double-precision operations, which might not be
7775       // interesting for all targets, especially GPUs.
7776       if (N1.getOpcode() == ISD::FP_EXTEND &&
7777         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7778         SDValue N100 = N1.getOperand(0).getOperand(0);
7779         SDValue N101 = N1.getOperand(0).getOperand(1);
7780         SDValue N102 = N1.getOperand(0).getOperand(2);
7781         if (N102.getOpcode() == ISD::FMUL) {
7782           SDValue N1020 = N102.getOperand(0);
7783           SDValue N1021 = N102.getOperand(1);
7784           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7785                              DAG.getNode(ISD::FNEG, SL, VT,
7786                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787                                                      N100)),
7788                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7789                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7790                                          DAG.getNode(ISD::FNEG, SL, VT,
7791                                              DAG.getNode(ISD::FP_EXTEND, SL,
7792                                                          VT, N1020)),
7793                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7794                                                      N1021),
7795                                          N0));
7796         }
7797       }
7798     }
7799   }
7800
7801   return SDValue();
7802 }
7803
7804 SDValue DAGCombiner::visitFADD(SDNode *N) {
7805   SDValue N0 = N->getOperand(0);
7806   SDValue N1 = N->getOperand(1);
7807   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7808   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7809   EVT VT = N->getValueType(0);
7810   SDLoc DL(N);
7811   const TargetOptions &Options = DAG.getTarget().Options;
7812
7813   // fold vector ops
7814   if (VT.isVector())
7815     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7816       return FoldedVOp;
7817
7818   // fold (fadd c1, c2) -> c1 + c2
7819   if (N0CFP && N1CFP)
7820     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7821
7822   // canonicalize constant to RHS
7823   if (N0CFP && !N1CFP)
7824     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7825
7826   // fold (fadd A, (fneg B)) -> (fsub A, B)
7827   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7828       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7829     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7830                        GetNegatedExpression(N1, DAG, LegalOperations));
7831
7832   // fold (fadd (fneg A), B) -> (fsub B, A)
7833   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7834       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7835     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7836                        GetNegatedExpression(N0, DAG, LegalOperations));
7837
7838   // If 'unsafe math' is enabled, fold lots of things.
7839   if (Options.UnsafeFPMath) {
7840     // No FP constant should be created after legalization as Instruction
7841     // Selection pass has a hard time dealing with FP constants.
7842     bool AllowNewConst = (Level < AfterLegalizeDAG);
7843
7844     // fold (fadd A, 0) -> A
7845     if (N1CFP && N1CFP->getValueAPF().isZero())
7846       return N0;
7847
7848     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7849     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7850         isa<ConstantFPSDNode>(N0.getOperand(1)))
7851       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7852                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7853
7854     // If allowed, fold (fadd (fneg x), x) -> 0.0
7855     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7856       return DAG.getConstantFP(0.0, DL, VT);
7857
7858     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7859     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7860       return DAG.getConstantFP(0.0, DL, VT);
7861
7862     // We can fold chains of FADD's of the same value into multiplications.
7863     // This transform is not safe in general because we are reducing the number
7864     // of rounding steps.
7865     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7866       if (N0.getOpcode() == ISD::FMUL) {
7867         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7868         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7869
7870         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7871         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7872           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7873                                        DAG.getConstantFP(1.0, DL, VT));
7874           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7875         }
7876
7877         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7878         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7879             N1.getOperand(0) == N1.getOperand(1) &&
7880             N0.getOperand(0) == N1.getOperand(0)) {
7881           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7882                                        DAG.getConstantFP(2.0, DL, VT));
7883           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7884         }
7885       }
7886
7887       if (N1.getOpcode() == ISD::FMUL) {
7888         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7889         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7890
7891         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7892         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7893           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7894                                        DAG.getConstantFP(1.0, DL, VT));
7895           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7896         }
7897
7898         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7899         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7900             N0.getOperand(0) == N0.getOperand(1) &&
7901             N1.getOperand(0) == N0.getOperand(0)) {
7902           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7903                                        DAG.getConstantFP(2.0, DL, VT));
7904           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7905         }
7906       }
7907
7908       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7909         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7910         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7911         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7912             (N0.getOperand(0) == N1)) {
7913           return DAG.getNode(ISD::FMUL, DL, VT,
7914                              N1, DAG.getConstantFP(3.0, DL, VT));
7915         }
7916       }
7917
7918       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7919         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7920         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7921         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7922             N1.getOperand(0) == N0) {
7923           return DAG.getNode(ISD::FMUL, DL, VT,
7924                              N0, DAG.getConstantFP(3.0, DL, VT));
7925         }
7926       }
7927
7928       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7929       if (AllowNewConst &&
7930           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7931           N0.getOperand(0) == N0.getOperand(1) &&
7932           N1.getOperand(0) == N1.getOperand(1) &&
7933           N0.getOperand(0) == N1.getOperand(0)) {
7934         return DAG.getNode(ISD::FMUL, DL, VT,
7935                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7936       }
7937     }
7938   } // enable-unsafe-fp-math
7939
7940   // FADD -> FMA combines:
7941   SDValue Fused = visitFADDForFMACombine(N);
7942   if (Fused) {
7943     AddToWorklist(Fused.getNode());
7944     return Fused;
7945   }
7946
7947   return SDValue();
7948 }
7949
7950 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7951   SDValue N0 = N->getOperand(0);
7952   SDValue N1 = N->getOperand(1);
7953   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7954   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7955   EVT VT = N->getValueType(0);
7956   SDLoc dl(N);
7957   const TargetOptions &Options = DAG.getTarget().Options;
7958
7959   // fold vector ops
7960   if (VT.isVector())
7961     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7962       return FoldedVOp;
7963
7964   // fold (fsub c1, c2) -> c1-c2
7965   if (N0CFP && N1CFP)
7966     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7967
7968   // fold (fsub A, (fneg B)) -> (fadd A, B)
7969   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7970     return DAG.getNode(ISD::FADD, dl, VT, N0,
7971                        GetNegatedExpression(N1, DAG, LegalOperations));
7972
7973   // If 'unsafe math' is enabled, fold lots of things.
7974   if (Options.UnsafeFPMath) {
7975     // (fsub A, 0) -> A
7976     if (N1CFP && N1CFP->getValueAPF().isZero())
7977       return N0;
7978
7979     // (fsub 0, B) -> -B
7980     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7981       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7982         return GetNegatedExpression(N1, DAG, LegalOperations);
7983       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7984         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7985     }
7986
7987     // (fsub x, x) -> 0.0
7988     if (N0 == N1)
7989       return DAG.getConstantFP(0.0f, dl, VT);
7990
7991     // (fsub x, (fadd x, y)) -> (fneg y)
7992     // (fsub x, (fadd y, x)) -> (fneg y)
7993     if (N1.getOpcode() == ISD::FADD) {
7994       SDValue N10 = N1->getOperand(0);
7995       SDValue N11 = N1->getOperand(1);
7996
7997       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7998         return GetNegatedExpression(N11, DAG, LegalOperations);
7999
8000       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8001         return GetNegatedExpression(N10, DAG, LegalOperations);
8002     }
8003   }
8004
8005   // FSUB -> FMA combines:
8006   SDValue Fused = visitFSUBForFMACombine(N);
8007   if (Fused) {
8008     AddToWorklist(Fused.getNode());
8009     return Fused;
8010   }
8011
8012   return SDValue();
8013 }
8014
8015 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8016   SDValue N0 = N->getOperand(0);
8017   SDValue N1 = N->getOperand(1);
8018   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8019   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8020   EVT VT = N->getValueType(0);
8021   SDLoc DL(N);
8022   const TargetOptions &Options = DAG.getTarget().Options;
8023
8024   // fold vector ops
8025   if (VT.isVector()) {
8026     // This just handles C1 * C2 for vectors. Other vector folds are below.
8027     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8028       return FoldedVOp;
8029   }
8030
8031   // fold (fmul c1, c2) -> c1*c2
8032   if (N0CFP && N1CFP)
8033     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8034
8035   // canonicalize constant to RHS
8036   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8037      !isConstantFPBuildVectorOrConstantFP(N1))
8038     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8039
8040   // fold (fmul A, 1.0) -> A
8041   if (N1CFP && N1CFP->isExactlyValue(1.0))
8042     return N0;
8043
8044   if (Options.UnsafeFPMath) {
8045     // fold (fmul A, 0) -> 0
8046     if (N1CFP && N1CFP->getValueAPF().isZero())
8047       return N1;
8048
8049     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8050     if (N0.getOpcode() == ISD::FMUL) {
8051       // Fold scalars or any vector constants (not just splats).
8052       // This fold is done in general by InstCombine, but extra fmul insts
8053       // may have been generated during lowering.
8054       SDValue N00 = N0.getOperand(0);
8055       SDValue N01 = N0.getOperand(1);
8056       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8057       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8058       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8059       
8060       // Check 1: Make sure that the first operand of the inner multiply is NOT
8061       // a constant. Otherwise, we may induce infinite looping.
8062       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8063         // Check 2: Make sure that the second operand of the inner multiply and
8064         // the second operand of the outer multiply are constants.
8065         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8066             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8067           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8068           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8069         }
8070       }
8071     }
8072
8073     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8074     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8075     // during an early run of DAGCombiner can prevent folding with fmuls
8076     // inserted during lowering.
8077     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8078       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8079       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8080       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8081     }
8082   }
8083
8084   // fold (fmul X, 2.0) -> (fadd X, X)
8085   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8086     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8087
8088   // fold (fmul X, -1.0) -> (fneg X)
8089   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8090     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8091       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8092
8093   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8094   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8095     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8096       // Both can be negated for free, check to see if at least one is cheaper
8097       // negated.
8098       if (LHSNeg == 2 || RHSNeg == 2)
8099         return DAG.getNode(ISD::FMUL, DL, VT,
8100                            GetNegatedExpression(N0, DAG, LegalOperations),
8101                            GetNegatedExpression(N1, DAG, LegalOperations));
8102     }
8103   }
8104
8105   return SDValue();
8106 }
8107
8108 SDValue DAGCombiner::visitFMA(SDNode *N) {
8109   SDValue N0 = N->getOperand(0);
8110   SDValue N1 = N->getOperand(1);
8111   SDValue N2 = N->getOperand(2);
8112   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8113   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8114   EVT VT = N->getValueType(0);
8115   SDLoc dl(N);
8116   const TargetOptions &Options = DAG.getTarget().Options;
8117
8118   // Constant fold FMA.
8119   if (isa<ConstantFPSDNode>(N0) &&
8120       isa<ConstantFPSDNode>(N1) &&
8121       isa<ConstantFPSDNode>(N2)) {
8122     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8123   }
8124
8125   if (Options.UnsafeFPMath) {
8126     if (N0CFP && N0CFP->isZero())
8127       return N2;
8128     if (N1CFP && N1CFP->isZero())
8129       return N2;
8130   }
8131   if (N0CFP && N0CFP->isExactlyValue(1.0))
8132     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8133   if (N1CFP && N1CFP->isExactlyValue(1.0))
8134     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8135
8136   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8137   if (N0CFP && !N1CFP)
8138     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8139
8140   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8141   if (Options.UnsafeFPMath && N1CFP &&
8142       N2.getOpcode() == ISD::FMUL &&
8143       N0 == N2.getOperand(0) &&
8144       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8145     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8146                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8147   }
8148
8149
8150   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8151   if (Options.UnsafeFPMath &&
8152       N0.getOpcode() == ISD::FMUL && N1CFP &&
8153       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8154     return DAG.getNode(ISD::FMA, dl, VT,
8155                        N0.getOperand(0),
8156                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8157                        N2);
8158   }
8159
8160   // (fma x, 1, y) -> (fadd x, y)
8161   // (fma x, -1, y) -> (fadd (fneg x), y)
8162   if (N1CFP) {
8163     if (N1CFP->isExactlyValue(1.0))
8164       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8165
8166     if (N1CFP->isExactlyValue(-1.0) &&
8167         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8168       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8169       AddToWorklist(RHSNeg.getNode());
8170       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8171     }
8172   }
8173
8174   // (fma x, c, x) -> (fmul x, (c+1))
8175   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8176     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8177                        DAG.getNode(ISD::FADD, dl, VT,
8178                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8179
8180   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8181   if (Options.UnsafeFPMath && N1CFP &&
8182       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8183     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8184                        DAG.getNode(ISD::FADD, dl, VT,
8185                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8186
8187
8188   return SDValue();
8189 }
8190
8191 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8192   SDValue N0 = N->getOperand(0);
8193   SDValue N1 = N->getOperand(1);
8194   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8195   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8196   EVT VT = N->getValueType(0);
8197   SDLoc DL(N);
8198   const TargetOptions &Options = DAG.getTarget().Options;
8199
8200   // fold vector ops
8201   if (VT.isVector())
8202     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8203       return FoldedVOp;
8204
8205   // fold (fdiv c1, c2) -> c1/c2
8206   if (N0CFP && N1CFP)
8207     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8208
8209   if (Options.UnsafeFPMath) {
8210     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8211     if (N1CFP) {
8212       // Compute the reciprocal 1.0 / c2.
8213       APFloat N1APF = N1CFP->getValueAPF();
8214       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8215       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8216       // Only do the transform if the reciprocal is a legal fp immediate that
8217       // isn't too nasty (eg NaN, denormal, ...).
8218       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8219           (!LegalOperations ||
8220            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8221            // backend)... we should handle this gracefully after Legalize.
8222            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8223            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8224            TLI.isFPImmLegal(Recip, VT)))
8225         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8226                            DAG.getConstantFP(Recip, DL, VT));
8227     }
8228
8229     // If this FDIV is part of a reciprocal square root, it may be folded
8230     // into a target-specific square root estimate instruction.
8231     if (N1.getOpcode() == ISD::FSQRT) {
8232       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8233         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8234       }
8235     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8236                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8237       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8238         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8239         AddToWorklist(RV.getNode());
8240         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8241       }
8242     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8243                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8244       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8245         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8246         AddToWorklist(RV.getNode());
8247         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8248       }
8249     } else if (N1.getOpcode() == ISD::FMUL) {
8250       // Look through an FMUL. Even though this won't remove the FDIV directly,
8251       // it's still worthwhile to get rid of the FSQRT if possible.
8252       SDValue SqrtOp;
8253       SDValue OtherOp;
8254       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8255         SqrtOp = N1.getOperand(0);
8256         OtherOp = N1.getOperand(1);
8257       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8258         SqrtOp = N1.getOperand(1);
8259         OtherOp = N1.getOperand(0);
8260       }
8261       if (SqrtOp.getNode()) {
8262         // We found a FSQRT, so try to make this fold:
8263         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8264         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8265           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8266           AddToWorklist(RV.getNode());
8267           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8268         }
8269       }
8270     }
8271
8272     // Fold into a reciprocal estimate and multiply instead of a real divide.
8273     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8274       AddToWorklist(RV.getNode());
8275       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8276     }
8277   }
8278
8279   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8280   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8281     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8282       // Both can be negated for free, check to see if at least one is cheaper
8283       // negated.
8284       if (LHSNeg == 2 || RHSNeg == 2)
8285         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8286                            GetNegatedExpression(N0, DAG, LegalOperations),
8287                            GetNegatedExpression(N1, DAG, LegalOperations));
8288     }
8289   }
8290
8291   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8292   // reciprocal.
8293   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8294   // Notice that this is not always beneficial. One reason is different target
8295   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8296   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8297   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8298   if (Options.UnsafeFPMath) {
8299     // Skip if current node is a reciprocal.
8300     if (N0CFP && N0CFP->isExactlyValue(1.0))
8301       return SDValue();
8302
8303     SmallVector<SDNode *, 4> Users;
8304     // Find all FDIV users of the same divisor.
8305     for (auto *U : N1->uses()) {
8306       if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8307         Users.push_back(U);
8308     }
8309
8310     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8311       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8312       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8313
8314       // Dividend / Divisor -> Dividend * Reciprocal
8315       for (auto *U : Users) {
8316         SDValue Dividend = U->getOperand(0);
8317         if (Dividend != FPOne) {
8318           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8319                                         Reciprocal);
8320           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8321         }
8322       }
8323       return SDValue();
8324     }
8325   }
8326
8327   return SDValue();
8328 }
8329
8330 SDValue DAGCombiner::visitFREM(SDNode *N) {
8331   SDValue N0 = N->getOperand(0);
8332   SDValue N1 = N->getOperand(1);
8333   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8334   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8335   EVT VT = N->getValueType(0);
8336
8337   // fold (frem c1, c2) -> fmod(c1,c2)
8338   if (N0CFP && N1CFP)
8339     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8340
8341   return SDValue();
8342 }
8343
8344 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8345   if (DAG.getTarget().Options.UnsafeFPMath &&
8346       !TLI.isFsqrtCheap()) {
8347     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8348     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8349       EVT VT = RV.getValueType();
8350       SDLoc DL(N);
8351       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8352       AddToWorklist(RV.getNode());
8353
8354       // Unfortunately, RV is now NaN if the input was exactly 0.
8355       // Select out this case and force the answer to 0.
8356       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8357       SDValue ZeroCmp =
8358         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8359                      N->getOperand(0), Zero, ISD::SETEQ);
8360       AddToWorklist(ZeroCmp.getNode());
8361       AddToWorklist(RV.getNode());
8362
8363       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8364                        DL, VT, ZeroCmp, Zero, RV);
8365       return RV;
8366     }
8367   }
8368   return SDValue();
8369 }
8370
8371 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8372   SDValue N0 = N->getOperand(0);
8373   SDValue N1 = N->getOperand(1);
8374   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8375   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8376   EVT VT = N->getValueType(0);
8377
8378   if (N0CFP && N1CFP)  // Constant fold
8379     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8380
8381   if (N1CFP) {
8382     const APFloat& V = N1CFP->getValueAPF();
8383     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8384     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8385     if (!V.isNegative()) {
8386       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8387         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8388     } else {
8389       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8390         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8391                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8392     }
8393   }
8394
8395   // copysign(fabs(x), y) -> copysign(x, y)
8396   // copysign(fneg(x), y) -> copysign(x, y)
8397   // copysign(copysign(x,z), y) -> copysign(x, y)
8398   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8399       N0.getOpcode() == ISD::FCOPYSIGN)
8400     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8401                        N0.getOperand(0), N1);
8402
8403   // copysign(x, abs(y)) -> abs(x)
8404   if (N1.getOpcode() == ISD::FABS)
8405     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8406
8407   // copysign(x, copysign(y,z)) -> copysign(x, z)
8408   if (N1.getOpcode() == ISD::FCOPYSIGN)
8409     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8410                        N0, N1.getOperand(1));
8411
8412   // copysign(x, fp_extend(y)) -> copysign(x, y)
8413   // copysign(x, fp_round(y)) -> copysign(x, y)
8414   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8415     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8416                        N0, N1.getOperand(0));
8417
8418   return SDValue();
8419 }
8420
8421 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8422   SDValue N0 = N->getOperand(0);
8423   EVT VT = N->getValueType(0);
8424   EVT OpVT = N0.getValueType();
8425
8426   // fold (sint_to_fp c1) -> c1fp
8427   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8428       // ...but only if the target supports immediate floating-point values
8429       (!LegalOperations ||
8430        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8431     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8432
8433   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8434   // but UINT_TO_FP is legal on this target, try to convert.
8435   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8436       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8437     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8438     if (DAG.SignBitIsZero(N0))
8439       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8440   }
8441
8442   // The next optimizations are desirable only if SELECT_CC can be lowered.
8443   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8444     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8445     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8446         !VT.isVector() &&
8447         (!LegalOperations ||
8448          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8449       SDLoc DL(N);
8450       SDValue Ops[] =
8451         { N0.getOperand(0), N0.getOperand(1),
8452           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8453           N0.getOperand(2) };
8454       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8455     }
8456
8457     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8458     //      (select_cc x, y, 1.0, 0.0,, cc)
8459     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8460         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8461         (!LegalOperations ||
8462          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8463       SDLoc DL(N);
8464       SDValue Ops[] =
8465         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8466           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8467           N0.getOperand(0).getOperand(2) };
8468       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8469     }
8470   }
8471
8472   return SDValue();
8473 }
8474
8475 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8476   SDValue N0 = N->getOperand(0);
8477   EVT VT = N->getValueType(0);
8478   EVT OpVT = N0.getValueType();
8479
8480   // fold (uint_to_fp c1) -> c1fp
8481   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8482       // ...but only if the target supports immediate floating-point values
8483       (!LegalOperations ||
8484        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8485     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8486
8487   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8488   // but SINT_TO_FP is legal on this target, try to convert.
8489   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8490       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8491     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8492     if (DAG.SignBitIsZero(N0))
8493       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8494   }
8495
8496   // The next optimizations are desirable only if SELECT_CC can be lowered.
8497   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8498     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8499
8500     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8501         (!LegalOperations ||
8502          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8503       SDLoc DL(N);
8504       SDValue Ops[] =
8505         { N0.getOperand(0), N0.getOperand(1),
8506           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8507           N0.getOperand(2) };
8508       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8509     }
8510   }
8511
8512   return SDValue();
8513 }
8514
8515 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8516 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8517   SDValue N0 = N->getOperand(0);
8518   EVT VT = N->getValueType(0);
8519
8520   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8521     return SDValue();
8522
8523   SDValue Src = N0.getOperand(0);
8524   EVT SrcVT = Src.getValueType();
8525   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8526   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8527
8528   // We can safely assume the conversion won't overflow the output range,
8529   // because (for example) (uint8_t)18293.f is undefined behavior.
8530
8531   // Since we can assume the conversion won't overflow, our decision as to
8532   // whether the input will fit in the float should depend on the minimum
8533   // of the input range and output range.
8534
8535   // This means this is also safe for a signed input and unsigned output, since
8536   // a negative input would lead to undefined behavior.
8537   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8538   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8539   unsigned ActualSize = std::min(InputSize, OutputSize);
8540   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8541
8542   // We can only fold away the float conversion if the input range can be
8543   // represented exactly in the float range.
8544   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8545     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8546       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8547                                                        : ISD::ZERO_EXTEND;
8548       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8549     }
8550     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8551       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8552     if (SrcVT == VT)
8553       return Src;
8554     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8555   }
8556   return SDValue();
8557 }
8558
8559 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8560   SDValue N0 = N->getOperand(0);
8561   EVT VT = N->getValueType(0);
8562
8563   // fold (fp_to_sint c1fp) -> c1
8564   if (isConstantFPBuildVectorOrConstantFP(N0))
8565     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8566
8567   return FoldIntToFPToInt(N, DAG);
8568 }
8569
8570 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8571   SDValue N0 = N->getOperand(0);
8572   EVT VT = N->getValueType(0);
8573
8574   // fold (fp_to_uint c1fp) -> c1
8575   if (isConstantFPBuildVectorOrConstantFP(N0))
8576     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8577
8578   return FoldIntToFPToInt(N, DAG);
8579 }
8580
8581 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8582   SDValue N0 = N->getOperand(0);
8583   SDValue N1 = N->getOperand(1);
8584   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8585   EVT VT = N->getValueType(0);
8586
8587   // fold (fp_round c1fp) -> c1fp
8588   if (N0CFP)
8589     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8590
8591   // fold (fp_round (fp_extend x)) -> x
8592   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8593     return N0.getOperand(0);
8594
8595   // fold (fp_round (fp_round x)) -> (fp_round x)
8596   if (N0.getOpcode() == ISD::FP_ROUND) {
8597     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8598     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8599     // If the first fp_round isn't a value preserving truncation, it might
8600     // introduce a tie in the second fp_round, that wouldn't occur in the
8601     // single-step fp_round we want to fold to.
8602     // In other words, double rounding isn't the same as rounding.
8603     // Also, this is a value preserving truncation iff both fp_round's are.
8604     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8605       SDLoc DL(N);
8606       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8607                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8608     }
8609   }
8610
8611   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8612   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8613     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8614                               N0.getOperand(0), N1);
8615     AddToWorklist(Tmp.getNode());
8616     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8617                        Tmp, N0.getOperand(1));
8618   }
8619
8620   return SDValue();
8621 }
8622
8623 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8624   SDValue N0 = N->getOperand(0);
8625   EVT VT = N->getValueType(0);
8626   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8627   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8628
8629   // fold (fp_round_inreg c1fp) -> c1fp
8630   if (N0CFP && isTypeLegal(EVT)) {
8631     SDLoc DL(N);
8632     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8633     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8634   }
8635
8636   return SDValue();
8637 }
8638
8639 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8640   SDValue N0 = N->getOperand(0);
8641   EVT VT = N->getValueType(0);
8642
8643   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8644   if (N->hasOneUse() &&
8645       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8646     return SDValue();
8647
8648   // fold (fp_extend c1fp) -> c1fp
8649   if (isConstantFPBuildVectorOrConstantFP(N0))
8650     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8651
8652   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8653   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8654       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8655     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8656
8657   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8658   // value of X.
8659   if (N0.getOpcode() == ISD::FP_ROUND
8660       && N0.getNode()->getConstantOperandVal(1) == 1) {
8661     SDValue In = N0.getOperand(0);
8662     if (In.getValueType() == VT) return In;
8663     if (VT.bitsLT(In.getValueType()))
8664       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8665                          In, N0.getOperand(1));
8666     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8667   }
8668
8669   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8670   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8671        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8672     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8673     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8674                                      LN0->getChain(),
8675                                      LN0->getBasePtr(), N0.getValueType(),
8676                                      LN0->getMemOperand());
8677     CombineTo(N, ExtLoad);
8678     CombineTo(N0.getNode(),
8679               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8680                           N0.getValueType(), ExtLoad,
8681                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8682               ExtLoad.getValue(1));
8683     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8684   }
8685
8686   return SDValue();
8687 }
8688
8689 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8690   SDValue N0 = N->getOperand(0);
8691   EVT VT = N->getValueType(0);
8692
8693   // fold (fceil c1) -> fceil(c1)
8694   if (isConstantFPBuildVectorOrConstantFP(N0))
8695     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8696
8697   return SDValue();
8698 }
8699
8700 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8701   SDValue N0 = N->getOperand(0);
8702   EVT VT = N->getValueType(0);
8703
8704   // fold (ftrunc c1) -> ftrunc(c1)
8705   if (isConstantFPBuildVectorOrConstantFP(N0))
8706     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8707
8708   return SDValue();
8709 }
8710
8711 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8712   SDValue N0 = N->getOperand(0);
8713   EVT VT = N->getValueType(0);
8714
8715   // fold (ffloor c1) -> ffloor(c1)
8716   if (isConstantFPBuildVectorOrConstantFP(N0))
8717     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8718
8719   return SDValue();
8720 }
8721
8722 // FIXME: FNEG and FABS have a lot in common; refactor.
8723 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8724   SDValue N0 = N->getOperand(0);
8725   EVT VT = N->getValueType(0);
8726
8727   // Constant fold FNEG.
8728   if (isConstantFPBuildVectorOrConstantFP(N0))
8729     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8730
8731   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8732                          &DAG.getTarget().Options))
8733     return GetNegatedExpression(N0, DAG, LegalOperations);
8734
8735   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8736   // constant pool values.
8737   if (!TLI.isFNegFree(VT) &&
8738       N0.getOpcode() == ISD::BITCAST &&
8739       N0.getNode()->hasOneUse()) {
8740     SDValue Int = N0.getOperand(0);
8741     EVT IntVT = Int.getValueType();
8742     if (IntVT.isInteger() && !IntVT.isVector()) {
8743       APInt SignMask;
8744       if (N0.getValueType().isVector()) {
8745         // For a vector, get a mask such as 0x80... per scalar element
8746         // and splat it.
8747         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8748         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8749       } else {
8750         // For a scalar, just generate 0x80...
8751         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8752       }
8753       SDLoc DL0(N0);
8754       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8755                         DAG.getConstant(SignMask, DL0, IntVT));
8756       AddToWorklist(Int.getNode());
8757       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8758     }
8759   }
8760
8761   // (fneg (fmul c, x)) -> (fmul -c, x)
8762   if (N0.getOpcode() == ISD::FMUL) {
8763     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8764     if (CFP1) {
8765       APFloat CVal = CFP1->getValueAPF();
8766       CVal.changeSign();
8767       if (Level >= AfterLegalizeDAG &&
8768           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8769            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8770         return DAG.getNode(
8771             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8772             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8773     }
8774   }
8775
8776   return SDValue();
8777 }
8778
8779 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8780   SDValue N0 = N->getOperand(0);
8781   SDValue N1 = N->getOperand(1);
8782   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8783   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8784
8785   if (N0CFP && N1CFP) {
8786     const APFloat &C0 = N0CFP->getValueAPF();
8787     const APFloat &C1 = N1CFP->getValueAPF();
8788     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8789   }
8790
8791   if (N0CFP) {
8792     EVT VT = N->getValueType(0);
8793     // Canonicalize to constant on RHS.
8794     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8795   }
8796
8797   return SDValue();
8798 }
8799
8800 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8801   SDValue N0 = N->getOperand(0);
8802   SDValue N1 = N->getOperand(1);
8803   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8804   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8805
8806   if (N0CFP && N1CFP) {
8807     const APFloat &C0 = N0CFP->getValueAPF();
8808     const APFloat &C1 = N1CFP->getValueAPF();
8809     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8810   }
8811
8812   if (N0CFP) {
8813     EVT VT = N->getValueType(0);
8814     // Canonicalize to constant on RHS.
8815     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8816   }
8817
8818   return SDValue();
8819 }
8820
8821 SDValue DAGCombiner::visitFABS(SDNode *N) {
8822   SDValue N0 = N->getOperand(0);
8823   EVT VT = N->getValueType(0);
8824
8825   // fold (fabs c1) -> fabs(c1)
8826   if (isConstantFPBuildVectorOrConstantFP(N0))
8827     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8828
8829   // fold (fabs (fabs x)) -> (fabs x)
8830   if (N0.getOpcode() == ISD::FABS)
8831     return N->getOperand(0);
8832
8833   // fold (fabs (fneg x)) -> (fabs x)
8834   // fold (fabs (fcopysign x, y)) -> (fabs x)
8835   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8836     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8837
8838   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8839   // constant pool values.
8840   if (!TLI.isFAbsFree(VT) &&
8841       N0.getOpcode() == ISD::BITCAST &&
8842       N0.getNode()->hasOneUse()) {
8843     SDValue Int = N0.getOperand(0);
8844     EVT IntVT = Int.getValueType();
8845     if (IntVT.isInteger() && !IntVT.isVector()) {
8846       APInt SignMask;
8847       if (N0.getValueType().isVector()) {
8848         // For a vector, get a mask such as 0x7f... per scalar element
8849         // and splat it.
8850         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8851         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8852       } else {
8853         // For a scalar, just generate 0x7f...
8854         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8855       }
8856       SDLoc DL(N0);
8857       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8858                         DAG.getConstant(SignMask, DL, IntVT));
8859       AddToWorklist(Int.getNode());
8860       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8861     }
8862   }
8863
8864   return SDValue();
8865 }
8866
8867 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8868   SDValue Chain = N->getOperand(0);
8869   SDValue N1 = N->getOperand(1);
8870   SDValue N2 = N->getOperand(2);
8871
8872   // If N is a constant we could fold this into a fallthrough or unconditional
8873   // branch. However that doesn't happen very often in normal code, because
8874   // Instcombine/SimplifyCFG should have handled the available opportunities.
8875   // If we did this folding here, it would be necessary to update the
8876   // MachineBasicBlock CFG, which is awkward.
8877
8878   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8879   // on the target.
8880   if (N1.getOpcode() == ISD::SETCC &&
8881       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8882                                    N1.getOperand(0).getValueType())) {
8883     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8884                        Chain, N1.getOperand(2),
8885                        N1.getOperand(0), N1.getOperand(1), N2);
8886   }
8887
8888   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8889       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8890        (N1.getOperand(0).hasOneUse() &&
8891         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8892     SDNode *Trunc = nullptr;
8893     if (N1.getOpcode() == ISD::TRUNCATE) {
8894       // Look pass the truncate.
8895       Trunc = N1.getNode();
8896       N1 = N1.getOperand(0);
8897     }
8898
8899     // Match this pattern so that we can generate simpler code:
8900     //
8901     //   %a = ...
8902     //   %b = and i32 %a, 2
8903     //   %c = srl i32 %b, 1
8904     //   brcond i32 %c ...
8905     //
8906     // into
8907     //
8908     //   %a = ...
8909     //   %b = and i32 %a, 2
8910     //   %c = setcc eq %b, 0
8911     //   brcond %c ...
8912     //
8913     // This applies only when the AND constant value has one bit set and the
8914     // SRL constant is equal to the log2 of the AND constant. The back-end is
8915     // smart enough to convert the result into a TEST/JMP sequence.
8916     SDValue Op0 = N1.getOperand(0);
8917     SDValue Op1 = N1.getOperand(1);
8918
8919     if (Op0.getOpcode() == ISD::AND &&
8920         Op1.getOpcode() == ISD::Constant) {
8921       SDValue AndOp1 = Op0.getOperand(1);
8922
8923       if (AndOp1.getOpcode() == ISD::Constant) {
8924         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8925
8926         if (AndConst.isPowerOf2() &&
8927             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8928           SDLoc DL(N);
8929           SDValue SetCC =
8930             DAG.getSetCC(DL,
8931                          getSetCCResultType(Op0.getValueType()),
8932                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8933                          ISD::SETNE);
8934
8935           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8936                                           MVT::Other, Chain, SetCC, N2);
8937           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8938           // will convert it back to (X & C1) >> C2.
8939           CombineTo(N, NewBRCond, false);
8940           // Truncate is dead.
8941           if (Trunc)
8942             deleteAndRecombine(Trunc);
8943           // Replace the uses of SRL with SETCC
8944           WorklistRemover DeadNodes(*this);
8945           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8946           deleteAndRecombine(N1.getNode());
8947           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8948         }
8949       }
8950     }
8951
8952     if (Trunc)
8953       // Restore N1 if the above transformation doesn't match.
8954       N1 = N->getOperand(1);
8955   }
8956
8957   // Transform br(xor(x, y)) -> br(x != y)
8958   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8959   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8960     SDNode *TheXor = N1.getNode();
8961     SDValue Op0 = TheXor->getOperand(0);
8962     SDValue Op1 = TheXor->getOperand(1);
8963     if (Op0.getOpcode() == Op1.getOpcode()) {
8964       // Avoid missing important xor optimizations.
8965       SDValue Tmp = visitXOR(TheXor);
8966       if (Tmp.getNode()) {
8967         if (Tmp.getNode() != TheXor) {
8968           DEBUG(dbgs() << "\nReplacing.8 ";
8969                 TheXor->dump(&DAG);
8970                 dbgs() << "\nWith: ";
8971                 Tmp.getNode()->dump(&DAG);
8972                 dbgs() << '\n');
8973           WorklistRemover DeadNodes(*this);
8974           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8975           deleteAndRecombine(TheXor);
8976           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8977                              MVT::Other, Chain, Tmp, N2);
8978         }
8979
8980         // visitXOR has changed XOR's operands or replaced the XOR completely,
8981         // bail out.
8982         return SDValue(N, 0);
8983       }
8984     }
8985
8986     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8987       bool Equal = false;
8988       if (isOneConstant(Op0) && Op0.hasOneUse() &&
8989           Op0.getOpcode() == ISD::XOR) {
8990         TheXor = Op0.getNode();
8991         Equal = true;
8992       }
8993
8994       EVT SetCCVT = N1.getValueType();
8995       if (LegalTypes)
8996         SetCCVT = getSetCCResultType(SetCCVT);
8997       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8998                                    SetCCVT,
8999                                    Op0, Op1,
9000                                    Equal ? ISD::SETEQ : ISD::SETNE);
9001       // Replace the uses of XOR with SETCC
9002       WorklistRemover DeadNodes(*this);
9003       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9004       deleteAndRecombine(N1.getNode());
9005       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9006                          MVT::Other, Chain, SetCC, N2);
9007     }
9008   }
9009
9010   return SDValue();
9011 }
9012
9013 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9014 //
9015 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9016   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9017   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9018
9019   // If N is a constant we could fold this into a fallthrough or unconditional
9020   // branch. However that doesn't happen very often in normal code, because
9021   // Instcombine/SimplifyCFG should have handled the available opportunities.
9022   // If we did this folding here, it would be necessary to update the
9023   // MachineBasicBlock CFG, which is awkward.
9024
9025   // Use SimplifySetCC to simplify SETCC's.
9026   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9027                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9028                                false);
9029   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9030
9031   // fold to a simpler setcc
9032   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9033     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9034                        N->getOperand(0), Simp.getOperand(2),
9035                        Simp.getOperand(0), Simp.getOperand(1),
9036                        N->getOperand(4));
9037
9038   return SDValue();
9039 }
9040
9041 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9042 /// and that N may be folded in the load / store addressing mode.
9043 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9044                                     SelectionDAG &DAG,
9045                                     const TargetLowering &TLI) {
9046   EVT VT;
9047   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9048     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9049       return false;
9050     VT = LD->getMemoryVT();
9051   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9052     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9053       return false;
9054     VT = ST->getMemoryVT();
9055   } else
9056     return false;
9057
9058   TargetLowering::AddrMode AM;
9059   if (N->getOpcode() == ISD::ADD) {
9060     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9061     if (Offset)
9062       // [reg +/- imm]
9063       AM.BaseOffs = Offset->getSExtValue();
9064     else
9065       // [reg +/- reg]
9066       AM.Scale = 1;
9067   } else if (N->getOpcode() == ISD::SUB) {
9068     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9069     if (Offset)
9070       // [reg +/- imm]
9071       AM.BaseOffs = -Offset->getSExtValue();
9072     else
9073       // [reg +/- reg]
9074       AM.Scale = 1;
9075   } else
9076     return false;
9077
9078   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9079 }
9080
9081 /// Try turning a load/store into a pre-indexed load/store when the base
9082 /// pointer is an add or subtract and it has other uses besides the load/store.
9083 /// After the transformation, the new indexed load/store has effectively folded
9084 /// the add/subtract in and all of its other uses are redirected to the
9085 /// new load/store.
9086 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9087   if (Level < AfterLegalizeDAG)
9088     return false;
9089
9090   bool isLoad = true;
9091   SDValue Ptr;
9092   EVT VT;
9093   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9094     if (LD->isIndexed())
9095       return false;
9096     VT = LD->getMemoryVT();
9097     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9098         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9099       return false;
9100     Ptr = LD->getBasePtr();
9101   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9102     if (ST->isIndexed())
9103       return false;
9104     VT = ST->getMemoryVT();
9105     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9106         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9107       return false;
9108     Ptr = ST->getBasePtr();
9109     isLoad = false;
9110   } else {
9111     return false;
9112   }
9113
9114   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9115   // out.  There is no reason to make this a preinc/predec.
9116   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9117       Ptr.getNode()->hasOneUse())
9118     return false;
9119
9120   // Ask the target to do addressing mode selection.
9121   SDValue BasePtr;
9122   SDValue Offset;
9123   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9124   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9125     return false;
9126
9127   // Backends without true r+i pre-indexed forms may need to pass a
9128   // constant base with a variable offset so that constant coercion
9129   // will work with the patterns in canonical form.
9130   bool Swapped = false;
9131   if (isa<ConstantSDNode>(BasePtr)) {
9132     std::swap(BasePtr, Offset);
9133     Swapped = true;
9134   }
9135
9136   // Don't create a indexed load / store with zero offset.
9137   if (isNullConstant(Offset))
9138     return false;
9139
9140   // Try turning it into a pre-indexed load / store except when:
9141   // 1) The new base ptr is a frame index.
9142   // 2) If N is a store and the new base ptr is either the same as or is a
9143   //    predecessor of the value being stored.
9144   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9145   //    that would create a cycle.
9146   // 4) All uses are load / store ops that use it as old base ptr.
9147
9148   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9149   // (plus the implicit offset) to a register to preinc anyway.
9150   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9151     return false;
9152
9153   // Check #2.
9154   if (!isLoad) {
9155     SDValue Val = cast<StoreSDNode>(N)->getValue();
9156     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9157       return false;
9158   }
9159
9160   // If the offset is a constant, there may be other adds of constants that
9161   // can be folded with this one. We should do this to avoid having to keep
9162   // a copy of the original base pointer.
9163   SmallVector<SDNode *, 16> OtherUses;
9164   if (isa<ConstantSDNode>(Offset))
9165     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9166                               UE = BasePtr.getNode()->use_end();
9167          UI != UE; ++UI) {
9168       SDUse &Use = UI.getUse();
9169       // Skip the use that is Ptr and uses of other results from BasePtr's
9170       // node (important for nodes that return multiple results).
9171       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9172         continue;
9173
9174       if (Use.getUser()->isPredecessorOf(N))
9175         continue;
9176
9177       if (Use.getUser()->getOpcode() != ISD::ADD &&
9178           Use.getUser()->getOpcode() != ISD::SUB) {
9179         OtherUses.clear();
9180         break;
9181       }
9182
9183       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9184       if (!isa<ConstantSDNode>(Op1)) {
9185         OtherUses.clear();
9186         break;
9187       }
9188
9189       // FIXME: In some cases, we can be smarter about this.
9190       if (Op1.getValueType() != Offset.getValueType()) {
9191         OtherUses.clear();
9192         break;
9193       }
9194
9195       OtherUses.push_back(Use.getUser());
9196     }
9197
9198   if (Swapped)
9199     std::swap(BasePtr, Offset);
9200
9201   // Now check for #3 and #4.
9202   bool RealUse = false;
9203
9204   // Caches for hasPredecessorHelper
9205   SmallPtrSet<const SDNode *, 32> Visited;
9206   SmallVector<const SDNode *, 16> Worklist;
9207
9208   for (SDNode *Use : Ptr.getNode()->uses()) {
9209     if (Use == N)
9210       continue;
9211     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9212       return false;
9213
9214     // If Ptr may be folded in addressing mode of other use, then it's
9215     // not profitable to do this transformation.
9216     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9217       RealUse = true;
9218   }
9219
9220   if (!RealUse)
9221     return false;
9222
9223   SDValue Result;
9224   if (isLoad)
9225     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9226                                 BasePtr, Offset, AM);
9227   else
9228     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9229                                  BasePtr, Offset, AM);
9230   ++PreIndexedNodes;
9231   ++NodesCombined;
9232   DEBUG(dbgs() << "\nReplacing.4 ";
9233         N->dump(&DAG);
9234         dbgs() << "\nWith: ";
9235         Result.getNode()->dump(&DAG);
9236         dbgs() << '\n');
9237   WorklistRemover DeadNodes(*this);
9238   if (isLoad) {
9239     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9240     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9241   } else {
9242     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9243   }
9244
9245   // Finally, since the node is now dead, remove it from the graph.
9246   deleteAndRecombine(N);
9247
9248   if (Swapped)
9249     std::swap(BasePtr, Offset);
9250
9251   // Replace other uses of BasePtr that can be updated to use Ptr
9252   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9253     unsigned OffsetIdx = 1;
9254     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9255       OffsetIdx = 0;
9256     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9257            BasePtr.getNode() && "Expected BasePtr operand");
9258
9259     // We need to replace ptr0 in the following expression:
9260     //   x0 * offset0 + y0 * ptr0 = t0
9261     // knowing that
9262     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9263     //
9264     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9265     // indexed load/store and the expresion that needs to be re-written.
9266     //
9267     // Therefore, we have:
9268     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9269
9270     ConstantSDNode *CN =
9271       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9272     int X0, X1, Y0, Y1;
9273     APInt Offset0 = CN->getAPIntValue();
9274     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9275
9276     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9277     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9278     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9279     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9280
9281     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9282
9283     APInt CNV = Offset0;
9284     if (X0 < 0) CNV = -CNV;
9285     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9286     else CNV = CNV - Offset1;
9287
9288     SDLoc DL(OtherUses[i]);
9289
9290     // We can now generate the new expression.
9291     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9292     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9293
9294     SDValue NewUse = DAG.getNode(Opcode,
9295                                  DL,
9296                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9297     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9298     deleteAndRecombine(OtherUses[i]);
9299   }
9300
9301   // Replace the uses of Ptr with uses of the updated base value.
9302   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9303   deleteAndRecombine(Ptr.getNode());
9304
9305   return true;
9306 }
9307
9308 /// Try to combine a load/store with a add/sub of the base pointer node into a
9309 /// post-indexed load/store. The transformation folded the add/subtract into the
9310 /// new indexed load/store effectively and all of its uses are redirected to the
9311 /// new load/store.
9312 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9313   if (Level < AfterLegalizeDAG)
9314     return false;
9315
9316   bool isLoad = true;
9317   SDValue Ptr;
9318   EVT VT;
9319   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9320     if (LD->isIndexed())
9321       return false;
9322     VT = LD->getMemoryVT();
9323     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9324         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9325       return false;
9326     Ptr = LD->getBasePtr();
9327   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9328     if (ST->isIndexed())
9329       return false;
9330     VT = ST->getMemoryVT();
9331     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9332         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9333       return false;
9334     Ptr = ST->getBasePtr();
9335     isLoad = false;
9336   } else {
9337     return false;
9338   }
9339
9340   if (Ptr.getNode()->hasOneUse())
9341     return false;
9342
9343   for (SDNode *Op : Ptr.getNode()->uses()) {
9344     if (Op == N ||
9345         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9346       continue;
9347
9348     SDValue BasePtr;
9349     SDValue Offset;
9350     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9351     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9352       // Don't create a indexed load / store with zero offset.
9353       if (isNullConstant(Offset))
9354         continue;
9355
9356       // Try turning it into a post-indexed load / store except when
9357       // 1) All uses are load / store ops that use it as base ptr (and
9358       //    it may be folded as addressing mmode).
9359       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9360       //    nor a successor of N. Otherwise, if Op is folded that would
9361       //    create a cycle.
9362
9363       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9364         continue;
9365
9366       // Check for #1.
9367       bool TryNext = false;
9368       for (SDNode *Use : BasePtr.getNode()->uses()) {
9369         if (Use == Ptr.getNode())
9370           continue;
9371
9372         // If all the uses are load / store addresses, then don't do the
9373         // transformation.
9374         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9375           bool RealUse = false;
9376           for (SDNode *UseUse : Use->uses()) {
9377             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9378               RealUse = true;
9379           }
9380
9381           if (!RealUse) {
9382             TryNext = true;
9383             break;
9384           }
9385         }
9386       }
9387
9388       if (TryNext)
9389         continue;
9390
9391       // Check for #2
9392       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9393         SDValue Result = isLoad
9394           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9395                                BasePtr, Offset, AM)
9396           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9397                                 BasePtr, Offset, AM);
9398         ++PostIndexedNodes;
9399         ++NodesCombined;
9400         DEBUG(dbgs() << "\nReplacing.5 ";
9401               N->dump(&DAG);
9402               dbgs() << "\nWith: ";
9403               Result.getNode()->dump(&DAG);
9404               dbgs() << '\n');
9405         WorklistRemover DeadNodes(*this);
9406         if (isLoad) {
9407           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9408           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9409         } else {
9410           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9411         }
9412
9413         // Finally, since the node is now dead, remove it from the graph.
9414         deleteAndRecombine(N);
9415
9416         // Replace the uses of Use with uses of the updated base value.
9417         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9418                                       Result.getValue(isLoad ? 1 : 0));
9419         deleteAndRecombine(Op);
9420         return true;
9421       }
9422     }
9423   }
9424
9425   return false;
9426 }
9427
9428 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9429 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9430   ISD::MemIndexedMode AM = LD->getAddressingMode();
9431   assert(AM != ISD::UNINDEXED);
9432   SDValue BP = LD->getOperand(1);
9433   SDValue Inc = LD->getOperand(2);
9434
9435   // Some backends use TargetConstants for load offsets, but don't expect
9436   // TargetConstants in general ADD nodes. We can convert these constants into
9437   // regular Constants (if the constant is not opaque).
9438   assert((Inc.getOpcode() != ISD::TargetConstant ||
9439           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9440          "Cannot split out indexing using opaque target constants");
9441   if (Inc.getOpcode() == ISD::TargetConstant) {
9442     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9443     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9444                           ConstInc->getValueType(0));
9445   }
9446
9447   unsigned Opc =
9448       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9449   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9450 }
9451
9452 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9453   LoadSDNode *LD  = cast<LoadSDNode>(N);
9454   SDValue Chain = LD->getChain();
9455   SDValue Ptr   = LD->getBasePtr();
9456
9457   // If load is not volatile and there are no uses of the loaded value (and
9458   // the updated indexed value in case of indexed loads), change uses of the
9459   // chain value into uses of the chain input (i.e. delete the dead load).
9460   if (!LD->isVolatile()) {
9461     if (N->getValueType(1) == MVT::Other) {
9462       // Unindexed loads.
9463       if (!N->hasAnyUseOfValue(0)) {
9464         // It's not safe to use the two value CombineTo variant here. e.g.
9465         // v1, chain2 = load chain1, loc
9466         // v2, chain3 = load chain2, loc
9467         // v3         = add v2, c
9468         // Now we replace use of chain2 with chain1.  This makes the second load
9469         // isomorphic to the one we are deleting, and thus makes this load live.
9470         DEBUG(dbgs() << "\nReplacing.6 ";
9471               N->dump(&DAG);
9472               dbgs() << "\nWith chain: ";
9473               Chain.getNode()->dump(&DAG);
9474               dbgs() << "\n");
9475         WorklistRemover DeadNodes(*this);
9476         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9477
9478         if (N->use_empty())
9479           deleteAndRecombine(N);
9480
9481         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9482       }
9483     } else {
9484       // Indexed loads.
9485       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9486
9487       // If this load has an opaque TargetConstant offset, then we cannot split
9488       // the indexing into an add/sub directly (that TargetConstant may not be
9489       // valid for a different type of node, and we cannot convert an opaque
9490       // target constant into a regular constant).
9491       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9492                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9493
9494       if (!N->hasAnyUseOfValue(0) &&
9495           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9496         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9497         SDValue Index;
9498         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9499           Index = SplitIndexingFromLoad(LD);
9500           // Try to fold the base pointer arithmetic into subsequent loads and
9501           // stores.
9502           AddUsersToWorklist(N);
9503         } else
9504           Index = DAG.getUNDEF(N->getValueType(1));
9505         DEBUG(dbgs() << "\nReplacing.7 ";
9506               N->dump(&DAG);
9507               dbgs() << "\nWith: ";
9508               Undef.getNode()->dump(&DAG);
9509               dbgs() << " and 2 other values\n");
9510         WorklistRemover DeadNodes(*this);
9511         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9512         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9513         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9514         deleteAndRecombine(N);
9515         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9516       }
9517     }
9518   }
9519
9520   // If this load is directly stored, replace the load value with the stored
9521   // value.
9522   // TODO: Handle store large -> read small portion.
9523   // TODO: Handle TRUNCSTORE/LOADEXT
9524   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9525     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9526       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9527       if (PrevST->getBasePtr() == Ptr &&
9528           PrevST->getValue().getValueType() == N->getValueType(0))
9529       return CombineTo(N, Chain.getOperand(1), Chain);
9530     }
9531   }
9532
9533   // Try to infer better alignment information than the load already has.
9534   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9535     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9536       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9537         SDValue NewLoad =
9538                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9539                               LD->getValueType(0),
9540                               Chain, Ptr, LD->getPointerInfo(),
9541                               LD->getMemoryVT(),
9542                               LD->isVolatile(), LD->isNonTemporal(),
9543                               LD->isInvariant(), Align, LD->getAAInfo());
9544         if (NewLoad.getNode() != N)
9545           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9546       }
9547     }
9548   }
9549
9550   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9551                                                   : DAG.getSubtarget().useAA();
9552 #ifndef NDEBUG
9553   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9554       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9555     UseAA = false;
9556 #endif
9557   if (UseAA && LD->isUnindexed()) {
9558     // Walk up chain skipping non-aliasing memory nodes.
9559     SDValue BetterChain = FindBetterChain(N, Chain);
9560
9561     // If there is a better chain.
9562     if (Chain != BetterChain) {
9563       SDValue ReplLoad;
9564
9565       // Replace the chain to void dependency.
9566       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9567         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9568                                BetterChain, Ptr, LD->getMemOperand());
9569       } else {
9570         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9571                                   LD->getValueType(0),
9572                                   BetterChain, Ptr, LD->getMemoryVT(),
9573                                   LD->getMemOperand());
9574       }
9575
9576       // Create token factor to keep old chain connected.
9577       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9578                                   MVT::Other, Chain, ReplLoad.getValue(1));
9579
9580       // Make sure the new and old chains are cleaned up.
9581       AddToWorklist(Token.getNode());
9582
9583       // Replace uses with load result and token factor. Don't add users
9584       // to work list.
9585       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9586     }
9587   }
9588
9589   // Try transforming N to an indexed load.
9590   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9591     return SDValue(N, 0);
9592
9593   // Try to slice up N to more direct loads if the slices are mapped to
9594   // different register banks or pairing can take place.
9595   if (SliceUpLoad(N))
9596     return SDValue(N, 0);
9597
9598   return SDValue();
9599 }
9600
9601 namespace {
9602 /// \brief Helper structure used to slice a load in smaller loads.
9603 /// Basically a slice is obtained from the following sequence:
9604 /// Origin = load Ty1, Base
9605 /// Shift = srl Ty1 Origin, CstTy Amount
9606 /// Inst = trunc Shift to Ty2
9607 ///
9608 /// Then, it will be rewriten into:
9609 /// Slice = load SliceTy, Base + SliceOffset
9610 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9611 ///
9612 /// SliceTy is deduced from the number of bits that are actually used to
9613 /// build Inst.
9614 struct LoadedSlice {
9615   /// \brief Helper structure used to compute the cost of a slice.
9616   struct Cost {
9617     /// Are we optimizing for code size.
9618     bool ForCodeSize;
9619     /// Various cost.
9620     unsigned Loads;
9621     unsigned Truncates;
9622     unsigned CrossRegisterBanksCopies;
9623     unsigned ZExts;
9624     unsigned Shift;
9625
9626     Cost(bool ForCodeSize = false)
9627         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9628           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9629
9630     /// \brief Get the cost of one isolated slice.
9631     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9632         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9633           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9634       EVT TruncType = LS.Inst->getValueType(0);
9635       EVT LoadedType = LS.getLoadedType();
9636       if (TruncType != LoadedType &&
9637           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9638         ZExts = 1;
9639     }
9640
9641     /// \brief Account for slicing gain in the current cost.
9642     /// Slicing provide a few gains like removing a shift or a
9643     /// truncate. This method allows to grow the cost of the original
9644     /// load with the gain from this slice.
9645     void addSliceGain(const LoadedSlice &LS) {
9646       // Each slice saves a truncate.
9647       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9648       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9649                               LS.Inst->getOperand(0).getValueType()))
9650         ++Truncates;
9651       // If there is a shift amount, this slice gets rid of it.
9652       if (LS.Shift)
9653         ++Shift;
9654       // If this slice can merge a cross register bank copy, account for it.
9655       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9656         ++CrossRegisterBanksCopies;
9657     }
9658
9659     Cost &operator+=(const Cost &RHS) {
9660       Loads += RHS.Loads;
9661       Truncates += RHS.Truncates;
9662       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9663       ZExts += RHS.ZExts;
9664       Shift += RHS.Shift;
9665       return *this;
9666     }
9667
9668     bool operator==(const Cost &RHS) const {
9669       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9670              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9671              ZExts == RHS.ZExts && Shift == RHS.Shift;
9672     }
9673
9674     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9675
9676     bool operator<(const Cost &RHS) const {
9677       // Assume cross register banks copies are as expensive as loads.
9678       // FIXME: Do we want some more target hooks?
9679       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9680       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9681       // Unless we are optimizing for code size, consider the
9682       // expensive operation first.
9683       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9684         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9685       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9686              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9687     }
9688
9689     bool operator>(const Cost &RHS) const { return RHS < *this; }
9690
9691     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9692
9693     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9694   };
9695   // The last instruction that represent the slice. This should be a
9696   // truncate instruction.
9697   SDNode *Inst;
9698   // The original load instruction.
9699   LoadSDNode *Origin;
9700   // The right shift amount in bits from the original load.
9701   unsigned Shift;
9702   // The DAG from which Origin came from.
9703   // This is used to get some contextual information about legal types, etc.
9704   SelectionDAG *DAG;
9705
9706   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9707               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9708       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9709
9710   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9711   /// \return Result is \p BitWidth and has used bits set to 1 and
9712   ///         not used bits set to 0.
9713   APInt getUsedBits() const {
9714     // Reproduce the trunc(lshr) sequence:
9715     // - Start from the truncated value.
9716     // - Zero extend to the desired bit width.
9717     // - Shift left.
9718     assert(Origin && "No original load to compare against.");
9719     unsigned BitWidth = Origin->getValueSizeInBits(0);
9720     assert(Inst && "This slice is not bound to an instruction");
9721     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9722            "Extracted slice is bigger than the whole type!");
9723     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9724     UsedBits.setAllBits();
9725     UsedBits = UsedBits.zext(BitWidth);
9726     UsedBits <<= Shift;
9727     return UsedBits;
9728   }
9729
9730   /// \brief Get the size of the slice to be loaded in bytes.
9731   unsigned getLoadedSize() const {
9732     unsigned SliceSize = getUsedBits().countPopulation();
9733     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9734     return SliceSize / 8;
9735   }
9736
9737   /// \brief Get the type that will be loaded for this slice.
9738   /// Note: This may not be the final type for the slice.
9739   EVT getLoadedType() const {
9740     assert(DAG && "Missing context");
9741     LLVMContext &Ctxt = *DAG->getContext();
9742     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9743   }
9744
9745   /// \brief Get the alignment of the load used for this slice.
9746   unsigned getAlignment() const {
9747     unsigned Alignment = Origin->getAlignment();
9748     unsigned Offset = getOffsetFromBase();
9749     if (Offset != 0)
9750       Alignment = MinAlign(Alignment, Alignment + Offset);
9751     return Alignment;
9752   }
9753
9754   /// \brief Check if this slice can be rewritten with legal operations.
9755   bool isLegal() const {
9756     // An invalid slice is not legal.
9757     if (!Origin || !Inst || !DAG)
9758       return false;
9759
9760     // Offsets are for indexed load only, we do not handle that.
9761     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9762       return false;
9763
9764     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9765
9766     // Check that the type is legal.
9767     EVT SliceType = getLoadedType();
9768     if (!TLI.isTypeLegal(SliceType))
9769       return false;
9770
9771     // Check that the load is legal for this type.
9772     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9773       return false;
9774
9775     // Check that the offset can be computed.
9776     // 1. Check its type.
9777     EVT PtrType = Origin->getBasePtr().getValueType();
9778     if (PtrType == MVT::Untyped || PtrType.isExtended())
9779       return false;
9780
9781     // 2. Check that it fits in the immediate.
9782     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9783       return false;
9784
9785     // 3. Check that the computation is legal.
9786     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9787       return false;
9788
9789     // Check that the zext is legal if it needs one.
9790     EVT TruncateType = Inst->getValueType(0);
9791     if (TruncateType != SliceType &&
9792         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9793       return false;
9794
9795     return true;
9796   }
9797
9798   /// \brief Get the offset in bytes of this slice in the original chunk of
9799   /// bits.
9800   /// \pre DAG != nullptr.
9801   uint64_t getOffsetFromBase() const {
9802     assert(DAG && "Missing context.");
9803     bool IsBigEndian =
9804         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9805     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9806     uint64_t Offset = Shift / 8;
9807     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9808     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9809            "The size of the original loaded type is not a multiple of a"
9810            " byte.");
9811     // If Offset is bigger than TySizeInBytes, it means we are loading all
9812     // zeros. This should have been optimized before in the process.
9813     assert(TySizeInBytes > Offset &&
9814            "Invalid shift amount for given loaded size");
9815     if (IsBigEndian)
9816       Offset = TySizeInBytes - Offset - getLoadedSize();
9817     return Offset;
9818   }
9819
9820   /// \brief Generate the sequence of instructions to load the slice
9821   /// represented by this object and redirect the uses of this slice to
9822   /// this new sequence of instructions.
9823   /// \pre this->Inst && this->Origin are valid Instructions and this
9824   /// object passed the legal check: LoadedSlice::isLegal returned true.
9825   /// \return The last instruction of the sequence used to load the slice.
9826   SDValue loadSlice() const {
9827     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9828     const SDValue &OldBaseAddr = Origin->getBasePtr();
9829     SDValue BaseAddr = OldBaseAddr;
9830     // Get the offset in that chunk of bytes w.r.t. the endianess.
9831     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9832     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9833     if (Offset) {
9834       // BaseAddr = BaseAddr + Offset.
9835       EVT ArithType = BaseAddr.getValueType();
9836       SDLoc DL(Origin);
9837       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9838                               DAG->getConstant(Offset, DL, ArithType));
9839     }
9840
9841     // Create the type of the loaded slice according to its size.
9842     EVT SliceType = getLoadedType();
9843
9844     // Create the load for the slice.
9845     SDValue LastInst = DAG->getLoad(
9846         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9847         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9848         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9849     // If the final type is not the same as the loaded type, this means that
9850     // we have to pad with zero. Create a zero extend for that.
9851     EVT FinalType = Inst->getValueType(0);
9852     if (SliceType != FinalType)
9853       LastInst =
9854           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9855     return LastInst;
9856   }
9857
9858   /// \brief Check if this slice can be merged with an expensive cross register
9859   /// bank copy. E.g.,
9860   /// i = load i32
9861   /// f = bitcast i32 i to float
9862   bool canMergeExpensiveCrossRegisterBankCopy() const {
9863     if (!Inst || !Inst->hasOneUse())
9864       return false;
9865     SDNode *Use = *Inst->use_begin();
9866     if (Use->getOpcode() != ISD::BITCAST)
9867       return false;
9868     assert(DAG && "Missing context");
9869     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9870     EVT ResVT = Use->getValueType(0);
9871     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9872     const TargetRegisterClass *ArgRC =
9873         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9874     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9875       return false;
9876
9877     // At this point, we know that we perform a cross-register-bank copy.
9878     // Check if it is expensive.
9879     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9880     // Assume bitcasts are cheap, unless both register classes do not
9881     // explicitly share a common sub class.
9882     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9883       return false;
9884
9885     // Check if it will be merged with the load.
9886     // 1. Check the alignment constraint.
9887     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9888         ResVT.getTypeForEVT(*DAG->getContext()));
9889
9890     if (RequiredAlignment > getAlignment())
9891       return false;
9892
9893     // 2. Check that the load is a legal operation for that type.
9894     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9895       return false;
9896
9897     // 3. Check that we do not have a zext in the way.
9898     if (Inst->getValueType(0) != getLoadedType())
9899       return false;
9900
9901     return true;
9902   }
9903 };
9904 }
9905
9906 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9907 /// \p UsedBits looks like 0..0 1..1 0..0.
9908 static bool areUsedBitsDense(const APInt &UsedBits) {
9909   // If all the bits are one, this is dense!
9910   if (UsedBits.isAllOnesValue())
9911     return true;
9912
9913   // Get rid of the unused bits on the right.
9914   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9915   // Get rid of the unused bits on the left.
9916   if (NarrowedUsedBits.countLeadingZeros())
9917     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9918   // Check that the chunk of bits is completely used.
9919   return NarrowedUsedBits.isAllOnesValue();
9920 }
9921
9922 /// \brief Check whether or not \p First and \p Second are next to each other
9923 /// in memory. This means that there is no hole between the bits loaded
9924 /// by \p First and the bits loaded by \p Second.
9925 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9926                                      const LoadedSlice &Second) {
9927   assert(First.Origin == Second.Origin && First.Origin &&
9928          "Unable to match different memory origins.");
9929   APInt UsedBits = First.getUsedBits();
9930   assert((UsedBits & Second.getUsedBits()) == 0 &&
9931          "Slices are not supposed to overlap.");
9932   UsedBits |= Second.getUsedBits();
9933   return areUsedBitsDense(UsedBits);
9934 }
9935
9936 /// \brief Adjust the \p GlobalLSCost according to the target
9937 /// paring capabilities and the layout of the slices.
9938 /// \pre \p GlobalLSCost should account for at least as many loads as
9939 /// there is in the slices in \p LoadedSlices.
9940 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9941                                  LoadedSlice::Cost &GlobalLSCost) {
9942   unsigned NumberOfSlices = LoadedSlices.size();
9943   // If there is less than 2 elements, no pairing is possible.
9944   if (NumberOfSlices < 2)
9945     return;
9946
9947   // Sort the slices so that elements that are likely to be next to each
9948   // other in memory are next to each other in the list.
9949   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9950             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9951     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9952     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9953   });
9954   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9955   // First (resp. Second) is the first (resp. Second) potentially candidate
9956   // to be placed in a paired load.
9957   const LoadedSlice *First = nullptr;
9958   const LoadedSlice *Second = nullptr;
9959   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9960                 // Set the beginning of the pair.
9961                                                            First = Second) {
9962
9963     Second = &LoadedSlices[CurrSlice];
9964
9965     // If First is NULL, it means we start a new pair.
9966     // Get to the next slice.
9967     if (!First)
9968       continue;
9969
9970     EVT LoadedType = First->getLoadedType();
9971
9972     // If the types of the slices are different, we cannot pair them.
9973     if (LoadedType != Second->getLoadedType())
9974       continue;
9975
9976     // Check if the target supplies paired loads for this type.
9977     unsigned RequiredAlignment = 0;
9978     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9979       // move to the next pair, this type is hopeless.
9980       Second = nullptr;
9981       continue;
9982     }
9983     // Check if we meet the alignment requirement.
9984     if (RequiredAlignment > First->getAlignment())
9985       continue;
9986
9987     // Check that both loads are next to each other in memory.
9988     if (!areSlicesNextToEachOther(*First, *Second))
9989       continue;
9990
9991     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9992     --GlobalLSCost.Loads;
9993     // Move to the next pair.
9994     Second = nullptr;
9995   }
9996 }
9997
9998 /// \brief Check the profitability of all involved LoadedSlice.
9999 /// Currently, it is considered profitable if there is exactly two
10000 /// involved slices (1) which are (2) next to each other in memory, and
10001 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10002 ///
10003 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10004 /// the elements themselves.
10005 ///
10006 /// FIXME: When the cost model will be mature enough, we can relax
10007 /// constraints (1) and (2).
10008 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10009                                 const APInt &UsedBits, bool ForCodeSize) {
10010   unsigned NumberOfSlices = LoadedSlices.size();
10011   if (StressLoadSlicing)
10012     return NumberOfSlices > 1;
10013
10014   // Check (1).
10015   if (NumberOfSlices != 2)
10016     return false;
10017
10018   // Check (2).
10019   if (!areUsedBitsDense(UsedBits))
10020     return false;
10021
10022   // Check (3).
10023   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10024   // The original code has one big load.
10025   OrigCost.Loads = 1;
10026   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10027     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10028     // Accumulate the cost of all the slices.
10029     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10030     GlobalSlicingCost += SliceCost;
10031
10032     // Account as cost in the original configuration the gain obtained
10033     // with the current slices.
10034     OrigCost.addSliceGain(LS);
10035   }
10036
10037   // If the target supports paired load, adjust the cost accordingly.
10038   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10039   return OrigCost > GlobalSlicingCost;
10040 }
10041
10042 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10043 /// operations, split it in the various pieces being extracted.
10044 ///
10045 /// This sort of thing is introduced by SROA.
10046 /// This slicing takes care not to insert overlapping loads.
10047 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10048 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10049   if (Level < AfterLegalizeDAG)
10050     return false;
10051
10052   LoadSDNode *LD = cast<LoadSDNode>(N);
10053   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10054       !LD->getValueType(0).isInteger())
10055     return false;
10056
10057   // Keep track of already used bits to detect overlapping values.
10058   // In that case, we will just abort the transformation.
10059   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10060
10061   SmallVector<LoadedSlice, 4> LoadedSlices;
10062
10063   // Check if this load is used as several smaller chunks of bits.
10064   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10065   // of computation for each trunc.
10066   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10067        UI != UIEnd; ++UI) {
10068     // Skip the uses of the chain.
10069     if (UI.getUse().getResNo() != 0)
10070       continue;
10071
10072     SDNode *User = *UI;
10073     unsigned Shift = 0;
10074
10075     // Check if this is a trunc(lshr).
10076     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10077         isa<ConstantSDNode>(User->getOperand(1))) {
10078       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10079       User = *User->use_begin();
10080     }
10081
10082     // At this point, User is a Truncate, iff we encountered, trunc or
10083     // trunc(lshr).
10084     if (User->getOpcode() != ISD::TRUNCATE)
10085       return false;
10086
10087     // The width of the type must be a power of 2 and greater than 8-bits.
10088     // Otherwise the load cannot be represented in LLVM IR.
10089     // Moreover, if we shifted with a non-8-bits multiple, the slice
10090     // will be across several bytes. We do not support that.
10091     unsigned Width = User->getValueSizeInBits(0);
10092     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10093       return 0;
10094
10095     // Build the slice for this chain of computations.
10096     LoadedSlice LS(User, LD, Shift, &DAG);
10097     APInt CurrentUsedBits = LS.getUsedBits();
10098
10099     // Check if this slice overlaps with another.
10100     if ((CurrentUsedBits & UsedBits) != 0)
10101       return false;
10102     // Update the bits used globally.
10103     UsedBits |= CurrentUsedBits;
10104
10105     // Check if the new slice would be legal.
10106     if (!LS.isLegal())
10107       return false;
10108
10109     // Record the slice.
10110     LoadedSlices.push_back(LS);
10111   }
10112
10113   // Abort slicing if it does not seem to be profitable.
10114   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10115     return false;
10116
10117   ++SlicedLoads;
10118
10119   // Rewrite each chain to use an independent load.
10120   // By construction, each chain can be represented by a unique load.
10121
10122   // Prepare the argument for the new token factor for all the slices.
10123   SmallVector<SDValue, 8> ArgChains;
10124   for (SmallVectorImpl<LoadedSlice>::const_iterator
10125            LSIt = LoadedSlices.begin(),
10126            LSItEnd = LoadedSlices.end();
10127        LSIt != LSItEnd; ++LSIt) {
10128     SDValue SliceInst = LSIt->loadSlice();
10129     CombineTo(LSIt->Inst, SliceInst, true);
10130     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10131       SliceInst = SliceInst.getOperand(0);
10132     assert(SliceInst->getOpcode() == ISD::LOAD &&
10133            "It takes more than a zext to get to the loaded slice!!");
10134     ArgChains.push_back(SliceInst.getValue(1));
10135   }
10136
10137   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10138                               ArgChains);
10139   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10140   return true;
10141 }
10142
10143 /// Check to see if V is (and load (ptr), imm), where the load is having
10144 /// specific bytes cleared out.  If so, return the byte size being masked out
10145 /// and the shift amount.
10146 static std::pair<unsigned, unsigned>
10147 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10148   std::pair<unsigned, unsigned> Result(0, 0);
10149
10150   // Check for the structure we're looking for.
10151   if (V->getOpcode() != ISD::AND ||
10152       !isa<ConstantSDNode>(V->getOperand(1)) ||
10153       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10154     return Result;
10155
10156   // Check the chain and pointer.
10157   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10158   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10159
10160   // The store should be chained directly to the load or be an operand of a
10161   // tokenfactor.
10162   if (LD == Chain.getNode())
10163     ; // ok.
10164   else if (Chain->getOpcode() != ISD::TokenFactor)
10165     return Result; // Fail.
10166   else {
10167     bool isOk = false;
10168     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10169       if (Chain->getOperand(i).getNode() == LD) {
10170         isOk = true;
10171         break;
10172       }
10173     if (!isOk) return Result;
10174   }
10175
10176   // This only handles simple types.
10177   if (V.getValueType() != MVT::i16 &&
10178       V.getValueType() != MVT::i32 &&
10179       V.getValueType() != MVT::i64)
10180     return Result;
10181
10182   // Check the constant mask.  Invert it so that the bits being masked out are
10183   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10184   // follow the sign bit for uniformity.
10185   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10186   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10187   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10188   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10189   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10190   if (NotMaskLZ == 64) return Result;  // All zero mask.
10191
10192   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10193   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10194     return Result;
10195
10196   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10197   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10198     NotMaskLZ -= 64-V.getValueSizeInBits();
10199
10200   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10201   switch (MaskedBytes) {
10202   case 1:
10203   case 2:
10204   case 4: break;
10205   default: return Result; // All one mask, or 5-byte mask.
10206   }
10207
10208   // Verify that the first bit starts at a multiple of mask so that the access
10209   // is aligned the same as the access width.
10210   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10211
10212   Result.first = MaskedBytes;
10213   Result.second = NotMaskTZ/8;
10214   return Result;
10215 }
10216
10217
10218 /// Check to see if IVal is something that provides a value as specified by
10219 /// MaskInfo. If so, replace the specified store with a narrower store of
10220 /// truncated IVal.
10221 static SDNode *
10222 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10223                                 SDValue IVal, StoreSDNode *St,
10224                                 DAGCombiner *DC) {
10225   unsigned NumBytes = MaskInfo.first;
10226   unsigned ByteShift = MaskInfo.second;
10227   SelectionDAG &DAG = DC->getDAG();
10228
10229   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10230   // that uses this.  If not, this is not a replacement.
10231   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10232                                   ByteShift*8, (ByteShift+NumBytes)*8);
10233   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10234
10235   // Check that it is legal on the target to do this.  It is legal if the new
10236   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10237   // legalization.
10238   MVT VT = MVT::getIntegerVT(NumBytes*8);
10239   if (!DC->isTypeLegal(VT))
10240     return nullptr;
10241
10242   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10243   // shifted by ByteShift and truncated down to NumBytes.
10244   if (ByteShift) {
10245     SDLoc DL(IVal);
10246     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10247                        DAG.getConstant(ByteShift*8, DL,
10248                                     DC->getShiftAmountTy(IVal.getValueType())));
10249   }
10250
10251   // Figure out the offset for the store and the alignment of the access.
10252   unsigned StOffset;
10253   unsigned NewAlign = St->getAlignment();
10254
10255   if (DAG.getTargetLoweringInfo().isLittleEndian())
10256     StOffset = ByteShift;
10257   else
10258     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10259
10260   SDValue Ptr = St->getBasePtr();
10261   if (StOffset) {
10262     SDLoc DL(IVal);
10263     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10264                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10265     NewAlign = MinAlign(NewAlign, StOffset);
10266   }
10267
10268   // Truncate down to the new size.
10269   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10270
10271   ++OpsNarrowed;
10272   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10273                       St->getPointerInfo().getWithOffset(StOffset),
10274                       false, false, NewAlign).getNode();
10275 }
10276
10277
10278 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10279 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10280 /// narrowing the load and store if it would end up being a win for performance
10281 /// or code size.
10282 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10283   StoreSDNode *ST  = cast<StoreSDNode>(N);
10284   if (ST->isVolatile())
10285     return SDValue();
10286
10287   SDValue Chain = ST->getChain();
10288   SDValue Value = ST->getValue();
10289   SDValue Ptr   = ST->getBasePtr();
10290   EVT VT = Value.getValueType();
10291
10292   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10293     return SDValue();
10294
10295   unsigned Opc = Value.getOpcode();
10296
10297   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10298   // is a byte mask indicating a consecutive number of bytes, check to see if
10299   // Y is known to provide just those bytes.  If so, we try to replace the
10300   // load + replace + store sequence with a single (narrower) store, which makes
10301   // the load dead.
10302   if (Opc == ISD::OR) {
10303     std::pair<unsigned, unsigned> MaskedLoad;
10304     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10305     if (MaskedLoad.first)
10306       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10307                                                   Value.getOperand(1), ST,this))
10308         return SDValue(NewST, 0);
10309
10310     // Or is commutative, so try swapping X and Y.
10311     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10312     if (MaskedLoad.first)
10313       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10314                                                   Value.getOperand(0), ST,this))
10315         return SDValue(NewST, 0);
10316   }
10317
10318   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10319       Value.getOperand(1).getOpcode() != ISD::Constant)
10320     return SDValue();
10321
10322   SDValue N0 = Value.getOperand(0);
10323   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10324       Chain == SDValue(N0.getNode(), 1)) {
10325     LoadSDNode *LD = cast<LoadSDNode>(N0);
10326     if (LD->getBasePtr() != Ptr ||
10327         LD->getPointerInfo().getAddrSpace() !=
10328         ST->getPointerInfo().getAddrSpace())
10329       return SDValue();
10330
10331     // Find the type to narrow it the load / op / store to.
10332     SDValue N1 = Value.getOperand(1);
10333     unsigned BitWidth = N1.getValueSizeInBits();
10334     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10335     if (Opc == ISD::AND)
10336       Imm ^= APInt::getAllOnesValue(BitWidth);
10337     if (Imm == 0 || Imm.isAllOnesValue())
10338       return SDValue();
10339     unsigned ShAmt = Imm.countTrailingZeros();
10340     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10341     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10342     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10343     // The narrowing should be profitable, the load/store operation should be
10344     // legal (or custom) and the store size should be equal to the NewVT width.
10345     while (NewBW < BitWidth &&
10346            (NewVT.getStoreSizeInBits() != NewBW ||
10347             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10348             !TLI.isNarrowingProfitable(VT, NewVT))) {
10349       NewBW = NextPowerOf2(NewBW);
10350       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10351     }
10352     if (NewBW >= BitWidth)
10353       return SDValue();
10354
10355     // If the lsb changed does not start at the type bitwidth boundary,
10356     // start at the previous one.
10357     if (ShAmt % NewBW)
10358       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10359     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10360                                    std::min(BitWidth, ShAmt + NewBW));
10361     if ((Imm & Mask) == Imm) {
10362       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10363       if (Opc == ISD::AND)
10364         NewImm ^= APInt::getAllOnesValue(NewBW);
10365       uint64_t PtrOff = ShAmt / 8;
10366       // For big endian targets, we need to adjust the offset to the pointer to
10367       // load the correct bytes.
10368       if (TLI.isBigEndian())
10369         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10370
10371       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10372       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10373       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10374         return SDValue();
10375
10376       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10377                                    Ptr.getValueType(), Ptr,
10378                                    DAG.getConstant(PtrOff, SDLoc(LD),
10379                                                    Ptr.getValueType()));
10380       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10381                                   LD->getChain(), NewPtr,
10382                                   LD->getPointerInfo().getWithOffset(PtrOff),
10383                                   LD->isVolatile(), LD->isNonTemporal(),
10384                                   LD->isInvariant(), NewAlign,
10385                                   LD->getAAInfo());
10386       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10387                                    DAG.getConstant(NewImm, SDLoc(Value),
10388                                                    NewVT));
10389       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10390                                    NewVal, NewPtr,
10391                                    ST->getPointerInfo().getWithOffset(PtrOff),
10392                                    false, false, NewAlign);
10393
10394       AddToWorklist(NewPtr.getNode());
10395       AddToWorklist(NewLD.getNode());
10396       AddToWorklist(NewVal.getNode());
10397       WorklistRemover DeadNodes(*this);
10398       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10399       ++OpsNarrowed;
10400       return NewST;
10401     }
10402   }
10403
10404   return SDValue();
10405 }
10406
10407 /// For a given floating point load / store pair, if the load value isn't used
10408 /// by any other operations, then consider transforming the pair to integer
10409 /// load / store operations if the target deems the transformation profitable.
10410 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10411   StoreSDNode *ST  = cast<StoreSDNode>(N);
10412   SDValue Chain = ST->getChain();
10413   SDValue Value = ST->getValue();
10414   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10415       Value.hasOneUse() &&
10416       Chain == SDValue(Value.getNode(), 1)) {
10417     LoadSDNode *LD = cast<LoadSDNode>(Value);
10418     EVT VT = LD->getMemoryVT();
10419     if (!VT.isFloatingPoint() ||
10420         VT != ST->getMemoryVT() ||
10421         LD->isNonTemporal() ||
10422         ST->isNonTemporal() ||
10423         LD->getPointerInfo().getAddrSpace() != 0 ||
10424         ST->getPointerInfo().getAddrSpace() != 0)
10425       return SDValue();
10426
10427     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10428     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10429         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10430         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10431         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10432       return SDValue();
10433
10434     unsigned LDAlign = LD->getAlignment();
10435     unsigned STAlign = ST->getAlignment();
10436     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10437     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10438     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10439       return SDValue();
10440
10441     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10442                                 LD->getChain(), LD->getBasePtr(),
10443                                 LD->getPointerInfo(),
10444                                 false, false, false, LDAlign);
10445
10446     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10447                                  NewLD, ST->getBasePtr(),
10448                                  ST->getPointerInfo(),
10449                                  false, false, STAlign);
10450
10451     AddToWorklist(NewLD.getNode());
10452     AddToWorklist(NewST.getNode());
10453     WorklistRemover DeadNodes(*this);
10454     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10455     ++LdStFP2Int;
10456     return NewST;
10457   }
10458
10459   return SDValue();
10460 }
10461
10462 namespace {
10463 /// Helper struct to parse and store a memory address as base + index + offset.
10464 /// We ignore sign extensions when it is safe to do so.
10465 /// The following two expressions are not equivalent. To differentiate we need
10466 /// to store whether there was a sign extension involved in the index
10467 /// computation.
10468 ///  (load (i64 add (i64 copyfromreg %c)
10469 ///                 (i64 signextend (add (i8 load %index)
10470 ///                                      (i8 1))))
10471 /// vs
10472 ///
10473 /// (load (i64 add (i64 copyfromreg %c)
10474 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10475 ///                                         (i32 1)))))
10476 struct BaseIndexOffset {
10477   SDValue Base;
10478   SDValue Index;
10479   int64_t Offset;
10480   bool IsIndexSignExt;
10481
10482   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10483
10484   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10485                   bool IsIndexSignExt) :
10486     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10487
10488   bool equalBaseIndex(const BaseIndexOffset &Other) {
10489     return Other.Base == Base && Other.Index == Index &&
10490       Other.IsIndexSignExt == IsIndexSignExt;
10491   }
10492
10493   /// Parses tree in Ptr for base, index, offset addresses.
10494   static BaseIndexOffset match(SDValue Ptr) {
10495     bool IsIndexSignExt = false;
10496
10497     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10498     // instruction, then it could be just the BASE or everything else we don't
10499     // know how to handle. Just use Ptr as BASE and give up.
10500     if (Ptr->getOpcode() != ISD::ADD)
10501       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10502
10503     // We know that we have at least an ADD instruction. Try to pattern match
10504     // the simple case of BASE + OFFSET.
10505     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10506       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10507       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10508                               IsIndexSignExt);
10509     }
10510
10511     // Inside a loop the current BASE pointer is calculated using an ADD and a
10512     // MUL instruction. In this case Ptr is the actual BASE pointer.
10513     // (i64 add (i64 %array_ptr)
10514     //          (i64 mul (i64 %induction_var)
10515     //                   (i64 %element_size)))
10516     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10517       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10518
10519     // Look at Base + Index + Offset cases.
10520     SDValue Base = Ptr->getOperand(0);
10521     SDValue IndexOffset = Ptr->getOperand(1);
10522
10523     // Skip signextends.
10524     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10525       IndexOffset = IndexOffset->getOperand(0);
10526       IsIndexSignExt = true;
10527     }
10528
10529     // Either the case of Base + Index (no offset) or something else.
10530     if (IndexOffset->getOpcode() != ISD::ADD)
10531       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10532
10533     // Now we have the case of Base + Index + offset.
10534     SDValue Index = IndexOffset->getOperand(0);
10535     SDValue Offset = IndexOffset->getOperand(1);
10536
10537     if (!isa<ConstantSDNode>(Offset))
10538       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10539
10540     // Ignore signextends.
10541     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10542       Index = Index->getOperand(0);
10543       IsIndexSignExt = true;
10544     } else IsIndexSignExt = false;
10545
10546     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10547     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10548   }
10549 };
10550 } // namespace
10551
10552 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10553                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10554                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10555   // Make sure we have something to merge.
10556   if (NumElem < 2)
10557     return false;
10558
10559   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10560   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10561   unsigned LatestNodeUsed = 0;
10562
10563   for (unsigned i=0; i < NumElem; ++i) {
10564     // Find a chain for the new wide-store operand. Notice that some
10565     // of the store nodes that we found may not be selected for inclusion
10566     // in the wide store. The chain we use needs to be the chain of the
10567     // latest store node which is *used* and replaced by the wide store.
10568     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10569       LatestNodeUsed = i;
10570   }
10571
10572   // The latest Node in the DAG.
10573   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10574   SDLoc DL(StoreNodes[0].MemNode);
10575
10576   SDValue StoredVal;
10577   if (UseVector) {
10578     // Find a legal type for the vector store.
10579     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10580     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10581     if (IsConstantSrc) {
10582       // A vector store with a constant source implies that the constant is
10583       // zero; we only handle merging stores of constant zeros because the zero
10584       // can be materialized without a load.
10585       // It may be beneficial to loosen this restriction to allow non-zero
10586       // store merging.
10587       StoredVal = DAG.getConstant(0, DL, Ty);
10588     } else {
10589       SmallVector<SDValue, 8> Ops;
10590       for (unsigned i = 0; i < NumElem ; ++i) {
10591         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10592         SDValue Val = St->getValue();
10593         // All of the operands of a BUILD_VECTOR must have the same type.
10594         if (Val.getValueType() != MemVT)
10595           return false;
10596         Ops.push_back(Val);
10597       }
10598
10599       // Build the extracted vector elements back into a vector.
10600       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10601     }
10602   } else {
10603     // We should always use a vector store when merging extracted vector
10604     // elements, so this path implies a store of constants.
10605     assert(IsConstantSrc && "Merged vector elements should use vector store");
10606
10607     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10608     APInt StoreInt(StoreBW, 0);
10609
10610     // Construct a single integer constant which is made of the smaller
10611     // constant inputs.
10612     bool IsLE = TLI.isLittleEndian();
10613     for (unsigned i = 0; i < NumElem ; ++i) {
10614       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10615       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10616       SDValue Val = St->getValue();
10617       StoreInt <<= ElementSizeBytes*8;
10618       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10619         StoreInt |= C->getAPIntValue().zext(StoreBW);
10620       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10621         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10622       } else {
10623         llvm_unreachable("Invalid constant element type");
10624       }
10625     }
10626
10627     // Create the new Load and Store operations.
10628     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10629     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10630   }
10631
10632   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10633                                   FirstInChain->getBasePtr(),
10634                                   FirstInChain->getPointerInfo(),
10635                                   false, false,
10636                                   FirstInChain->getAlignment());
10637
10638   // Replace the last store with the new store
10639   CombineTo(LatestOp, NewStore);
10640   // Erase all other stores.
10641   for (unsigned i = 0; i < NumElem ; ++i) {
10642     if (StoreNodes[i].MemNode == LatestOp)
10643       continue;
10644     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10645     // ReplaceAllUsesWith will replace all uses that existed when it was
10646     // called, but graph optimizations may cause new ones to appear. For
10647     // example, the case in pr14333 looks like
10648     //
10649     //  St's chain -> St -> another store -> X
10650     //
10651     // And the only difference from St to the other store is the chain.
10652     // When we change it's chain to be St's chain they become identical,
10653     // get CSEed and the net result is that X is now a use of St.
10654     // Since we know that St is redundant, just iterate.
10655     while (!St->use_empty())
10656       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10657     deleteAndRecombine(St);
10658   }
10659
10660   return true;
10661 }
10662
10663 static bool allowableAlignment(const SelectionDAG &DAG,
10664                                const TargetLowering &TLI, EVT EVTTy,
10665                                unsigned AS, unsigned Align) {
10666   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10667     return true;
10668
10669   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10670   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10671   return (Align >= ABIAlignment);
10672 }
10673
10674 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10675   if (OptLevel == CodeGenOpt::None)
10676     return false;
10677
10678   EVT MemVT = St->getMemoryVT();
10679   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10680   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10681       Attribute::NoImplicitFloat);
10682
10683   // This function cannot currently deal with non-byte-sized memory sizes.
10684   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10685     return false;
10686
10687   // Don't merge vectors into wider inputs.
10688   if (MemVT.isVector() || !MemVT.isSimple())
10689     return false;
10690
10691   // Perform an early exit check. Do not bother looking at stored values that
10692   // are not constants, loads, or extracted vector elements.
10693   SDValue StoredVal = St->getValue();
10694   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10695   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10696                        isa<ConstantFPSDNode>(StoredVal);
10697   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10698
10699   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10700     return false;
10701
10702   // Only look at ends of store sequences.
10703   SDValue Chain = SDValue(St, 0);
10704   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10705     return false;
10706
10707   // This holds the base pointer, index, and the offset in bytes from the base
10708   // pointer.
10709   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10710
10711   // We must have a base and an offset.
10712   if (!BasePtr.Base.getNode())
10713     return false;
10714
10715   // Do not handle stores to undef base pointers.
10716   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10717     return false;
10718
10719   // Save the LoadSDNodes that we find in the chain.
10720   // We need to make sure that these nodes do not interfere with
10721   // any of the store nodes.
10722   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10723
10724   // Save the StoreSDNodes that we find in the chain.
10725   SmallVector<MemOpLink, 8> StoreNodes;
10726
10727   // Walk up the chain and look for nodes with offsets from the same
10728   // base pointer. Stop when reaching an instruction with a different kind
10729   // or instruction which has a different base pointer.
10730   unsigned Seq = 0;
10731   StoreSDNode *Index = St;
10732   while (Index) {
10733     // If the chain has more than one use, then we can't reorder the mem ops.
10734     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10735       break;
10736
10737     // Find the base pointer and offset for this memory node.
10738     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10739
10740     // Check that the base pointer is the same as the original one.
10741     if (!Ptr.equalBaseIndex(BasePtr))
10742       break;
10743
10744     // The memory operands must not be volatile.
10745     if (Index->isVolatile() || Index->isIndexed())
10746       break;
10747
10748     // No truncation.
10749     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10750       if (St->isTruncatingStore())
10751         break;
10752
10753     // The stored memory type must be the same.
10754     if (Index->getMemoryVT() != MemVT)
10755       break;
10756
10757     // We found a potential memory operand to merge.
10758     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10759
10760     // Find the next memory operand in the chain. If the next operand in the
10761     // chain is a store then move up and continue the scan with the next
10762     // memory operand. If the next operand is a load save it and use alias
10763     // information to check if it interferes with anything.
10764     SDNode *NextInChain = Index->getChain().getNode();
10765     while (1) {
10766       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10767         // We found a store node. Use it for the next iteration.
10768         Index = STn;
10769         break;
10770       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10771         if (Ldn->isVolatile()) {
10772           Index = nullptr;
10773           break;
10774         }
10775
10776         // Save the load node for later. Continue the scan.
10777         AliasLoadNodes.push_back(Ldn);
10778         NextInChain = Ldn->getChain().getNode();
10779         continue;
10780       } else {
10781         Index = nullptr;
10782         break;
10783       }
10784     }
10785   }
10786
10787   // Check if there is anything to merge.
10788   if (StoreNodes.size() < 2)
10789     return false;
10790
10791   // Sort the memory operands according to their distance from the base pointer.
10792   std::sort(StoreNodes.begin(), StoreNodes.end(),
10793             [](MemOpLink LHS, MemOpLink RHS) {
10794     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10795            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10796             LHS.SequenceNum > RHS.SequenceNum);
10797   });
10798
10799   // Scan the memory operations on the chain and find the first non-consecutive
10800   // store memory address.
10801   unsigned LastConsecutiveStore = 0;
10802   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10803   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10804
10805     // Check that the addresses are consecutive starting from the second
10806     // element in the list of stores.
10807     if (i > 0) {
10808       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10809       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10810         break;
10811     }
10812
10813     bool Alias = false;
10814     // Check if this store interferes with any of the loads that we found.
10815     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10816       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10817         Alias = true;
10818         break;
10819       }
10820     // We found a load that alias with this store. Stop the sequence.
10821     if (Alias)
10822       break;
10823
10824     // Mark this node as useful.
10825     LastConsecutiveStore = i;
10826   }
10827
10828   // The node with the lowest store address.
10829   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10830   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10831   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10832
10833   // Store the constants into memory as one consecutive store.
10834   if (IsConstantSrc) {
10835     unsigned LastLegalType = 0;
10836     unsigned LastLegalVectorType = 0;
10837     bool NonZero = false;
10838     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10839       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10840       SDValue StoredVal = St->getValue();
10841
10842       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10843         NonZero |= !C->isNullValue();
10844       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10845         NonZero |= !C->getConstantFPValue()->isNullValue();
10846       } else {
10847         // Non-constant.
10848         break;
10849       }
10850
10851       // Find a legal type for the constant store.
10852       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10853       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10854       if (TLI.isTypeLegal(StoreTy) &&
10855           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10856                              FirstStoreAlign)) {
10857         LastLegalType = i+1;
10858       // Or check whether a truncstore is legal.
10859       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10860                  TargetLowering::TypePromoteInteger) {
10861         EVT LegalizedStoredValueTy =
10862           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10863         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10864             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10865                                FirstStoreAlign)) {
10866           LastLegalType = i + 1;
10867         }
10868       }
10869
10870       // Find a legal type for the vector store.
10871       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10872       if (TLI.isTypeLegal(Ty) &&
10873           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10874         LastLegalVectorType = i + 1;
10875       }
10876     }
10877
10878     // We only use vectors if the constant is known to be zero and the
10879     // function is not marked with the noimplicitfloat attribute.
10880     if (NonZero || NoVectors)
10881       LastLegalVectorType = 0;
10882
10883     // Check if we found a legal integer type to store.
10884     if (LastLegalType == 0 && LastLegalVectorType == 0)
10885       return false;
10886
10887     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10888     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10889
10890     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10891                                            true, UseVector);
10892   }
10893
10894   // When extracting multiple vector elements, try to store them
10895   // in one vector store rather than a sequence of scalar stores.
10896   if (IsExtractVecEltSrc) {
10897     unsigned NumElem = 0;
10898     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10899       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10900       SDValue StoredVal = St->getValue();
10901       // This restriction could be loosened.
10902       // Bail out if any stored values are not elements extracted from a vector.
10903       // It should be possible to handle mixed sources, but load sources need
10904       // more careful handling (see the block of code below that handles
10905       // consecutive loads).
10906       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10907         return false;
10908
10909       // Find a legal type for the vector store.
10910       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10911       if (TLI.isTypeLegal(Ty) &&
10912           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10913         NumElem = i + 1;
10914     }
10915
10916     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10917                                            false, true);
10918   }
10919
10920   // Below we handle the case of multiple consecutive stores that
10921   // come from multiple consecutive loads. We merge them into a single
10922   // wide load and a single wide store.
10923
10924   // Look for load nodes which are used by the stored values.
10925   SmallVector<MemOpLink, 8> LoadNodes;
10926
10927   // Find acceptable loads. Loads need to have the same chain (token factor),
10928   // must not be zext, volatile, indexed, and they must be consecutive.
10929   BaseIndexOffset LdBasePtr;
10930   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10931     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10932     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10933     if (!Ld) break;
10934
10935     // Loads must only have one use.
10936     if (!Ld->hasNUsesOfValue(1, 0))
10937       break;
10938
10939     // The memory operands must not be volatile.
10940     if (Ld->isVolatile() || Ld->isIndexed())
10941       break;
10942
10943     // We do not accept ext loads.
10944     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10945       break;
10946
10947     // The stored memory type must be the same.
10948     if (Ld->getMemoryVT() != MemVT)
10949       break;
10950
10951     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10952     // If this is not the first ptr that we check.
10953     if (LdBasePtr.Base.getNode()) {
10954       // The base ptr must be the same.
10955       if (!LdPtr.equalBaseIndex(LdBasePtr))
10956         break;
10957     } else {
10958       // Check that all other base pointers are the same as this one.
10959       LdBasePtr = LdPtr;
10960     }
10961
10962     // We found a potential memory operand to merge.
10963     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10964   }
10965
10966   if (LoadNodes.size() < 2)
10967     return false;
10968
10969   // If we have load/store pair instructions and we only have two values,
10970   // don't bother.
10971   unsigned RequiredAlignment;
10972   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10973       St->getAlignment() >= RequiredAlignment)
10974     return false;
10975
10976   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10977   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10978   unsigned FirstLoadAlign = FirstLoad->getAlignment();
10979
10980   // Scan the memory operations on the chain and find the first non-consecutive
10981   // load memory address. These variables hold the index in the store node
10982   // array.
10983   unsigned LastConsecutiveLoad = 0;
10984   // This variable refers to the size and not index in the array.
10985   unsigned LastLegalVectorType = 0;
10986   unsigned LastLegalIntegerType = 0;
10987   StartAddress = LoadNodes[0].OffsetFromBase;
10988   SDValue FirstChain = FirstLoad->getChain();
10989   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10990     // All loads much share the same chain.
10991     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10992       break;
10993
10994     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10995     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10996       break;
10997     LastConsecutiveLoad = i;
10998
10999     // Find a legal type for the vector store.
11000     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11001     if (TLI.isTypeLegal(StoreTy) &&
11002         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11003         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11004       LastLegalVectorType = i + 1;
11005     }
11006
11007     // Find a legal type for the integer store.
11008     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11009     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11010     if (TLI.isTypeLegal(StoreTy) &&
11011         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11012         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11013       LastLegalIntegerType = i + 1;
11014     // Or check whether a truncstore and extload is legal.
11015     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11016              TargetLowering::TypePromoteInteger) {
11017       EVT LegalizedStoredValueTy =
11018         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11019       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11020           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11021           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11022           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11023           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11024                              FirstStoreAlign) &&
11025           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11026                              FirstLoadAlign))
11027         LastLegalIntegerType = i+1;
11028     }
11029   }
11030
11031   // Only use vector types if the vector type is larger than the integer type.
11032   // If they are the same, use integers.
11033   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11034   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11035
11036   // We add +1 here because the LastXXX variables refer to location while
11037   // the NumElem refers to array/index size.
11038   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11039   NumElem = std::min(LastLegalType, NumElem);
11040
11041   if (NumElem < 2)
11042     return false;
11043
11044   // The latest Node in the DAG.
11045   unsigned LatestNodeUsed = 0;
11046   for (unsigned i=1; i<NumElem; ++i) {
11047     // Find a chain for the new wide-store operand. Notice that some
11048     // of the store nodes that we found may not be selected for inclusion
11049     // in the wide store. The chain we use needs to be the chain of the
11050     // latest store node which is *used* and replaced by the wide store.
11051     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11052       LatestNodeUsed = i;
11053   }
11054
11055   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11056
11057   // Find if it is better to use vectors or integers to load and store
11058   // to memory.
11059   EVT JointMemOpVT;
11060   if (UseVectorTy) {
11061     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11062   } else {
11063     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11064     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11065   }
11066
11067   SDLoc LoadDL(LoadNodes[0].MemNode);
11068   SDLoc StoreDL(StoreNodes[0].MemNode);
11069
11070   SDValue NewLoad = DAG.getLoad(
11071       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11072       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11073
11074   SDValue NewStore = DAG.getStore(
11075       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11076       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11077
11078   // Replace one of the loads with the new load.
11079   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11080   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11081                                 SDValue(NewLoad.getNode(), 1));
11082
11083   // Remove the rest of the load chains.
11084   for (unsigned i = 1; i < NumElem ; ++i) {
11085     // Replace all chain users of the old load nodes with the chain of the new
11086     // load node.
11087     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11088     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11089   }
11090
11091   // Replace the last store with the new store.
11092   CombineTo(LatestOp, NewStore);
11093   // Erase all other stores.
11094   for (unsigned i = 0; i < NumElem ; ++i) {
11095     // Remove all Store nodes.
11096     if (StoreNodes[i].MemNode == LatestOp)
11097       continue;
11098     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11099     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11100     deleteAndRecombine(St);
11101   }
11102
11103   return true;
11104 }
11105
11106 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11107   StoreSDNode *ST  = cast<StoreSDNode>(N);
11108   SDValue Chain = ST->getChain();
11109   SDValue Value = ST->getValue();
11110   SDValue Ptr   = ST->getBasePtr();
11111
11112   // If this is a store of a bit convert, store the input value if the
11113   // resultant store does not need a higher alignment than the original.
11114   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11115       ST->isUnindexed()) {
11116     unsigned OrigAlign = ST->getAlignment();
11117     EVT SVT = Value.getOperand(0).getValueType();
11118     unsigned Align = TLI.getDataLayout()->
11119       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11120     if (Align <= OrigAlign &&
11121         ((!LegalOperations && !ST->isVolatile()) ||
11122          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11123       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11124                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11125                           ST->isNonTemporal(), OrigAlign,
11126                           ST->getAAInfo());
11127   }
11128
11129   // Turn 'store undef, Ptr' -> nothing.
11130   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11131     return Chain;
11132
11133   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11134   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11135     // NOTE: If the original store is volatile, this transform must not increase
11136     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11137     // processor operation but an i64 (which is not legal) requires two.  So the
11138     // transform should not be done in this case.
11139     if (Value.getOpcode() != ISD::TargetConstantFP) {
11140       SDValue Tmp;
11141       switch (CFP->getSimpleValueType(0).SimpleTy) {
11142       default: llvm_unreachable("Unknown FP type");
11143       case MVT::f16:    // We don't do this for these yet.
11144       case MVT::f80:
11145       case MVT::f128:
11146       case MVT::ppcf128:
11147         break;
11148       case MVT::f32:
11149         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11150             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11151           ;
11152           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11153                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11154                               MVT::i32);
11155           return DAG.getStore(Chain, SDLoc(N), Tmp,
11156                               Ptr, ST->getMemOperand());
11157         }
11158         break;
11159       case MVT::f64:
11160         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11161              !ST->isVolatile()) ||
11162             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11163           ;
11164           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11165                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11166           return DAG.getStore(Chain, SDLoc(N), Tmp,
11167                               Ptr, ST->getMemOperand());
11168         }
11169
11170         if (!ST->isVolatile() &&
11171             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11172           // Many FP stores are not made apparent until after legalize, e.g. for
11173           // argument passing.  Since this is so common, custom legalize the
11174           // 64-bit integer store into two 32-bit stores.
11175           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11176           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11177           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11178           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11179
11180           unsigned Alignment = ST->getAlignment();
11181           bool isVolatile = ST->isVolatile();
11182           bool isNonTemporal = ST->isNonTemporal();
11183           AAMDNodes AAInfo = ST->getAAInfo();
11184
11185           SDLoc DL(N);
11186
11187           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11188                                      Ptr, ST->getPointerInfo(),
11189                                      isVolatile, isNonTemporal,
11190                                      ST->getAlignment(), AAInfo);
11191           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11192                             DAG.getConstant(4, DL, Ptr.getValueType()));
11193           Alignment = MinAlign(Alignment, 4U);
11194           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11195                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11196                                      isVolatile, isNonTemporal,
11197                                      Alignment, AAInfo);
11198           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11199                              St0, St1);
11200         }
11201
11202         break;
11203       }
11204     }
11205   }
11206
11207   // Try to infer better alignment information than the store already has.
11208   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11209     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11210       if (Align > ST->getAlignment()) {
11211         SDValue NewStore =
11212                DAG.getTruncStore(Chain, SDLoc(N), Value,
11213                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11214                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11215                                  ST->getAAInfo());
11216         if (NewStore.getNode() != N)
11217           return CombineTo(ST, NewStore, true);
11218       }
11219     }
11220   }
11221
11222   // Try transforming a pair floating point load / store ops to integer
11223   // load / store ops.
11224   SDValue NewST = TransformFPLoadStorePair(N);
11225   if (NewST.getNode())
11226     return NewST;
11227
11228   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11229                                                   : DAG.getSubtarget().useAA();
11230 #ifndef NDEBUG
11231   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11232       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11233     UseAA = false;
11234 #endif
11235   if (UseAA && ST->isUnindexed()) {
11236     // Walk up chain skipping non-aliasing memory nodes.
11237     SDValue BetterChain = FindBetterChain(N, Chain);
11238
11239     // If there is a better chain.
11240     if (Chain != BetterChain) {
11241       SDValue ReplStore;
11242
11243       // Replace the chain to avoid dependency.
11244       if (ST->isTruncatingStore()) {
11245         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11246                                       ST->getMemoryVT(), ST->getMemOperand());
11247       } else {
11248         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11249                                  ST->getMemOperand());
11250       }
11251
11252       // Create token to keep both nodes around.
11253       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11254                                   MVT::Other, Chain, ReplStore);
11255
11256       // Make sure the new and old chains are cleaned up.
11257       AddToWorklist(Token.getNode());
11258
11259       // Don't add users to work list.
11260       return CombineTo(N, Token, false);
11261     }
11262   }
11263
11264   // Try transforming N to an indexed store.
11265   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11266     return SDValue(N, 0);
11267
11268   // FIXME: is there such a thing as a truncating indexed store?
11269   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11270       Value.getValueType().isInteger()) {
11271     // See if we can simplify the input to this truncstore with knowledge that
11272     // only the low bits are being used.  For example:
11273     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11274     SDValue Shorter =
11275       GetDemandedBits(Value,
11276                       APInt::getLowBitsSet(
11277                         Value.getValueType().getScalarType().getSizeInBits(),
11278                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11279     AddToWorklist(Value.getNode());
11280     if (Shorter.getNode())
11281       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11282                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11283
11284     // Otherwise, see if we can simplify the operation with
11285     // SimplifyDemandedBits, which only works if the value has a single use.
11286     if (SimplifyDemandedBits(Value,
11287                         APInt::getLowBitsSet(
11288                           Value.getValueType().getScalarType().getSizeInBits(),
11289                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11290       return SDValue(N, 0);
11291   }
11292
11293   // If this is a load followed by a store to the same location, then the store
11294   // is dead/noop.
11295   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11296     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11297         ST->isUnindexed() && !ST->isVolatile() &&
11298         // There can't be any side effects between the load and store, such as
11299         // a call or store.
11300         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11301       // The store is dead, remove it.
11302       return Chain;
11303     }
11304   }
11305
11306   // If this is a store followed by a store with the same value to the same
11307   // location, then the store is dead/noop.
11308   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11309     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11310         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11311         ST1->isUnindexed() && !ST1->isVolatile()) {
11312       // The store is dead, remove it.
11313       return Chain;
11314     }
11315   }
11316
11317   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11318   // truncating store.  We can do this even if this is already a truncstore.
11319   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11320       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11321       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11322                             ST->getMemoryVT())) {
11323     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11324                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11325   }
11326
11327   // Only perform this optimization before the types are legal, because we
11328   // don't want to perform this optimization on every DAGCombine invocation.
11329   if (!LegalTypes) {
11330     bool EverChanged = false;
11331
11332     do {
11333       // There can be multiple store sequences on the same chain.
11334       // Keep trying to merge store sequences until we are unable to do so
11335       // or until we merge the last store on the chain.
11336       bool Changed = MergeConsecutiveStores(ST);
11337       EverChanged |= Changed;
11338       if (!Changed) break;
11339     } while (ST->getOpcode() != ISD::DELETED_NODE);
11340
11341     if (EverChanged)
11342       return SDValue(N, 0);
11343   }
11344
11345   return ReduceLoadOpStoreWidth(N);
11346 }
11347
11348 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11349   SDValue InVec = N->getOperand(0);
11350   SDValue InVal = N->getOperand(1);
11351   SDValue EltNo = N->getOperand(2);
11352   SDLoc dl(N);
11353
11354   // If the inserted element is an UNDEF, just use the input vector.
11355   if (InVal.getOpcode() == ISD::UNDEF)
11356     return InVec;
11357
11358   EVT VT = InVec.getValueType();
11359
11360   // If we can't generate a legal BUILD_VECTOR, exit
11361   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11362     return SDValue();
11363
11364   // Check that we know which element is being inserted
11365   if (!isa<ConstantSDNode>(EltNo))
11366     return SDValue();
11367   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11368
11369   // Canonicalize insert_vector_elt dag nodes.
11370   // Example:
11371   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11372   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11373   //
11374   // Do this only if the child insert_vector node has one use; also
11375   // do this only if indices are both constants and Idx1 < Idx0.
11376   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11377       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11378     unsigned OtherElt =
11379       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11380     if (Elt < OtherElt) {
11381       // Swap nodes.
11382       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11383                                   InVec.getOperand(0), InVal, EltNo);
11384       AddToWorklist(NewOp.getNode());
11385       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11386                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11387     }
11388   }
11389
11390   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11391   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11392   // vector elements.
11393   SmallVector<SDValue, 8> Ops;
11394   // Do not combine these two vectors if the output vector will not replace
11395   // the input vector.
11396   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11397     Ops.append(InVec.getNode()->op_begin(),
11398                InVec.getNode()->op_end());
11399   } else if (InVec.getOpcode() == ISD::UNDEF) {
11400     unsigned NElts = VT.getVectorNumElements();
11401     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11402   } else {
11403     return SDValue();
11404   }
11405
11406   // Insert the element
11407   if (Elt < Ops.size()) {
11408     // All the operands of BUILD_VECTOR must have the same type;
11409     // we enforce that here.
11410     EVT OpVT = Ops[0].getValueType();
11411     if (InVal.getValueType() != OpVT)
11412       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11413                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11414                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11415     Ops[Elt] = InVal;
11416   }
11417
11418   // Return the new vector
11419   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11420 }
11421
11422 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11423     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11424   EVT ResultVT = EVE->getValueType(0);
11425   EVT VecEltVT = InVecVT.getVectorElementType();
11426   unsigned Align = OriginalLoad->getAlignment();
11427   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11428       VecEltVT.getTypeForEVT(*DAG.getContext()));
11429
11430   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11431     return SDValue();
11432
11433   Align = NewAlign;
11434
11435   SDValue NewPtr = OriginalLoad->getBasePtr();
11436   SDValue Offset;
11437   EVT PtrType = NewPtr.getValueType();
11438   MachinePointerInfo MPI;
11439   SDLoc DL(EVE);
11440   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11441     int Elt = ConstEltNo->getZExtValue();
11442     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11443     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11444     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11445   } else {
11446     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11447     Offset = DAG.getNode(
11448         ISD::MUL, DL, PtrType, Offset,
11449         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11450     MPI = OriginalLoad->getPointerInfo();
11451   }
11452   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11453
11454   // The replacement we need to do here is a little tricky: we need to
11455   // replace an extractelement of a load with a load.
11456   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11457   // Note that this replacement assumes that the extractvalue is the only
11458   // use of the load; that's okay because we don't want to perform this
11459   // transformation in other cases anyway.
11460   SDValue Load;
11461   SDValue Chain;
11462   if (ResultVT.bitsGT(VecEltVT)) {
11463     // If the result type of vextract is wider than the load, then issue an
11464     // extending load instead.
11465     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11466                                                   VecEltVT)
11467                                    ? ISD::ZEXTLOAD
11468                                    : ISD::EXTLOAD;
11469     Load = DAG.getExtLoad(
11470         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11471         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11472         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11473     Chain = Load.getValue(1);
11474   } else {
11475     Load = DAG.getLoad(
11476         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11477         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11478         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11479     Chain = Load.getValue(1);
11480     if (ResultVT.bitsLT(VecEltVT))
11481       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11482     else
11483       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11484   }
11485   WorklistRemover DeadNodes(*this);
11486   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11487   SDValue To[] = { Load, Chain };
11488   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11489   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11490   // worklist explicitly as well.
11491   AddToWorklist(Load.getNode());
11492   AddUsersToWorklist(Load.getNode()); // Add users too
11493   // Make sure to revisit this node to clean it up; it will usually be dead.
11494   AddToWorklist(EVE);
11495   ++OpsNarrowed;
11496   return SDValue(EVE, 0);
11497 }
11498
11499 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11500   // (vextract (scalar_to_vector val, 0) -> val
11501   SDValue InVec = N->getOperand(0);
11502   EVT VT = InVec.getValueType();
11503   EVT NVT = N->getValueType(0);
11504
11505   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11506     // Check if the result type doesn't match the inserted element type. A
11507     // SCALAR_TO_VECTOR may truncate the inserted element and the
11508     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11509     SDValue InOp = InVec.getOperand(0);
11510     if (InOp.getValueType() != NVT) {
11511       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11512       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11513     }
11514     return InOp;
11515   }
11516
11517   SDValue EltNo = N->getOperand(1);
11518   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11519
11520   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11521   // We only perform this optimization before the op legalization phase because
11522   // we may introduce new vector instructions which are not backed by TD
11523   // patterns. For example on AVX, extracting elements from a wide vector
11524   // without using extract_subvector. However, if we can find an underlying
11525   // scalar value, then we can always use that.
11526   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11527       && ConstEltNo) {
11528     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11529     int NumElem = VT.getVectorNumElements();
11530     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11531     // Find the new index to extract from.
11532     int OrigElt = SVOp->getMaskElt(Elt);
11533
11534     // Extracting an undef index is undef.
11535     if (OrigElt == -1)
11536       return DAG.getUNDEF(NVT);
11537
11538     // Select the right vector half to extract from.
11539     SDValue SVInVec;
11540     if (OrigElt < NumElem) {
11541       SVInVec = InVec->getOperand(0);
11542     } else {
11543       SVInVec = InVec->getOperand(1);
11544       OrigElt -= NumElem;
11545     }
11546
11547     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11548       SDValue InOp = SVInVec.getOperand(OrigElt);
11549       if (InOp.getValueType() != NVT) {
11550         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11551         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11552       }
11553
11554       return InOp;
11555     }
11556
11557     // FIXME: We should handle recursing on other vector shuffles and
11558     // scalar_to_vector here as well.
11559
11560     if (!LegalOperations) {
11561       EVT IndexTy = TLI.getVectorIdxTy();
11562       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11563                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11564     }
11565   }
11566
11567   bool BCNumEltsChanged = false;
11568   EVT ExtVT = VT.getVectorElementType();
11569   EVT LVT = ExtVT;
11570
11571   // If the result of load has to be truncated, then it's not necessarily
11572   // profitable.
11573   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11574     return SDValue();
11575
11576   if (InVec.getOpcode() == ISD::BITCAST) {
11577     // Don't duplicate a load with other uses.
11578     if (!InVec.hasOneUse())
11579       return SDValue();
11580
11581     EVT BCVT = InVec.getOperand(0).getValueType();
11582     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11583       return SDValue();
11584     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11585       BCNumEltsChanged = true;
11586     InVec = InVec.getOperand(0);
11587     ExtVT = BCVT.getVectorElementType();
11588   }
11589
11590   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11591   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11592       ISD::isNormalLoad(InVec.getNode()) &&
11593       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11594     SDValue Index = N->getOperand(1);
11595     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11596       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11597                                                            OrigLoad);
11598   }
11599
11600   // Perform only after legalization to ensure build_vector / vector_shuffle
11601   // optimizations have already been done.
11602   if (!LegalOperations) return SDValue();
11603
11604   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11605   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11606   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11607
11608   if (ConstEltNo) {
11609     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11610
11611     LoadSDNode *LN0 = nullptr;
11612     const ShuffleVectorSDNode *SVN = nullptr;
11613     if (ISD::isNormalLoad(InVec.getNode())) {
11614       LN0 = cast<LoadSDNode>(InVec);
11615     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11616                InVec.getOperand(0).getValueType() == ExtVT &&
11617                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11618       // Don't duplicate a load with other uses.
11619       if (!InVec.hasOneUse())
11620         return SDValue();
11621
11622       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11623     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11624       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11625       // =>
11626       // (load $addr+1*size)
11627
11628       // Don't duplicate a load with other uses.
11629       if (!InVec.hasOneUse())
11630         return SDValue();
11631
11632       // If the bit convert changed the number of elements, it is unsafe
11633       // to examine the mask.
11634       if (BCNumEltsChanged)
11635         return SDValue();
11636
11637       // Select the input vector, guarding against out of range extract vector.
11638       unsigned NumElems = VT.getVectorNumElements();
11639       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11640       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11641
11642       if (InVec.getOpcode() == ISD::BITCAST) {
11643         // Don't duplicate a load with other uses.
11644         if (!InVec.hasOneUse())
11645           return SDValue();
11646
11647         InVec = InVec.getOperand(0);
11648       }
11649       if (ISD::isNormalLoad(InVec.getNode())) {
11650         LN0 = cast<LoadSDNode>(InVec);
11651         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11652         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11653       }
11654     }
11655
11656     // Make sure we found a non-volatile load and the extractelement is
11657     // the only use.
11658     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11659       return SDValue();
11660
11661     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11662     if (Elt == -1)
11663       return DAG.getUNDEF(LVT);
11664
11665     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11666   }
11667
11668   return SDValue();
11669 }
11670
11671 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11672 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11673   // We perform this optimization post type-legalization because
11674   // the type-legalizer often scalarizes integer-promoted vectors.
11675   // Performing this optimization before may create bit-casts which
11676   // will be type-legalized to complex code sequences.
11677   // We perform this optimization only before the operation legalizer because we
11678   // may introduce illegal operations.
11679   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11680     return SDValue();
11681
11682   unsigned NumInScalars = N->getNumOperands();
11683   SDLoc dl(N);
11684   EVT VT = N->getValueType(0);
11685
11686   // Check to see if this is a BUILD_VECTOR of a bunch of values
11687   // which come from any_extend or zero_extend nodes. If so, we can create
11688   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11689   // optimizations. We do not handle sign-extend because we can't fill the sign
11690   // using shuffles.
11691   EVT SourceType = MVT::Other;
11692   bool AllAnyExt = true;
11693
11694   for (unsigned i = 0; i != NumInScalars; ++i) {
11695     SDValue In = N->getOperand(i);
11696     // Ignore undef inputs.
11697     if (In.getOpcode() == ISD::UNDEF) continue;
11698
11699     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11700     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11701
11702     // Abort if the element is not an extension.
11703     if (!ZeroExt && !AnyExt) {
11704       SourceType = MVT::Other;
11705       break;
11706     }
11707
11708     // The input is a ZeroExt or AnyExt. Check the original type.
11709     EVT InTy = In.getOperand(0).getValueType();
11710
11711     // Check that all of the widened source types are the same.
11712     if (SourceType == MVT::Other)
11713       // First time.
11714       SourceType = InTy;
11715     else if (InTy != SourceType) {
11716       // Multiple income types. Abort.
11717       SourceType = MVT::Other;
11718       break;
11719     }
11720
11721     // Check if all of the extends are ANY_EXTENDs.
11722     AllAnyExt &= AnyExt;
11723   }
11724
11725   // In order to have valid types, all of the inputs must be extended from the
11726   // same source type and all of the inputs must be any or zero extend.
11727   // Scalar sizes must be a power of two.
11728   EVT OutScalarTy = VT.getScalarType();
11729   bool ValidTypes = SourceType != MVT::Other &&
11730                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11731                  isPowerOf2_32(SourceType.getSizeInBits());
11732
11733   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11734   // turn into a single shuffle instruction.
11735   if (!ValidTypes)
11736     return SDValue();
11737
11738   bool isLE = TLI.isLittleEndian();
11739   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11740   assert(ElemRatio > 1 && "Invalid element size ratio");
11741   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11742                                DAG.getConstant(0, SDLoc(N), SourceType);
11743
11744   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11745   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11746
11747   // Populate the new build_vector
11748   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11749     SDValue Cast = N->getOperand(i);
11750     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11751             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11752             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11753     SDValue In;
11754     if (Cast.getOpcode() == ISD::UNDEF)
11755       In = DAG.getUNDEF(SourceType);
11756     else
11757       In = Cast->getOperand(0);
11758     unsigned Index = isLE ? (i * ElemRatio) :
11759                             (i * ElemRatio + (ElemRatio - 1));
11760
11761     assert(Index < Ops.size() && "Invalid index");
11762     Ops[Index] = In;
11763   }
11764
11765   // The type of the new BUILD_VECTOR node.
11766   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11767   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11768          "Invalid vector size");
11769   // Check if the new vector type is legal.
11770   if (!isTypeLegal(VecVT)) return SDValue();
11771
11772   // Make the new BUILD_VECTOR.
11773   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11774
11775   // The new BUILD_VECTOR node has the potential to be further optimized.
11776   AddToWorklist(BV.getNode());
11777   // Bitcast to the desired type.
11778   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11779 }
11780
11781 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11782   EVT VT = N->getValueType(0);
11783
11784   unsigned NumInScalars = N->getNumOperands();
11785   SDLoc dl(N);
11786
11787   EVT SrcVT = MVT::Other;
11788   unsigned Opcode = ISD::DELETED_NODE;
11789   unsigned NumDefs = 0;
11790
11791   for (unsigned i = 0; i != NumInScalars; ++i) {
11792     SDValue In = N->getOperand(i);
11793     unsigned Opc = In.getOpcode();
11794
11795     if (Opc == ISD::UNDEF)
11796       continue;
11797
11798     // If all scalar values are floats and converted from integers.
11799     if (Opcode == ISD::DELETED_NODE &&
11800         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11801       Opcode = Opc;
11802     }
11803
11804     if (Opc != Opcode)
11805       return SDValue();
11806
11807     EVT InVT = In.getOperand(0).getValueType();
11808
11809     // If all scalar values are typed differently, bail out. It's chosen to
11810     // simplify BUILD_VECTOR of integer types.
11811     if (SrcVT == MVT::Other)
11812       SrcVT = InVT;
11813     if (SrcVT != InVT)
11814       return SDValue();
11815     NumDefs++;
11816   }
11817
11818   // If the vector has just one element defined, it's not worth to fold it into
11819   // a vectorized one.
11820   if (NumDefs < 2)
11821     return SDValue();
11822
11823   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11824          && "Should only handle conversion from integer to float.");
11825   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11826
11827   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11828
11829   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11830     return SDValue();
11831
11832   // Just because the floating-point vector type is legal does not necessarily
11833   // mean that the corresponding integer vector type is.
11834   if (!isTypeLegal(NVT))
11835     return SDValue();
11836
11837   SmallVector<SDValue, 8> Opnds;
11838   for (unsigned i = 0; i != NumInScalars; ++i) {
11839     SDValue In = N->getOperand(i);
11840
11841     if (In.getOpcode() == ISD::UNDEF)
11842       Opnds.push_back(DAG.getUNDEF(SrcVT));
11843     else
11844       Opnds.push_back(In.getOperand(0));
11845   }
11846   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11847   AddToWorklist(BV.getNode());
11848
11849   return DAG.getNode(Opcode, dl, VT, BV);
11850 }
11851
11852 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11853   unsigned NumInScalars = N->getNumOperands();
11854   SDLoc dl(N);
11855   EVT VT = N->getValueType(0);
11856
11857   // A vector built entirely of undefs is undef.
11858   if (ISD::allOperandsUndef(N))
11859     return DAG.getUNDEF(VT);
11860
11861   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11862     return V;
11863
11864   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11865     return V;
11866
11867   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11868   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11869   // at most two distinct vectors, turn this into a shuffle node.
11870
11871   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11872   if (!isTypeLegal(VT))
11873     return SDValue();
11874
11875   // May only combine to shuffle after legalize if shuffle is legal.
11876   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11877     return SDValue();
11878
11879   SDValue VecIn1, VecIn2;
11880   bool UsesZeroVector = false;
11881   for (unsigned i = 0; i != NumInScalars; ++i) {
11882     SDValue Op = N->getOperand(i);
11883     // Ignore undef inputs.
11884     if (Op.getOpcode() == ISD::UNDEF) continue;
11885
11886     // See if we can combine this build_vector into a blend with a zero vector.
11887     if (!VecIn2.getNode() && (isNullConstant(Op) ||
11888         (Op.getOpcode() == ISD::ConstantFP &&
11889         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11890       UsesZeroVector = true;
11891       continue;
11892     }
11893
11894     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11895     // constant index, bail out.
11896     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11897         !isa<ConstantSDNode>(Op.getOperand(1))) {
11898       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11899       break;
11900     }
11901
11902     // We allow up to two distinct input vectors.
11903     SDValue ExtractedFromVec = Op.getOperand(0);
11904     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11905       continue;
11906
11907     if (!VecIn1.getNode()) {
11908       VecIn1 = ExtractedFromVec;
11909     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11910       VecIn2 = ExtractedFromVec;
11911     } else {
11912       // Too many inputs.
11913       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11914       break;
11915     }
11916   }
11917
11918   // If everything is good, we can make a shuffle operation.
11919   if (VecIn1.getNode()) {
11920     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11921     SmallVector<int, 8> Mask;
11922     for (unsigned i = 0; i != NumInScalars; ++i) {
11923       unsigned Opcode = N->getOperand(i).getOpcode();
11924       if (Opcode == ISD::UNDEF) {
11925         Mask.push_back(-1);
11926         continue;
11927       }
11928
11929       // Operands can also be zero.
11930       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11931         assert(UsesZeroVector &&
11932                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11933                "Unexpected node found!");
11934         Mask.push_back(NumInScalars+i);
11935         continue;
11936       }
11937
11938       // If extracting from the first vector, just use the index directly.
11939       SDValue Extract = N->getOperand(i);
11940       SDValue ExtVal = Extract.getOperand(1);
11941       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11942       if (Extract.getOperand(0) == VecIn1) {
11943         Mask.push_back(ExtIndex);
11944         continue;
11945       }
11946
11947       // Otherwise, use InIdx + InputVecSize
11948       Mask.push_back(InNumElements + ExtIndex);
11949     }
11950
11951     // Avoid introducing illegal shuffles with zero.
11952     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11953       return SDValue();
11954
11955     // We can't generate a shuffle node with mismatched input and output types.
11956     // Attempt to transform a single input vector to the correct type.
11957     if ((VT != VecIn1.getValueType())) {
11958       // If the input vector type has a different base type to the output
11959       // vector type, bail out.
11960       EVT VTElemType = VT.getVectorElementType();
11961       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11962           (VecIn2.getNode() &&
11963            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11964         return SDValue();
11965
11966       // If the input vector is too small, widen it.
11967       // We only support widening of vectors which are half the size of the
11968       // output registers. For example XMM->YMM widening on X86 with AVX.
11969       EVT VecInT = VecIn1.getValueType();
11970       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11971         // If we only have one small input, widen it by adding undef values.
11972         if (!VecIn2.getNode())
11973           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11974                                DAG.getUNDEF(VecIn1.getValueType()));
11975         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11976           // If we have two small inputs of the same type, try to concat them.
11977           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11978           VecIn2 = SDValue(nullptr, 0);
11979         } else
11980           return SDValue();
11981       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11982         // If the input vector is too large, try to split it.
11983         // We don't support having two input vectors that are too large.
11984         // If the zero vector was used, we can not split the vector,
11985         // since we'd need 3 inputs.
11986         if (UsesZeroVector || VecIn2.getNode())
11987           return SDValue();
11988
11989         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11990           return SDValue();
11991
11992         // Try to replace VecIn1 with two extract_subvectors
11993         // No need to update the masks, they should still be correct.
11994         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11995           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11996         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11997           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11998       } else
11999         return SDValue();
12000     }
12001
12002     if (UsesZeroVector)
12003       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12004                                 DAG.getConstantFP(0.0, dl, VT);
12005     else
12006       // If VecIn2 is unused then change it to undef.
12007       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12008
12009     // Check that we were able to transform all incoming values to the same
12010     // type.
12011     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12012         VecIn1.getValueType() != VT)
12013           return SDValue();
12014
12015     // Return the new VECTOR_SHUFFLE node.
12016     SDValue Ops[2];
12017     Ops[0] = VecIn1;
12018     Ops[1] = VecIn2;
12019     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12020   }
12021
12022   return SDValue();
12023 }
12024
12025 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12027   EVT OpVT = N->getOperand(0).getValueType();
12028
12029   // If the operands are legal vectors, leave them alone.
12030   if (TLI.isTypeLegal(OpVT))
12031     return SDValue();
12032
12033   SDLoc DL(N);
12034   EVT VT = N->getValueType(0);
12035   SmallVector<SDValue, 8> Ops;
12036
12037   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12038   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12039
12040   // Keep track of what we encounter.
12041   bool AnyInteger = false;
12042   bool AnyFP = false;
12043   for (const SDValue &Op : N->ops()) {
12044     if (ISD::BITCAST == Op.getOpcode() &&
12045         !Op.getOperand(0).getValueType().isVector())
12046       Ops.push_back(Op.getOperand(0));
12047     else if (ISD::UNDEF == Op.getOpcode())
12048       Ops.push_back(ScalarUndef);
12049     else
12050       return SDValue();
12051
12052     // Note whether we encounter an integer or floating point scalar.
12053     // If it's neither, bail out, it could be something weird like x86mmx.
12054     EVT LastOpVT = Ops.back().getValueType();
12055     if (LastOpVT.isFloatingPoint())
12056       AnyFP = true;
12057     else if (LastOpVT.isInteger())
12058       AnyInteger = true;
12059     else
12060       return SDValue();
12061   }
12062
12063   // If any of the operands is a floating point scalar bitcast to a vector,
12064   // use floating point types throughout, and bitcast everything.  
12065   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12066   if (AnyFP) {
12067     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12068     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12069     if (AnyInteger) {
12070       for (SDValue &Op : Ops) {
12071         if (Op.getValueType() == SVT)
12072           continue;
12073         if (Op.getOpcode() == ISD::UNDEF)
12074           Op = ScalarUndef;
12075         else
12076           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12077       }
12078     }
12079   }
12080
12081   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12082                                VT.getSizeInBits() / SVT.getSizeInBits());
12083   return DAG.getNode(ISD::BITCAST, DL, VT,
12084                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12085 }
12086
12087 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12088   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12089   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12090   // inputs come from at most two distinct vectors, turn this into a shuffle
12091   // node.
12092
12093   // If we only have one input vector, we don't need to do any concatenation.
12094   if (N->getNumOperands() == 1)
12095     return N->getOperand(0);
12096
12097   // Check if all of the operands are undefs.
12098   EVT VT = N->getValueType(0);
12099   if (ISD::allOperandsUndef(N))
12100     return DAG.getUNDEF(VT);
12101
12102   // Optimize concat_vectors where all but the first of the vectors are undef.
12103   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12104         return Op.getOpcode() == ISD::UNDEF;
12105       })) {
12106     SDValue In = N->getOperand(0);
12107     assert(In.getValueType().isVector() && "Must concat vectors");
12108
12109     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12110     if (In->getOpcode() == ISD::BITCAST &&
12111         !In->getOperand(0)->getValueType(0).isVector()) {
12112       SDValue Scalar = In->getOperand(0);
12113
12114       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12115       // look through the trunc so we can still do the transform:
12116       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12117       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12118           !TLI.isTypeLegal(Scalar.getValueType()) &&
12119           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12120         Scalar = Scalar->getOperand(0);
12121
12122       EVT SclTy = Scalar->getValueType(0);
12123
12124       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12125         return SDValue();
12126
12127       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12128                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12129       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12130         return SDValue();
12131
12132       SDLoc dl = SDLoc(N);
12133       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12134       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12135     }
12136   }
12137
12138   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12139   // We have already tested above for an UNDEF only concatenation.
12140   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12141   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12142   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12143     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12144   };
12145   bool AllBuildVectorsOrUndefs =
12146       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12147   if (AllBuildVectorsOrUndefs) {
12148     SmallVector<SDValue, 8> Opnds;
12149     EVT SVT = VT.getScalarType();
12150
12151     EVT MinVT = SVT;
12152     if (!SVT.isFloatingPoint()) {
12153       // If BUILD_VECTOR are from built from integer, they may have different
12154       // operand types. Get the smallest type and truncate all operands to it.
12155       bool FoundMinVT = false;
12156       for (const SDValue &Op : N->ops())
12157         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12158           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12159           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12160           FoundMinVT = true;
12161         }
12162       assert(FoundMinVT && "Concat vector type mismatch");
12163     }
12164
12165     for (const SDValue &Op : N->ops()) {
12166       EVT OpVT = Op.getValueType();
12167       unsigned NumElts = OpVT.getVectorNumElements();
12168
12169       if (ISD::UNDEF == Op.getOpcode())
12170         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12171
12172       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12173         if (SVT.isFloatingPoint()) {
12174           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12175           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12176         } else {
12177           for (unsigned i = 0; i != NumElts; ++i)
12178             Opnds.push_back(
12179                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12180         }
12181       }
12182     }
12183
12184     assert(VT.getVectorNumElements() == Opnds.size() &&
12185            "Concat vector type mismatch");
12186     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12187   }
12188
12189   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12190   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12191     return V;
12192
12193   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12194   // nodes often generate nop CONCAT_VECTOR nodes.
12195   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12196   // place the incoming vectors at the exact same location.
12197   SDValue SingleSource = SDValue();
12198   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12199
12200   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12201     SDValue Op = N->getOperand(i);
12202
12203     if (Op.getOpcode() == ISD::UNDEF)
12204       continue;
12205
12206     // Check if this is the identity extract:
12207     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12208       return SDValue();
12209
12210     // Find the single incoming vector for the extract_subvector.
12211     if (SingleSource.getNode()) {
12212       if (Op.getOperand(0) != SingleSource)
12213         return SDValue();
12214     } else {
12215       SingleSource = Op.getOperand(0);
12216
12217       // Check the source type is the same as the type of the result.
12218       // If not, this concat may extend the vector, so we can not
12219       // optimize it away.
12220       if (SingleSource.getValueType() != N->getValueType(0))
12221         return SDValue();
12222     }
12223
12224     unsigned IdentityIndex = i * PartNumElem;
12225     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12226     // The extract index must be constant.
12227     if (!CS)
12228       return SDValue();
12229
12230     // Check that we are reading from the identity index.
12231     if (CS->getZExtValue() != IdentityIndex)
12232       return SDValue();
12233   }
12234
12235   if (SingleSource.getNode())
12236     return SingleSource;
12237
12238   return SDValue();
12239 }
12240
12241 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12242   EVT NVT = N->getValueType(0);
12243   SDValue V = N->getOperand(0);
12244
12245   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12246     // Combine:
12247     //    (extract_subvec (concat V1, V2, ...), i)
12248     // Into:
12249     //    Vi if possible
12250     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12251     // type.
12252     if (V->getOperand(0).getValueType() != NVT)
12253       return SDValue();
12254     unsigned Idx = N->getConstantOperandVal(1);
12255     unsigned NumElems = NVT.getVectorNumElements();
12256     assert((Idx % NumElems) == 0 &&
12257            "IDX in concat is not a multiple of the result vector length.");
12258     return V->getOperand(Idx / NumElems);
12259   }
12260
12261   // Skip bitcasting
12262   if (V->getOpcode() == ISD::BITCAST)
12263     V = V.getOperand(0);
12264
12265   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12266     SDLoc dl(N);
12267     // Handle only simple case where vector being inserted and vector
12268     // being extracted are of same type, and are half size of larger vectors.
12269     EVT BigVT = V->getOperand(0).getValueType();
12270     EVT SmallVT = V->getOperand(1).getValueType();
12271     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12272       return SDValue();
12273
12274     // Only handle cases where both indexes are constants with the same type.
12275     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12276     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12277
12278     if (InsIdx && ExtIdx &&
12279         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12280         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12281       // Combine:
12282       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12283       // Into:
12284       //    indices are equal or bit offsets are equal => V1
12285       //    otherwise => (extract_subvec V1, ExtIdx)
12286       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12287           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12288         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12289       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12290                          DAG.getNode(ISD::BITCAST, dl,
12291                                      N->getOperand(0).getValueType(),
12292                                      V->getOperand(0)), N->getOperand(1));
12293     }
12294   }
12295
12296   return SDValue();
12297 }
12298
12299 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12300                                                  SDValue V, SelectionDAG &DAG) {
12301   SDLoc DL(V);
12302   EVT VT = V.getValueType();
12303
12304   switch (V.getOpcode()) {
12305   default:
12306     return V;
12307
12308   case ISD::CONCAT_VECTORS: {
12309     EVT OpVT = V->getOperand(0).getValueType();
12310     int OpSize = OpVT.getVectorNumElements();
12311     SmallBitVector OpUsedElements(OpSize, false);
12312     bool FoundSimplification = false;
12313     SmallVector<SDValue, 4> NewOps;
12314     NewOps.reserve(V->getNumOperands());
12315     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12316       SDValue Op = V->getOperand(i);
12317       bool OpUsed = false;
12318       for (int j = 0; j < OpSize; ++j)
12319         if (UsedElements[i * OpSize + j]) {
12320           OpUsedElements[j] = true;
12321           OpUsed = true;
12322         }
12323       NewOps.push_back(
12324           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12325                  : DAG.getUNDEF(OpVT));
12326       FoundSimplification |= Op == NewOps.back();
12327       OpUsedElements.reset();
12328     }
12329     if (FoundSimplification)
12330       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12331     return V;
12332   }
12333
12334   case ISD::INSERT_SUBVECTOR: {
12335     SDValue BaseV = V->getOperand(0);
12336     SDValue SubV = V->getOperand(1);
12337     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12338     if (!IdxN)
12339       return V;
12340
12341     int SubSize = SubV.getValueType().getVectorNumElements();
12342     int Idx = IdxN->getZExtValue();
12343     bool SubVectorUsed = false;
12344     SmallBitVector SubUsedElements(SubSize, false);
12345     for (int i = 0; i < SubSize; ++i)
12346       if (UsedElements[i + Idx]) {
12347         SubVectorUsed = true;
12348         SubUsedElements[i] = true;
12349         UsedElements[i + Idx] = false;
12350       }
12351
12352     // Now recurse on both the base and sub vectors.
12353     SDValue SimplifiedSubV =
12354         SubVectorUsed
12355             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12356             : DAG.getUNDEF(SubV.getValueType());
12357     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12358     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12359       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12360                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12361     return V;
12362   }
12363   }
12364 }
12365
12366 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12367                                        SDValue N1, SelectionDAG &DAG) {
12368   EVT VT = SVN->getValueType(0);
12369   int NumElts = VT.getVectorNumElements();
12370   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12371   for (int M : SVN->getMask())
12372     if (M >= 0 && M < NumElts)
12373       N0UsedElements[M] = true;
12374     else if (M >= NumElts)
12375       N1UsedElements[M - NumElts] = true;
12376
12377   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12378   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12379   if (S0 == N0 && S1 == N1)
12380     return SDValue();
12381
12382   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12383 }
12384
12385 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12386 // or turn a shuffle of a single concat into simpler shuffle then concat.
12387 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12388   EVT VT = N->getValueType(0);
12389   unsigned NumElts = VT.getVectorNumElements();
12390
12391   SDValue N0 = N->getOperand(0);
12392   SDValue N1 = N->getOperand(1);
12393   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12394
12395   SmallVector<SDValue, 4> Ops;
12396   EVT ConcatVT = N0.getOperand(0).getValueType();
12397   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12398   unsigned NumConcats = NumElts / NumElemsPerConcat;
12399
12400   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12401   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12402   // half vector elements.
12403   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12404       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12405                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12406     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12407                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12408     N1 = DAG.getUNDEF(ConcatVT);
12409     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12410   }
12411
12412   // Look at every vector that's inserted. We're looking for exact
12413   // subvector-sized copies from a concatenated vector
12414   for (unsigned I = 0; I != NumConcats; ++I) {
12415     // Make sure we're dealing with a copy.
12416     unsigned Begin = I * NumElemsPerConcat;
12417     bool AllUndef = true, NoUndef = true;
12418     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12419       if (SVN->getMaskElt(J) >= 0)
12420         AllUndef = false;
12421       else
12422         NoUndef = false;
12423     }
12424
12425     if (NoUndef) {
12426       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12427         return SDValue();
12428
12429       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12430         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12431           return SDValue();
12432
12433       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12434       if (FirstElt < N0.getNumOperands())
12435         Ops.push_back(N0.getOperand(FirstElt));
12436       else
12437         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12438
12439     } else if (AllUndef) {
12440       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12441     } else { // Mixed with general masks and undefs, can't do optimization.
12442       return SDValue();
12443     }
12444   }
12445
12446   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12447 }
12448
12449 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12450   EVT VT = N->getValueType(0);
12451   unsigned NumElts = VT.getVectorNumElements();
12452
12453   SDValue N0 = N->getOperand(0);
12454   SDValue N1 = N->getOperand(1);
12455
12456   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12457
12458   // Canonicalize shuffle undef, undef -> undef
12459   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12460     return DAG.getUNDEF(VT);
12461
12462   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12463
12464   // Canonicalize shuffle v, v -> v, undef
12465   if (N0 == N1) {
12466     SmallVector<int, 8> NewMask;
12467     for (unsigned i = 0; i != NumElts; ++i) {
12468       int Idx = SVN->getMaskElt(i);
12469       if (Idx >= (int)NumElts) Idx -= NumElts;
12470       NewMask.push_back(Idx);
12471     }
12472     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12473                                 &NewMask[0]);
12474   }
12475
12476   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12477   if (N0.getOpcode() == ISD::UNDEF) {
12478     SmallVector<int, 8> NewMask;
12479     for (unsigned i = 0; i != NumElts; ++i) {
12480       int Idx = SVN->getMaskElt(i);
12481       if (Idx >= 0) {
12482         if (Idx >= (int)NumElts)
12483           Idx -= NumElts;
12484         else
12485           Idx = -1; // remove reference to lhs
12486       }
12487       NewMask.push_back(Idx);
12488     }
12489     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12490                                 &NewMask[0]);
12491   }
12492
12493   // Remove references to rhs if it is undef
12494   if (N1.getOpcode() == ISD::UNDEF) {
12495     bool Changed = false;
12496     SmallVector<int, 8> NewMask;
12497     for (unsigned i = 0; i != NumElts; ++i) {
12498       int Idx = SVN->getMaskElt(i);
12499       if (Idx >= (int)NumElts) {
12500         Idx = -1;
12501         Changed = true;
12502       }
12503       NewMask.push_back(Idx);
12504     }
12505     if (Changed)
12506       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12507   }
12508
12509   // If it is a splat, check if the argument vector is another splat or a
12510   // build_vector.
12511   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12512     SDNode *V = N0.getNode();
12513
12514     // If this is a bit convert that changes the element type of the vector but
12515     // not the number of vector elements, look through it.  Be careful not to
12516     // look though conversions that change things like v4f32 to v2f64.
12517     if (V->getOpcode() == ISD::BITCAST) {
12518       SDValue ConvInput = V->getOperand(0);
12519       if (ConvInput.getValueType().isVector() &&
12520           ConvInput.getValueType().getVectorNumElements() == NumElts)
12521         V = ConvInput.getNode();
12522     }
12523
12524     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12525       assert(V->getNumOperands() == NumElts &&
12526              "BUILD_VECTOR has wrong number of operands");
12527       SDValue Base;
12528       bool AllSame = true;
12529       for (unsigned i = 0; i != NumElts; ++i) {
12530         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12531           Base = V->getOperand(i);
12532           break;
12533         }
12534       }
12535       // Splat of <u, u, u, u>, return <u, u, u, u>
12536       if (!Base.getNode())
12537         return N0;
12538       for (unsigned i = 0; i != NumElts; ++i) {
12539         if (V->getOperand(i) != Base) {
12540           AllSame = false;
12541           break;
12542         }
12543       }
12544       // Splat of <x, x, x, x>, return <x, x, x, x>
12545       if (AllSame)
12546         return N0;
12547
12548       // Canonicalize any other splat as a build_vector.
12549       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12550       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12551       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12552                                   V->getValueType(0), Ops);
12553
12554       // We may have jumped through bitcasts, so the type of the
12555       // BUILD_VECTOR may not match the type of the shuffle.
12556       if (V->getValueType(0) != VT)
12557         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12558       return NewBV;
12559     }
12560   }
12561
12562   // There are various patterns used to build up a vector from smaller vectors,
12563   // subvectors, or elements. Scan chains of these and replace unused insertions
12564   // or components with undef.
12565   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12566     return S;
12567
12568   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12569       Level < AfterLegalizeVectorOps &&
12570       (N1.getOpcode() == ISD::UNDEF ||
12571       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12572        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12573     SDValue V = partitionShuffleOfConcats(N, DAG);
12574
12575     if (V.getNode())
12576       return V;
12577   }
12578
12579   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12580   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12581   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12582     SmallVector<SDValue, 8> Ops;
12583     for (int M : SVN->getMask()) {
12584       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12585       if (M >= 0) {
12586         int Idx = M % NumElts;
12587         SDValue &S = (M < (int)NumElts ? N0 : N1);
12588         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12589           Op = S.getOperand(Idx);
12590         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12591           if (Idx == 0)
12592             Op = S.getOperand(0);
12593         } else {
12594           // Operand can't be combined - bail out.
12595           break;
12596         }
12597       }
12598       Ops.push_back(Op);
12599     }
12600     if (Ops.size() == VT.getVectorNumElements()) {
12601       // BUILD_VECTOR requires all inputs to be of the same type, find the
12602       // maximum type and extend them all.
12603       EVT SVT = VT.getScalarType();
12604       if (SVT.isInteger())
12605         for (SDValue &Op : Ops)
12606           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12607       if (SVT != VT.getScalarType())
12608         for (SDValue &Op : Ops)
12609           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12610                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12611                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12612       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12613     }
12614   }
12615
12616   // If this shuffle only has a single input that is a bitcasted shuffle,
12617   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12618   // back to their original types.
12619   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12620       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12621       TLI.isTypeLegal(VT)) {
12622
12623     // Peek through the bitcast only if there is one user.
12624     SDValue BC0 = N0;
12625     while (BC0.getOpcode() == ISD::BITCAST) {
12626       if (!BC0.hasOneUse())
12627         break;
12628       BC0 = BC0.getOperand(0);
12629     }
12630
12631     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12632       if (Scale == 1)
12633         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12634
12635       SmallVector<int, 8> NewMask;
12636       for (int M : Mask)
12637         for (int s = 0; s != Scale; ++s)
12638           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12639       return NewMask;
12640     };
12641
12642     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12643       EVT SVT = VT.getScalarType();
12644       EVT InnerVT = BC0->getValueType(0);
12645       EVT InnerSVT = InnerVT.getScalarType();
12646
12647       // Determine which shuffle works with the smaller scalar type.
12648       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12649       EVT ScaleSVT = ScaleVT.getScalarType();
12650
12651       if (TLI.isTypeLegal(ScaleVT) &&
12652           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12653           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12654
12655         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12656         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12657
12658         // Scale the shuffle masks to the smaller scalar type.
12659         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12660         SmallVector<int, 8> InnerMask =
12661             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12662         SmallVector<int, 8> OuterMask =
12663             ScaleShuffleMask(SVN->getMask(), OuterScale);
12664
12665         // Merge the shuffle masks.
12666         SmallVector<int, 8> NewMask;
12667         for (int M : OuterMask)
12668           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12669
12670         // Test for shuffle mask legality over both commutations.
12671         SDValue SV0 = BC0->getOperand(0);
12672         SDValue SV1 = BC0->getOperand(1);
12673         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12674         if (!LegalMask) {
12675           std::swap(SV0, SV1);
12676           ShuffleVectorSDNode::commuteMask(NewMask);
12677           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12678         }
12679
12680         if (LegalMask) {
12681           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12682           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12683           return DAG.getNode(
12684               ISD::BITCAST, SDLoc(N), VT,
12685               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12686         }
12687       }
12688     }
12689   }
12690
12691   // Canonicalize shuffles according to rules:
12692   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12693   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12694   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12695   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12696       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12697       TLI.isTypeLegal(VT)) {
12698     // The incoming shuffle must be of the same type as the result of the
12699     // current shuffle.
12700     assert(N1->getOperand(0).getValueType() == VT &&
12701            "Shuffle types don't match");
12702
12703     SDValue SV0 = N1->getOperand(0);
12704     SDValue SV1 = N1->getOperand(1);
12705     bool HasSameOp0 = N0 == SV0;
12706     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12707     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12708       // Commute the operands of this shuffle so that next rule
12709       // will trigger.
12710       return DAG.getCommutedVectorShuffle(*SVN);
12711   }
12712
12713   // Try to fold according to rules:
12714   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12715   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12716   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12717   // Don't try to fold shuffles with illegal type.
12718   // Only fold if this shuffle is the only user of the other shuffle.
12719   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12720       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12721     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12722
12723     // The incoming shuffle must be of the same type as the result of the
12724     // current shuffle.
12725     assert(OtherSV->getOperand(0).getValueType() == VT &&
12726            "Shuffle types don't match");
12727
12728     SDValue SV0, SV1;
12729     SmallVector<int, 4> Mask;
12730     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12731     // operand, and SV1 as the second operand.
12732     for (unsigned i = 0; i != NumElts; ++i) {
12733       int Idx = SVN->getMaskElt(i);
12734       if (Idx < 0) {
12735         // Propagate Undef.
12736         Mask.push_back(Idx);
12737         continue;
12738       }
12739
12740       SDValue CurrentVec;
12741       if (Idx < (int)NumElts) {
12742         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12743         // shuffle mask to identify which vector is actually referenced.
12744         Idx = OtherSV->getMaskElt(Idx);
12745         if (Idx < 0) {
12746           // Propagate Undef.
12747           Mask.push_back(Idx);
12748           continue;
12749         }
12750
12751         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12752                                            : OtherSV->getOperand(1);
12753       } else {
12754         // This shuffle index references an element within N1.
12755         CurrentVec = N1;
12756       }
12757
12758       // Simple case where 'CurrentVec' is UNDEF.
12759       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12760         Mask.push_back(-1);
12761         continue;
12762       }
12763
12764       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12765       // will be the first or second operand of the combined shuffle.
12766       Idx = Idx % NumElts;
12767       if (!SV0.getNode() || SV0 == CurrentVec) {
12768         // Ok. CurrentVec is the left hand side.
12769         // Update the mask accordingly.
12770         SV0 = CurrentVec;
12771         Mask.push_back(Idx);
12772         continue;
12773       }
12774
12775       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12776       if (SV1.getNode() && SV1 != CurrentVec)
12777         return SDValue();
12778
12779       // Ok. CurrentVec is the right hand side.
12780       // Update the mask accordingly.
12781       SV1 = CurrentVec;
12782       Mask.push_back(Idx + NumElts);
12783     }
12784
12785     // Check if all indices in Mask are Undef. In case, propagate Undef.
12786     bool isUndefMask = true;
12787     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12788       isUndefMask &= Mask[i] < 0;
12789
12790     if (isUndefMask)
12791       return DAG.getUNDEF(VT);
12792
12793     if (!SV0.getNode())
12794       SV0 = DAG.getUNDEF(VT);
12795     if (!SV1.getNode())
12796       SV1 = DAG.getUNDEF(VT);
12797
12798     // Avoid introducing shuffles with illegal mask.
12799     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12800       ShuffleVectorSDNode::commuteMask(Mask);
12801
12802       if (!TLI.isShuffleMaskLegal(Mask, VT))
12803         return SDValue();
12804
12805       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12806       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12807       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12808       std::swap(SV0, SV1);
12809     }
12810
12811     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12812     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12813     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12814     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12815   }
12816
12817   return SDValue();
12818 }
12819
12820 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12821   SDValue InVal = N->getOperand(0);
12822   EVT VT = N->getValueType(0);
12823
12824   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12825   // with a VECTOR_SHUFFLE.
12826   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12827     SDValue InVec = InVal->getOperand(0);
12828     SDValue EltNo = InVal->getOperand(1);
12829
12830     // FIXME: We could support implicit truncation if the shuffle can be
12831     // scaled to a smaller vector scalar type.
12832     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12833     if (C0 && VT == InVec.getValueType() &&
12834         VT.getScalarType() == InVal.getValueType()) {
12835       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12836       int Elt = C0->getZExtValue();
12837       NewMask[0] = Elt;
12838
12839       if (TLI.isShuffleMaskLegal(NewMask, VT))
12840         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12841                                     NewMask);
12842     }
12843   }
12844
12845   return SDValue();
12846 }
12847
12848 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12849   SDValue N0 = N->getOperand(0);
12850   SDValue N2 = N->getOperand(2);
12851
12852   // If the input vector is a concatenation, and the insert replaces
12853   // one of the halves, we can optimize into a single concat_vectors.
12854   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12855       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12856     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12857     EVT VT = N->getValueType(0);
12858
12859     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12860     // (concat_vectors Z, Y)
12861     if (InsIdx == 0)
12862       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12863                          N->getOperand(1), N0.getOperand(1));
12864
12865     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12866     // (concat_vectors X, Z)
12867     if (InsIdx == VT.getVectorNumElements()/2)
12868       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12869                          N0.getOperand(0), N->getOperand(1));
12870   }
12871
12872   return SDValue();
12873 }
12874
12875 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12876   SDValue N0 = N->getOperand(0);
12877
12878   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12879   if (N0->getOpcode() == ISD::FP16_TO_FP)
12880     return N0->getOperand(0);
12881
12882   return SDValue();
12883 }
12884
12885 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12886 /// with the destination vector and a zero vector.
12887 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12888 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12889 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12890   EVT VT = N->getValueType(0);
12891   SDValue LHS = N->getOperand(0);
12892   SDValue RHS = N->getOperand(1);
12893   SDLoc dl(N);
12894
12895   // Make sure we're not running after operation legalization where it 
12896   // may have custom lowered the vector shuffles.
12897   if (LegalOperations)
12898     return SDValue();
12899
12900   if (N->getOpcode() != ISD::AND)
12901     return SDValue();
12902
12903   if (RHS.getOpcode() == ISD::BITCAST)
12904     RHS = RHS.getOperand(0);
12905
12906   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12907     SmallVector<int, 8> Indices;
12908     unsigned NumElts = RHS.getNumOperands();
12909
12910     for (unsigned i = 0; i != NumElts; ++i) {
12911       SDValue Elt = RHS.getOperand(i);
12912       if (isAllOnesConstant(Elt))
12913         Indices.push_back(i);
12914       else if (isNullConstant(Elt))
12915         Indices.push_back(NumElts+i);
12916       else
12917         return SDValue();
12918     }
12919
12920     // Let's see if the target supports this vector_shuffle.
12921     EVT RVT = RHS.getValueType();
12922     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12923       return SDValue();
12924
12925     // Return the new VECTOR_SHUFFLE node.
12926     EVT EltVT = RVT.getVectorElementType();
12927     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12928                                    DAG.getConstant(0, dl, EltVT));
12929     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12930     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12931     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12932     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12933   }
12934
12935   return SDValue();
12936 }
12937
12938 /// Visit a binary vector operation, like ADD.
12939 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12940   assert(N->getValueType(0).isVector() &&
12941          "SimplifyVBinOp only works on vectors!");
12942
12943   SDValue LHS = N->getOperand(0);
12944   SDValue RHS = N->getOperand(1);
12945
12946   if (SDValue Shuffle = XformToShuffleWithZero(N))
12947     return Shuffle;
12948
12949   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12950   // this operation.
12951   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12952       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12953     // Check if both vectors are constants. If not bail out.
12954     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12955           cast<BuildVectorSDNode>(RHS)->isConstant()))
12956       return SDValue();
12957
12958     SmallVector<SDValue, 8> Ops;
12959     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12960       SDValue LHSOp = LHS.getOperand(i);
12961       SDValue RHSOp = RHS.getOperand(i);
12962
12963       // Can't fold divide by zero.
12964       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12965           N->getOpcode() == ISD::FDIV) {
12966         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12967              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12968           break;
12969       }
12970
12971       EVT VT = LHSOp.getValueType();
12972       EVT RVT = RHSOp.getValueType();
12973       if (RVT != VT) {
12974         // Integer BUILD_VECTOR operands may have types larger than the element
12975         // size (e.g., when the element type is not legal).  Prior to type
12976         // legalization, the types may not match between the two BUILD_VECTORS.
12977         // Truncate one of the operands to make them match.
12978         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12979           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12980         } else {
12981           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12982           VT = RVT;
12983         }
12984       }
12985       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12986                                    LHSOp, RHSOp);
12987       if (FoldOp.getOpcode() != ISD::UNDEF &&
12988           FoldOp.getOpcode() != ISD::Constant &&
12989           FoldOp.getOpcode() != ISD::ConstantFP)
12990         break;
12991       Ops.push_back(FoldOp);
12992       AddToWorklist(FoldOp.getNode());
12993     }
12994
12995     if (Ops.size() == LHS.getNumOperands())
12996       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12997   }
12998
12999   // Type legalization might introduce new shuffles in the DAG.
13000   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13001   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13002   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13003       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13004       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13005       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13006     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13007     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13008
13009     if (SVN0->getMask().equals(SVN1->getMask())) {
13010       EVT VT = N->getValueType(0);
13011       SDValue UndefVector = LHS.getOperand(1);
13012       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13013                                      LHS.getOperand(0), RHS.getOperand(0));
13014       AddUsersToWorklist(N);
13015       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13016                                   &SVN0->getMask()[0]);
13017     }
13018   }
13019
13020   return SDValue();
13021 }
13022
13023 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13024                                     SDValue N1, SDValue N2){
13025   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13026
13027   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13028                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13029
13030   // If we got a simplified select_cc node back from SimplifySelectCC, then
13031   // break it down into a new SETCC node, and a new SELECT node, and then return
13032   // the SELECT node, since we were called with a SELECT node.
13033   if (SCC.getNode()) {
13034     // Check to see if we got a select_cc back (to turn into setcc/select).
13035     // Otherwise, just return whatever node we got back, like fabs.
13036     if (SCC.getOpcode() == ISD::SELECT_CC) {
13037       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13038                                   N0.getValueType(),
13039                                   SCC.getOperand(0), SCC.getOperand(1),
13040                                   SCC.getOperand(4));
13041       AddToWorklist(SETCC.getNode());
13042       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13043                            SCC.getOperand(2), SCC.getOperand(3));
13044     }
13045
13046     return SCC;
13047   }
13048   return SDValue();
13049 }
13050
13051 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13052 /// being selected between, see if we can simplify the select.  Callers of this
13053 /// should assume that TheSelect is deleted if this returns true.  As such, they
13054 /// should return the appropriate thing (e.g. the node) back to the top-level of
13055 /// the DAG combiner loop to avoid it being looked at.
13056 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13057                                     SDValue RHS) {
13058
13059   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13060   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13061   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13062     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13063       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13064       SDValue Sqrt = RHS;
13065       ISD::CondCode CC;
13066       SDValue CmpLHS;
13067       const ConstantFPSDNode *NegZero = nullptr;
13068
13069       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13070         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13071         CmpLHS = TheSelect->getOperand(0);
13072         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13073       } else {
13074         // SELECT or VSELECT
13075         SDValue Cmp = TheSelect->getOperand(0);
13076         if (Cmp.getOpcode() == ISD::SETCC) {
13077           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13078           CmpLHS = Cmp.getOperand(0);
13079           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13080         }
13081       }
13082       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13083           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13084           CC == ISD::SETULT || CC == ISD::SETLT)) {
13085         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13086         CombineTo(TheSelect, Sqrt);
13087         return true;
13088       }
13089     }
13090   }
13091   // Cannot simplify select with vector condition
13092   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13093
13094   // If this is a select from two identical things, try to pull the operation
13095   // through the select.
13096   if (LHS.getOpcode() != RHS.getOpcode() ||
13097       !LHS.hasOneUse() || !RHS.hasOneUse())
13098     return false;
13099
13100   // If this is a load and the token chain is identical, replace the select
13101   // of two loads with a load through a select of the address to load from.
13102   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13103   // constants have been dropped into the constant pool.
13104   if (LHS.getOpcode() == ISD::LOAD) {
13105     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13106     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13107
13108     // Token chains must be identical.
13109     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13110         // Do not let this transformation reduce the number of volatile loads.
13111         LLD->isVolatile() || RLD->isVolatile() ||
13112         // FIXME: If either is a pre/post inc/dec load,
13113         // we'd need to split out the address adjustment.
13114         LLD->isIndexed() || RLD->isIndexed() ||
13115         // If this is an EXTLOAD, the VT's must match.
13116         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13117         // If this is an EXTLOAD, the kind of extension must match.
13118         (LLD->getExtensionType() != RLD->getExtensionType() &&
13119          // The only exception is if one of the extensions is anyext.
13120          LLD->getExtensionType() != ISD::EXTLOAD &&
13121          RLD->getExtensionType() != ISD::EXTLOAD) ||
13122         // FIXME: this discards src value information.  This is
13123         // over-conservative. It would be beneficial to be able to remember
13124         // both potential memory locations.  Since we are discarding
13125         // src value info, don't do the transformation if the memory
13126         // locations are not in the default address space.
13127         LLD->getPointerInfo().getAddrSpace() != 0 ||
13128         RLD->getPointerInfo().getAddrSpace() != 0 ||
13129         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13130                                       LLD->getBasePtr().getValueType()))
13131       return false;
13132
13133     // Check that the select condition doesn't reach either load.  If so,
13134     // folding this will induce a cycle into the DAG.  If not, this is safe to
13135     // xform, so create a select of the addresses.
13136     SDValue Addr;
13137     if (TheSelect->getOpcode() == ISD::SELECT) {
13138       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13139       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13140           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13141         return false;
13142       // The loads must not depend on one another.
13143       if (LLD->isPredecessorOf(RLD) ||
13144           RLD->isPredecessorOf(LLD))
13145         return false;
13146       Addr = DAG.getSelect(SDLoc(TheSelect),
13147                            LLD->getBasePtr().getValueType(),
13148                            TheSelect->getOperand(0), LLD->getBasePtr(),
13149                            RLD->getBasePtr());
13150     } else {  // Otherwise SELECT_CC
13151       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13152       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13153
13154       if ((LLD->hasAnyUseOfValue(1) &&
13155            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13156           (RLD->hasAnyUseOfValue(1) &&
13157            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13158         return false;
13159
13160       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13161                          LLD->getBasePtr().getValueType(),
13162                          TheSelect->getOperand(0),
13163                          TheSelect->getOperand(1),
13164                          LLD->getBasePtr(), RLD->getBasePtr(),
13165                          TheSelect->getOperand(4));
13166     }
13167
13168     SDValue Load;
13169     // It is safe to replace the two loads if they have different alignments,
13170     // but the new load must be the minimum (most restrictive) alignment of the
13171     // inputs.
13172     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13173     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13174     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13175       Load = DAG.getLoad(TheSelect->getValueType(0),
13176                          SDLoc(TheSelect),
13177                          // FIXME: Discards pointer and AA info.
13178                          LLD->getChain(), Addr, MachinePointerInfo(),
13179                          LLD->isVolatile(), LLD->isNonTemporal(),
13180                          isInvariant, Alignment);
13181     } else {
13182       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13183                             RLD->getExtensionType() : LLD->getExtensionType(),
13184                             SDLoc(TheSelect),
13185                             TheSelect->getValueType(0),
13186                             // FIXME: Discards pointer and AA info.
13187                             LLD->getChain(), Addr, MachinePointerInfo(),
13188                             LLD->getMemoryVT(), LLD->isVolatile(),
13189                             LLD->isNonTemporal(), isInvariant, Alignment);
13190     }
13191
13192     // Users of the select now use the result of the load.
13193     CombineTo(TheSelect, Load);
13194
13195     // Users of the old loads now use the new load's chain.  We know the
13196     // old-load value is dead now.
13197     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13198     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13199     return true;
13200   }
13201
13202   return false;
13203 }
13204
13205 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13206 /// where 'cond' is the comparison specified by CC.
13207 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13208                                       SDValue N2, SDValue N3,
13209                                       ISD::CondCode CC, bool NotExtCompare) {
13210   // (x ? y : y) -> y.
13211   if (N2 == N3) return N2;
13212
13213   EVT VT = N2.getValueType();
13214   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13215   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13216
13217   // Determine if the condition we're dealing with is constant
13218   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13219                               N0, N1, CC, DL, false);
13220   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13221
13222   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13223     // fold select_cc true, x, y -> x
13224     // fold select_cc false, x, y -> y
13225     return !SCCC->isNullValue() ? N2 : N3;
13226   }
13227
13228   // Check to see if we can simplify the select into an fabs node
13229   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13230     // Allow either -0.0 or 0.0
13231     if (CFP->getValueAPF().isZero()) {
13232       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13233       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13234           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13235           N2 == N3.getOperand(0))
13236         return DAG.getNode(ISD::FABS, DL, VT, N0);
13237
13238       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13239       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13240           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13241           N2.getOperand(0) == N3)
13242         return DAG.getNode(ISD::FABS, DL, VT, N3);
13243     }
13244   }
13245
13246   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13247   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13248   // in it.  This is a win when the constant is not otherwise available because
13249   // it replaces two constant pool loads with one.  We only do this if the FP
13250   // type is known to be legal, because if it isn't, then we are before legalize
13251   // types an we want the other legalization to happen first (e.g. to avoid
13252   // messing with soft float) and if the ConstantFP is not legal, because if
13253   // it is legal, we may not need to store the FP constant in a constant pool.
13254   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13255     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13256       if (TLI.isTypeLegal(N2.getValueType()) &&
13257           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13258                TargetLowering::Legal &&
13259            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13260            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13261           // If both constants have multiple uses, then we won't need to do an
13262           // extra load, they are likely around in registers for other users.
13263           (TV->hasOneUse() || FV->hasOneUse())) {
13264         Constant *Elts[] = {
13265           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13266           const_cast<ConstantFP*>(TV->getConstantFPValue())
13267         };
13268         Type *FPTy = Elts[0]->getType();
13269         const DataLayout &TD = *TLI.getDataLayout();
13270
13271         // Create a ConstantArray of the two constants.
13272         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13273         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13274                                             TD.getPrefTypeAlignment(FPTy));
13275         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13276
13277         // Get the offsets to the 0 and 1 element of the array so that we can
13278         // select between them.
13279         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13280         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13281         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13282
13283         SDValue Cond = DAG.getSetCC(DL,
13284                                     getSetCCResultType(N0.getValueType()),
13285                                     N0, N1, CC);
13286         AddToWorklist(Cond.getNode());
13287         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13288                                           Cond, One, Zero);
13289         AddToWorklist(CstOffset.getNode());
13290         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13291                             CstOffset);
13292         AddToWorklist(CPIdx.getNode());
13293         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13294                            MachinePointerInfo::getConstantPool(), false,
13295                            false, false, Alignment);
13296       }
13297     }
13298
13299   // Check to see if we can perform the "gzip trick", transforming
13300   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13301   if (isNullConstant(N3) && CC == ISD::SETLT &&
13302       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13303        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13304     EVT XType = N0.getValueType();
13305     EVT AType = N2.getValueType();
13306     if (XType.bitsGE(AType)) {
13307       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13308       // single-bit constant.
13309       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13310         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13311         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13312         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13313                                        getShiftAmountTy(N0.getValueType()));
13314         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13315                                     XType, N0, ShCt);
13316         AddToWorklist(Shift.getNode());
13317
13318         if (XType.bitsGT(AType)) {
13319           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13320           AddToWorklist(Shift.getNode());
13321         }
13322
13323         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13324       }
13325
13326       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13327                                   XType, N0,
13328                                   DAG.getConstant(XType.getSizeInBits() - 1,
13329                                                   SDLoc(N0),
13330                                          getShiftAmountTy(N0.getValueType())));
13331       AddToWorklist(Shift.getNode());
13332
13333       if (XType.bitsGT(AType)) {
13334         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13335         AddToWorklist(Shift.getNode());
13336       }
13337
13338       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13339     }
13340   }
13341
13342   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13343   // where y is has a single bit set.
13344   // A plaintext description would be, we can turn the SELECT_CC into an AND
13345   // when the condition can be materialized as an all-ones register.  Any
13346   // single bit-test can be materialized as an all-ones register with
13347   // shift-left and shift-right-arith.
13348   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13349       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13350     SDValue AndLHS = N0->getOperand(0);
13351     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13352     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13353       // Shift the tested bit over the sign bit.
13354       APInt AndMask = ConstAndRHS->getAPIntValue();
13355       SDValue ShlAmt =
13356         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13357                         getShiftAmountTy(AndLHS.getValueType()));
13358       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13359
13360       // Now arithmetic right shift it all the way over, so the result is either
13361       // all-ones, or zero.
13362       SDValue ShrAmt =
13363         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13364                         getShiftAmountTy(Shl.getValueType()));
13365       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13366
13367       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13368     }
13369   }
13370
13371   // fold select C, 16, 0 -> shl C, 4
13372   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13373       TLI.getBooleanContents(N0.getValueType()) ==
13374           TargetLowering::ZeroOrOneBooleanContent) {
13375
13376     // If the caller doesn't want us to simplify this into a zext of a compare,
13377     // don't do it.
13378     if (NotExtCompare && N2C->isOne())
13379       return SDValue();
13380
13381     // Get a SetCC of the condition
13382     // NOTE: Don't create a SETCC if it's not legal on this target.
13383     if (!LegalOperations ||
13384         TLI.isOperationLegal(ISD::SETCC,
13385           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13386       SDValue Temp, SCC;
13387       // cast from setcc result type to select result type
13388       if (LegalTypes) {
13389         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13390                             N0, N1, CC);
13391         if (N2.getValueType().bitsLT(SCC.getValueType()))
13392           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13393                                         N2.getValueType());
13394         else
13395           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13396                              N2.getValueType(), SCC);
13397       } else {
13398         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13399         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13400                            N2.getValueType(), SCC);
13401       }
13402
13403       AddToWorklist(SCC.getNode());
13404       AddToWorklist(Temp.getNode());
13405
13406       if (N2C->isOne())
13407         return Temp;
13408
13409       // shl setcc result by log2 n2c
13410       return DAG.getNode(
13411           ISD::SHL, DL, N2.getValueType(), Temp,
13412           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13413                           getShiftAmountTy(Temp.getValueType())));
13414     }
13415   }
13416
13417   // Check to see if this is the equivalent of setcc
13418   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13419   // otherwise, go ahead with the folds.
13420   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13421     EVT XType = N0.getValueType();
13422     if (!LegalOperations ||
13423         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13424       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13425       if (Res.getValueType() != VT)
13426         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13427       return Res;
13428     }
13429
13430     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13431     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13432         (!LegalOperations ||
13433          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13434       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13435       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13436                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13437                                          SDLoc(Ctlz),
13438                                        getShiftAmountTy(Ctlz.getValueType())));
13439     }
13440     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13441     if (isNullConstant(N1) && CC == ISD::SETGT) {
13442       SDLoc DL(N0);
13443       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13444                                   XType, DAG.getConstant(0, DL, XType), N0);
13445       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13446       return DAG.getNode(ISD::SRL, DL, XType,
13447                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13448                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13449                                          getShiftAmountTy(XType)));
13450     }
13451     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13452     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13453       SDLoc DL(N0);
13454       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13455                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13456                                          getShiftAmountTy(N0.getValueType())));
13457       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13458                                                                     XType));
13459     }
13460   }
13461
13462   // Check to see if this is an integer abs.
13463   // select_cc setg[te] X,  0,  X, -X ->
13464   // select_cc setgt    X, -1,  X, -X ->
13465   // select_cc setl[te] X,  0, -X,  X ->
13466   // select_cc setlt    X,  1, -X,  X ->
13467   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13468   if (N1C) {
13469     ConstantSDNode *SubC = nullptr;
13470     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13471          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13472         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13473       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13474     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13475               (N1C->isOne() && CC == ISD::SETLT)) &&
13476              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13477       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13478
13479     EVT XType = N0.getValueType();
13480     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13481       SDLoc DL(N0);
13482       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13483                                   N0,
13484                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13485                                          getShiftAmountTy(N0.getValueType())));
13486       SDValue Add = DAG.getNode(ISD::ADD, DL,
13487                                 XType, N0, Shift);
13488       AddToWorklist(Shift.getNode());
13489       AddToWorklist(Add.getNode());
13490       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13491     }
13492   }
13493
13494   return SDValue();
13495 }
13496
13497 /// This is a stub for TargetLowering::SimplifySetCC.
13498 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13499                                    SDValue N1, ISD::CondCode Cond,
13500                                    SDLoc DL, bool foldBooleans) {
13501   TargetLowering::DAGCombinerInfo
13502     DagCombineInfo(DAG, Level, false, this);
13503   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13504 }
13505
13506 /// Given an ISD::SDIV node expressing a divide by constant, return
13507 /// a DAG expression to select that will generate the same value by multiplying
13508 /// by a magic number.
13509 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13510 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13511   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13512   if (!C)
13513     return SDValue();
13514
13515   // Avoid division by zero.
13516   if (C->isNullValue())
13517     return SDValue();
13518
13519   std::vector<SDNode*> Built;
13520   SDValue S =
13521       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13522
13523   for (SDNode *N : Built)
13524     AddToWorklist(N);
13525   return S;
13526 }
13527
13528 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13529 /// DAG expression that will generate the same value by right shifting.
13530 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13531   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13532   if (!C)
13533     return SDValue();
13534
13535   // Avoid division by zero.
13536   if (C->isNullValue())
13537     return SDValue();
13538
13539   std::vector<SDNode *> Built;
13540   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13541
13542   for (SDNode *N : Built)
13543     AddToWorklist(N);
13544   return S;
13545 }
13546
13547 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13548 /// expression that will generate the same value by multiplying by a magic
13549 /// number.
13550 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13551 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13552   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13553   if (!C)
13554     return SDValue();
13555
13556   // Avoid division by zero.
13557   if (C->isNullValue())
13558     return SDValue();
13559
13560   std::vector<SDNode*> Built;
13561   SDValue S =
13562       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13563
13564   for (SDNode *N : Built)
13565     AddToWorklist(N);
13566   return S;
13567 }
13568
13569 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13570   if (Level >= AfterLegalizeDAG)
13571     return SDValue();
13572
13573   // Expose the DAG combiner to the target combiner implementations.
13574   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13575
13576   unsigned Iterations = 0;
13577   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13578     if (Iterations) {
13579       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13580       // For the reciprocal, we need to find the zero of the function:
13581       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13582       //     =>
13583       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13584       //     does not require additional intermediate precision]
13585       EVT VT = Op.getValueType();
13586       SDLoc DL(Op);
13587       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13588
13589       AddToWorklist(Est.getNode());
13590
13591       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13592       for (unsigned i = 0; i < Iterations; ++i) {
13593         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13594         AddToWorklist(NewEst.getNode());
13595
13596         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13597         AddToWorklist(NewEst.getNode());
13598
13599         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13600         AddToWorklist(NewEst.getNode());
13601
13602         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13603         AddToWorklist(Est.getNode());
13604       }
13605     }
13606     return Est;
13607   }
13608
13609   return SDValue();
13610 }
13611
13612 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13613 /// For the reciprocal sqrt, we need to find the zero of the function:
13614 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13615 ///     =>
13616 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13617 /// As a result, we precompute A/2 prior to the iteration loop.
13618 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13619                                           unsigned Iterations) {
13620   EVT VT = Arg.getValueType();
13621   SDLoc DL(Arg);
13622   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13623
13624   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13625   // this entire sequence requires only one FP constant.
13626   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13627   AddToWorklist(HalfArg.getNode());
13628
13629   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13630   AddToWorklist(HalfArg.getNode());
13631
13632   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13633   for (unsigned i = 0; i < Iterations; ++i) {
13634     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13635     AddToWorklist(NewEst.getNode());
13636
13637     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13638     AddToWorklist(NewEst.getNode());
13639
13640     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13641     AddToWorklist(NewEst.getNode());
13642
13643     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13644     AddToWorklist(Est.getNode());
13645   }
13646   return Est;
13647 }
13648
13649 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13650 /// For the reciprocal sqrt, we need to find the zero of the function:
13651 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13652 ///     =>
13653 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13654 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13655                                           unsigned Iterations) {
13656   EVT VT = Arg.getValueType();
13657   SDLoc DL(Arg);
13658   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13659   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13660
13661   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13662   for (unsigned i = 0; i < Iterations; ++i) {
13663     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13664     AddToWorklist(HalfEst.getNode());
13665
13666     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13667     AddToWorklist(Est.getNode());
13668
13669     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13670     AddToWorklist(Est.getNode());
13671
13672     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13673     AddToWorklist(Est.getNode());
13674
13675     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13676     AddToWorklist(Est.getNode());
13677   }
13678   return Est;
13679 }
13680
13681 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13682   if (Level >= AfterLegalizeDAG)
13683     return SDValue();
13684
13685   // Expose the DAG combiner to the target combiner implementations.
13686   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13687   unsigned Iterations = 0;
13688   bool UseOneConstNR = false;
13689   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13690     AddToWorklist(Est.getNode());
13691     if (Iterations) {
13692       Est = UseOneConstNR ?
13693         BuildRsqrtNROneConst(Op, Est, Iterations) :
13694         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13695     }
13696     return Est;
13697   }
13698
13699   return SDValue();
13700 }
13701
13702 /// Return true if base is a frame index, which is known not to alias with
13703 /// anything but itself.  Provides base object and offset as results.
13704 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13705                            const GlobalValue *&GV, const void *&CV) {
13706   // Assume it is a primitive operation.
13707   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13708
13709   // If it's an adding a simple constant then integrate the offset.
13710   if (Base.getOpcode() == ISD::ADD) {
13711     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13712       Base = Base.getOperand(0);
13713       Offset += C->getZExtValue();
13714     }
13715   }
13716
13717   // Return the underlying GlobalValue, and update the Offset.  Return false
13718   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13719   // by multiple nodes with different offsets.
13720   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13721     GV = G->getGlobal();
13722     Offset += G->getOffset();
13723     return false;
13724   }
13725
13726   // Return the underlying Constant value, and update the Offset.  Return false
13727   // for ConstantSDNodes since the same constant pool entry may be represented
13728   // by multiple nodes with different offsets.
13729   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13730     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13731                                          : (const void *)C->getConstVal();
13732     Offset += C->getOffset();
13733     return false;
13734   }
13735   // If it's any of the following then it can't alias with anything but itself.
13736   return isa<FrameIndexSDNode>(Base);
13737 }
13738
13739 /// Return true if there is any possibility that the two addresses overlap.
13740 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13741   // If they are the same then they must be aliases.
13742   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13743
13744   // If they are both volatile then they cannot be reordered.
13745   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13746
13747   // Gather base node and offset information.
13748   SDValue Base1, Base2;
13749   int64_t Offset1, Offset2;
13750   const GlobalValue *GV1, *GV2;
13751   const void *CV1, *CV2;
13752   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13753                                       Base1, Offset1, GV1, CV1);
13754   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13755                                       Base2, Offset2, GV2, CV2);
13756
13757   // If they have a same base address then check to see if they overlap.
13758   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13759     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13760              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13761
13762   // It is possible for different frame indices to alias each other, mostly
13763   // when tail call optimization reuses return address slots for arguments.
13764   // To catch this case, look up the actual index of frame indices to compute
13765   // the real alias relationship.
13766   if (isFrameIndex1 && isFrameIndex2) {
13767     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13768     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13769     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13770     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13771              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13772   }
13773
13774   // Otherwise, if we know what the bases are, and they aren't identical, then
13775   // we know they cannot alias.
13776   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13777     return false;
13778
13779   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13780   // compared to the size and offset of the access, we may be able to prove they
13781   // do not alias.  This check is conservative for now to catch cases created by
13782   // splitting vector types.
13783   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13784       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13785       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13786        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13787       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13788     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13789     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13790
13791     // There is no overlap between these relatively aligned accesses of similar
13792     // size, return no alias.
13793     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13794         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13795       return false;
13796   }
13797
13798   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13799                    ? CombinerGlobalAA
13800                    : DAG.getSubtarget().useAA();
13801 #ifndef NDEBUG
13802   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13803       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13804     UseAA = false;
13805 #endif
13806   if (UseAA &&
13807       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13808     // Use alias analysis information.
13809     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13810                                  Op1->getSrcValueOffset());
13811     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13812         Op0->getSrcValueOffset() - MinOffset;
13813     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13814         Op1->getSrcValueOffset() - MinOffset;
13815     AliasAnalysis::AliasResult AAResult =
13816         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13817                                          Overlap1,
13818                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13819                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13820                                          Overlap2,
13821                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13822     if (AAResult == AliasAnalysis::NoAlias)
13823       return false;
13824   }
13825
13826   // Otherwise we have to assume they alias.
13827   return true;
13828 }
13829
13830 /// Walk up chain skipping non-aliasing memory nodes,
13831 /// looking for aliasing nodes and adding them to the Aliases vector.
13832 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13833                                    SmallVectorImpl<SDValue> &Aliases) {
13834   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13835   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13836
13837   // Get alias information for node.
13838   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13839
13840   // Starting off.
13841   Chains.push_back(OriginalChain);
13842   unsigned Depth = 0;
13843
13844   // Look at each chain and determine if it is an alias.  If so, add it to the
13845   // aliases list.  If not, then continue up the chain looking for the next
13846   // candidate.
13847   while (!Chains.empty()) {
13848     SDValue Chain = Chains.back();
13849     Chains.pop_back();
13850
13851     // For TokenFactor nodes, look at each operand and only continue up the
13852     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13853     // find more and revert to original chain since the xform is unlikely to be
13854     // profitable.
13855     //
13856     // FIXME: The depth check could be made to return the last non-aliasing
13857     // chain we found before we hit a tokenfactor rather than the original
13858     // chain.
13859     if (Depth > 6 || Aliases.size() == 2) {
13860       Aliases.clear();
13861       Aliases.push_back(OriginalChain);
13862       return;
13863     }
13864
13865     // Don't bother if we've been before.
13866     if (!Visited.insert(Chain.getNode()).second)
13867       continue;
13868
13869     switch (Chain.getOpcode()) {
13870     case ISD::EntryToken:
13871       // Entry token is ideal chain operand, but handled in FindBetterChain.
13872       break;
13873
13874     case ISD::LOAD:
13875     case ISD::STORE: {
13876       // Get alias information for Chain.
13877       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13878           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13879
13880       // If chain is alias then stop here.
13881       if (!(IsLoad && IsOpLoad) &&
13882           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13883         Aliases.push_back(Chain);
13884       } else {
13885         // Look further up the chain.
13886         Chains.push_back(Chain.getOperand(0));
13887         ++Depth;
13888       }
13889       break;
13890     }
13891
13892     case ISD::TokenFactor:
13893       // We have to check each of the operands of the token factor for "small"
13894       // token factors, so we queue them up.  Adding the operands to the queue
13895       // (stack) in reverse order maintains the original order and increases the
13896       // likelihood that getNode will find a matching token factor (CSE.)
13897       if (Chain.getNumOperands() > 16) {
13898         Aliases.push_back(Chain);
13899         break;
13900       }
13901       for (unsigned n = Chain.getNumOperands(); n;)
13902         Chains.push_back(Chain.getOperand(--n));
13903       ++Depth;
13904       break;
13905
13906     default:
13907       // For all other instructions we will just have to take what we can get.
13908       Aliases.push_back(Chain);
13909       break;
13910     }
13911   }
13912
13913   // We need to be careful here to also search for aliases through the
13914   // value operand of a store, etc. Consider the following situation:
13915   //   Token1 = ...
13916   //   L1 = load Token1, %52
13917   //   S1 = store Token1, L1, %51
13918   //   L2 = load Token1, %52+8
13919   //   S2 = store Token1, L2, %51+8
13920   //   Token2 = Token(S1, S2)
13921   //   L3 = load Token2, %53
13922   //   S3 = store Token2, L3, %52
13923   //   L4 = load Token2, %53+8
13924   //   S4 = store Token2, L4, %52+8
13925   // If we search for aliases of S3 (which loads address %52), and we look
13926   // only through the chain, then we'll miss the trivial dependence on L1
13927   // (which also loads from %52). We then might change all loads and
13928   // stores to use Token1 as their chain operand, which could result in
13929   // copying %53 into %52 before copying %52 into %51 (which should
13930   // happen first).
13931   //
13932   // The problem is, however, that searching for such data dependencies
13933   // can become expensive, and the cost is not directly related to the
13934   // chain depth. Instead, we'll rule out such configurations here by
13935   // insisting that we've visited all chain users (except for users
13936   // of the original chain, which is not necessary). When doing this,
13937   // we need to look through nodes we don't care about (otherwise, things
13938   // like register copies will interfere with trivial cases).
13939
13940   SmallVector<const SDNode *, 16> Worklist;
13941   for (const SDNode *N : Visited)
13942     if (N != OriginalChain.getNode())
13943       Worklist.push_back(N);
13944
13945   while (!Worklist.empty()) {
13946     const SDNode *M = Worklist.pop_back_val();
13947
13948     // We have already visited M, and want to make sure we've visited any uses
13949     // of M that we care about. For uses that we've not visisted, and don't
13950     // care about, queue them to the worklist.
13951
13952     for (SDNode::use_iterator UI = M->use_begin(),
13953          UIE = M->use_end(); UI != UIE; ++UI)
13954       if (UI.getUse().getValueType() == MVT::Other &&
13955           Visited.insert(*UI).second) {
13956         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13957           // We've not visited this use, and we care about it (it could have an
13958           // ordering dependency with the original node).
13959           Aliases.clear();
13960           Aliases.push_back(OriginalChain);
13961           return;
13962         }
13963
13964         // We've not visited this use, but we don't care about it. Mark it as
13965         // visited and enqueue it to the worklist.
13966         Worklist.push_back(*UI);
13967       }
13968   }
13969 }
13970
13971 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13972 /// (aliasing node.)
13973 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13974   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13975
13976   // Accumulate all the aliases to this node.
13977   GatherAllAliases(N, OldChain, Aliases);
13978
13979   // If no operands then chain to entry token.
13980   if (Aliases.size() == 0)
13981     return DAG.getEntryNode();
13982
13983   // If a single operand then chain to it.  We don't need to revisit it.
13984   if (Aliases.size() == 1)
13985     return Aliases[0];
13986
13987   // Construct a custom tailored token factor.
13988   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13989 }
13990
13991 /// This is the entry point for the file.
13992 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13993                            CodeGenOpt::Level OptLevel) {
13994   /// This is the main entry point to this class.
13995   DAGCombiner(*this, AA, OptLevel).Run(Level);
13996 }