feeb1267e3535dd5f0efab2f33358cd78d07ecf1
[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 SDValue DAGCombiner::visitADD(SDNode *N) {
1589   SDValue N0 = N->getOperand(0);
1590   SDValue N1 = N->getOperand(1);
1591   EVT VT = N0.getValueType();
1592
1593   // fold vector ops
1594   if (VT.isVector()) {
1595     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1596       return FoldedVOp;
1597
1598     // fold (add x, 0) -> x, vector edition
1599     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1600       return N0;
1601     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1602       return N1;
1603   }
1604
1605   // fold (add x, undef) -> undef
1606   if (N0.getOpcode() == ISD::UNDEF)
1607     return N0;
1608   if (N1.getOpcode() == ISD::UNDEF)
1609     return N1;
1610   // fold (add c1, c2) -> c1+c2
1611   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1612   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1613   if (N0C && N1C)
1614     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1615   // canonicalize constant to RHS
1616   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1617      !isConstantIntBuildVectorOrConstantInt(N1))
1618     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1619   // fold (add x, 0) -> x
1620   if (isNullConstant(N1))
1621     return N0;
1622   // fold (add Sym, c) -> Sym+c
1623   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1624     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1625         GA->getOpcode() == ISD::GlobalAddress)
1626       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1627                                   GA->getOffset() +
1628                                     (uint64_t)N1C->getSExtValue());
1629   // fold ((c1-A)+c2) -> (c1+c2)-A
1630   if (N1C && N0.getOpcode() == ISD::SUB)
1631     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1632       SDLoc DL(N);
1633       return DAG.getNode(ISD::SUB, DL, VT,
1634                          DAG.getConstant(N1C->getAPIntValue()+
1635                                          N0C->getAPIntValue(), DL, VT),
1636                          N0.getOperand(1));
1637     }
1638   // reassociate add
1639   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1640     return RADD;
1641   // fold ((0-A) + B) -> B-A
1642   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1643     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1644   // fold (A + (0-B)) -> A-B
1645   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1646     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1647   // fold (A+(B-A)) -> B
1648   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1649     return N1.getOperand(0);
1650   // fold ((B-A)+A) -> B
1651   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1652     return N0.getOperand(0);
1653   // fold (A+(B-(A+C))) to (B-C)
1654   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1655       N0 == N1.getOperand(1).getOperand(0))
1656     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1657                        N1.getOperand(1).getOperand(1));
1658   // fold (A+(B-(C+A))) to (B-C)
1659   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1660       N0 == N1.getOperand(1).getOperand(1))
1661     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1662                        N1.getOperand(1).getOperand(0));
1663   // fold (A+((B-A)+or-C)) to (B+or-C)
1664   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1665       N1.getOperand(0).getOpcode() == ISD::SUB &&
1666       N0 == N1.getOperand(0).getOperand(1))
1667     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1668                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1669
1670   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1671   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1672     SDValue N00 = N0.getOperand(0);
1673     SDValue N01 = N0.getOperand(1);
1674     SDValue N10 = N1.getOperand(0);
1675     SDValue N11 = N1.getOperand(1);
1676
1677     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1678       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1679                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1680                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1681   }
1682
1683   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1684     return SDValue(N, 0);
1685
1686   // fold (a+b) -> (a|b) iff a and b share no bits.
1687   if (VT.isInteger() && !VT.isVector()) {
1688     APInt LHSZero, LHSOne;
1689     APInt RHSZero, RHSOne;
1690     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1691
1692     if (LHSZero.getBoolValue()) {
1693       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1694
1695       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1696       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1697       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1698         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1699           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1700       }
1701     }
1702   }
1703
1704   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1705   if (N1.getOpcode() == ISD::SHL &&
1706       N1.getOperand(0).getOpcode() == ISD::SUB)
1707     if (ConstantSDNode *C =
1708           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1709       if (C->getAPIntValue() == 0)
1710         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1711                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1712                                        N1.getOperand(0).getOperand(1),
1713                                        N1.getOperand(1)));
1714   if (N0.getOpcode() == ISD::SHL &&
1715       N0.getOperand(0).getOpcode() == ISD::SUB)
1716     if (ConstantSDNode *C =
1717           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1718       if (C->getAPIntValue() == 0)
1719         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1720                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1721                                        N0.getOperand(0).getOperand(1),
1722                                        N0.getOperand(1)));
1723
1724   if (N1.getOpcode() == ISD::AND) {
1725     SDValue AndOp0 = N1.getOperand(0);
1726     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1727     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1728     unsigned DestBits = VT.getScalarType().getSizeInBits();
1729
1730     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1731     // and similar xforms where the inner op is either ~0 or 0.
1732     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1733       SDLoc DL(N);
1734       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1735     }
1736   }
1737
1738   // add (sext i1), X -> sub X, (zext i1)
1739   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1740       N0.getOperand(0).getValueType() == MVT::i1 &&
1741       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1742     SDLoc DL(N);
1743     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1744     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1745   }
1746
1747   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1748   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1749     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1750     if (TN->getVT() == MVT::i1) {
1751       SDLoc DL(N);
1752       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1753                                  DAG.getConstant(1, DL, VT));
1754       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1755     }
1756   }
1757
1758   return SDValue();
1759 }
1760
1761 SDValue DAGCombiner::visitADDC(SDNode *N) {
1762   SDValue N0 = N->getOperand(0);
1763   SDValue N1 = N->getOperand(1);
1764   EVT VT = N0.getValueType();
1765
1766   // If the flag result is dead, turn this into an ADD.
1767   if (!N->hasAnyUseOfValue(1))
1768     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1769                      DAG.getNode(ISD::CARRY_FALSE,
1770                                  SDLoc(N), MVT::Glue));
1771
1772   // canonicalize constant to RHS.
1773   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1774   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1775   if (N0C && !N1C)
1776     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1777
1778   // fold (addc x, 0) -> x + no carry out
1779   if (isNullConstant(N1))
1780     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1781                                         SDLoc(N), MVT::Glue));
1782
1783   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1784   APInt LHSZero, LHSOne;
1785   APInt RHSZero, RHSOne;
1786   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1787
1788   if (LHSZero.getBoolValue()) {
1789     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1790
1791     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1792     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1793     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1794       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1795                        DAG.getNode(ISD::CARRY_FALSE,
1796                                    SDLoc(N), MVT::Glue));
1797   }
1798
1799   return SDValue();
1800 }
1801
1802 SDValue DAGCombiner::visitADDE(SDNode *N) {
1803   SDValue N0 = N->getOperand(0);
1804   SDValue N1 = N->getOperand(1);
1805   SDValue CarryIn = N->getOperand(2);
1806
1807   // canonicalize constant to RHS
1808   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1809   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1810   if (N0C && !N1C)
1811     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1812                        N1, N0, CarryIn);
1813
1814   // fold (adde x, y, false) -> (addc x, y)
1815   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1816     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1817
1818   return SDValue();
1819 }
1820
1821 // Since it may not be valid to emit a fold to zero for vector initializers
1822 // check if we can before folding.
1823 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1824                              SelectionDAG &DAG,
1825                              bool LegalOperations, bool LegalTypes) {
1826   if (!VT.isVector())
1827     return DAG.getConstant(0, DL, VT);
1828   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1829     return DAG.getConstant(0, DL, VT);
1830   return SDValue();
1831 }
1832
1833 SDValue DAGCombiner::visitSUB(SDNode *N) {
1834   SDValue N0 = N->getOperand(0);
1835   SDValue N1 = N->getOperand(1);
1836   EVT VT = N0.getValueType();
1837
1838   // fold vector ops
1839   if (VT.isVector()) {
1840     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1841       return FoldedVOp;
1842
1843     // fold (sub x, 0) -> x, vector edition
1844     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1845       return N0;
1846   }
1847
1848   // fold (sub x, x) -> 0
1849   // FIXME: Refactor this and xor and other similar operations together.
1850   if (N0 == N1)
1851     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1852   // fold (sub c1, c2) -> c1-c2
1853   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1854   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1855   if (N0C && N1C)
1856     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1857   // fold (sub x, c) -> (add x, -c)
1858   if (N1C) {
1859     SDLoc DL(N);
1860     return DAG.getNode(ISD::ADD, DL, VT, N0,
1861                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1862   }
1863   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1864   if (N0C && N0C->isAllOnesValue())
1865     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1866   // fold A-(A-B) -> B
1867   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1868     return N1.getOperand(1);
1869   // fold (A+B)-A -> B
1870   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1871     return N0.getOperand(1);
1872   // fold (A+B)-B -> A
1873   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1874     return N0.getOperand(0);
1875   // fold C2-(A+C1) -> (C2-C1)-A
1876   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1877     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1878   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1879     SDLoc DL(N);
1880     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1881                                    DL, VT);
1882     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1883                        N1.getOperand(0));
1884   }
1885   // fold ((A+(B+or-C))-B) -> A+or-C
1886   if (N0.getOpcode() == ISD::ADD &&
1887       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1888        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1889       N0.getOperand(1).getOperand(0) == N1)
1890     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1891                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1892   // fold ((A+(C+B))-B) -> A+C
1893   if (N0.getOpcode() == ISD::ADD &&
1894       N0.getOperand(1).getOpcode() == ISD::ADD &&
1895       N0.getOperand(1).getOperand(1) == N1)
1896     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1897                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1898   // fold ((A-(B-C))-C) -> A-B
1899   if (N0.getOpcode() == ISD::SUB &&
1900       N0.getOperand(1).getOpcode() == ISD::SUB &&
1901       N0.getOperand(1).getOperand(1) == N1)
1902     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1903                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1904
1905   // If either operand of a sub is undef, the result is undef
1906   if (N0.getOpcode() == ISD::UNDEF)
1907     return N0;
1908   if (N1.getOpcode() == ISD::UNDEF)
1909     return N1;
1910
1911   // If the relocation model supports it, consider symbol offsets.
1912   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1913     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1914       // fold (sub Sym, c) -> Sym-c
1915       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1916         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1917                                     GA->getOffset() -
1918                                       (uint64_t)N1C->getSExtValue());
1919       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1920       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1921         if (GA->getGlobal() == GB->getGlobal())
1922           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1923                                  SDLoc(N), VT);
1924     }
1925
1926   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1927   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1928     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1929     if (TN->getVT() == MVT::i1) {
1930       SDLoc DL(N);
1931       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1932                                  DAG.getConstant(1, DL, VT));
1933       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1934     }
1935   }
1936
1937   return SDValue();
1938 }
1939
1940 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1941   SDValue N0 = N->getOperand(0);
1942   SDValue N1 = N->getOperand(1);
1943   EVT VT = N0.getValueType();
1944
1945   // If the flag result is dead, turn this into an SUB.
1946   if (!N->hasAnyUseOfValue(1))
1947     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1948                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1949                                  MVT::Glue));
1950
1951   // fold (subc x, x) -> 0 + no borrow
1952   if (N0 == N1) {
1953     SDLoc DL(N);
1954     return CombineTo(N, DAG.getConstant(0, DL, VT),
1955                      DAG.getNode(ISD::CARRY_FALSE, DL,
1956                                  MVT::Glue));
1957   }
1958
1959   // fold (subc x, 0) -> x + no borrow
1960   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1961   if (isNullConstant(N1))
1962     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963                                         MVT::Glue));
1964
1965   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1966   if (N0C && N0C->isAllOnesValue())
1967     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1968                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1969                                  MVT::Glue));
1970
1971   return SDValue();
1972 }
1973
1974 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1975   SDValue N0 = N->getOperand(0);
1976   SDValue N1 = N->getOperand(1);
1977   SDValue CarryIn = N->getOperand(2);
1978
1979   // fold (sube x, y, false) -> (subc x, y)
1980   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1981     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1982
1983   return SDValue();
1984 }
1985
1986 SDValue DAGCombiner::visitMUL(SDNode *N) {
1987   SDValue N0 = N->getOperand(0);
1988   SDValue N1 = N->getOperand(1);
1989   EVT VT = N0.getValueType();
1990
1991   // fold (mul x, undef) -> 0
1992   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1993     return DAG.getConstant(0, SDLoc(N), VT);
1994
1995   bool N0IsConst = false;
1996   bool N1IsConst = false;
1997   APInt ConstValue0, ConstValue1;
1998   // fold vector ops
1999   if (VT.isVector()) {
2000     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2001       return FoldedVOp;
2002
2003     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2004     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2005   } else {
2006     N0IsConst = isa<ConstantSDNode>(N0);
2007     if (N0IsConst)
2008       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2009     N1IsConst = isa<ConstantSDNode>(N1);
2010     if (N1IsConst)
2011       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2012   }
2013
2014   // fold (mul c1, c2) -> c1*c2
2015   if (N0IsConst && N1IsConst)
2016     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2017                                       N0.getNode(), N1.getNode());
2018
2019   // canonicalize constant to RHS (vector doesn't have to splat)
2020   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2021      !isConstantIntBuildVectorOrConstantInt(N1))
2022     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2023   // fold (mul x, 0) -> 0
2024   if (N1IsConst && ConstValue1 == 0)
2025     return N1;
2026   // We require a splat of the entire scalar bit width for non-contiguous
2027   // bit patterns.
2028   bool IsFullSplat =
2029     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2030   // fold (mul x, 1) -> x
2031   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2032     return N0;
2033   // fold (mul x, -1) -> 0-x
2034   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2035     SDLoc DL(N);
2036     return DAG.getNode(ISD::SUB, DL, VT,
2037                        DAG.getConstant(0, DL, VT), N0);
2038   }
2039   // fold (mul x, (1 << c)) -> x << c
2040   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2041     SDLoc DL(N);
2042     return DAG.getNode(ISD::SHL, DL, VT, N0,
2043                        DAG.getConstant(ConstValue1.logBase2(), DL,
2044                                        getShiftAmountTy(N0.getValueType())));
2045   }
2046   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2047   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2048     unsigned Log2Val = (-ConstValue1).logBase2();
2049     SDLoc DL(N);
2050     // FIXME: If the input is something that is easily negated (e.g. a
2051     // single-use add), we should put the negate there.
2052     return DAG.getNode(ISD::SUB, DL, VT,
2053                        DAG.getConstant(0, DL, VT),
2054                        DAG.getNode(ISD::SHL, DL, VT, N0,
2055                             DAG.getConstant(Log2Val, DL,
2056                                       getShiftAmountTy(N0.getValueType()))));
2057   }
2058
2059   APInt Val;
2060   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2061   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2062       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2063                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2064     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2065                              N1, N0.getOperand(1));
2066     AddToWorklist(C3.getNode());
2067     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2068                        N0.getOperand(0), C3);
2069   }
2070
2071   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2072   // use.
2073   {
2074     SDValue Sh(nullptr,0), Y(nullptr,0);
2075     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2076     if (N0.getOpcode() == ISD::SHL &&
2077         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2078                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2079         N0.getNode()->hasOneUse()) {
2080       Sh = N0; Y = N1;
2081     } else if (N1.getOpcode() == ISD::SHL &&
2082                isa<ConstantSDNode>(N1.getOperand(1)) &&
2083                N1.getNode()->hasOneUse()) {
2084       Sh = N1; Y = N0;
2085     }
2086
2087     if (Sh.getNode()) {
2088       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2089                                 Sh.getOperand(0), Y);
2090       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2091                          Mul, Sh.getOperand(1));
2092     }
2093   }
2094
2095   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2096   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2097       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2098                      isa<ConstantSDNode>(N0.getOperand(1))))
2099     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2100                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2101                                    N0.getOperand(0), N1),
2102                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2103                                    N0.getOperand(1), N1));
2104
2105   // reassociate mul
2106   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2107     return RMUL;
2108
2109   return SDValue();
2110 }
2111
2112 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2113   SDValue N0 = N->getOperand(0);
2114   SDValue N1 = N->getOperand(1);
2115   EVT VT = N->getValueType(0);
2116
2117   // fold vector ops
2118   if (VT.isVector())
2119     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2120       return FoldedVOp;
2121
2122   // fold (sdiv c1, c2) -> c1/c2
2123   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2124   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2125   if (N0C && N1C && N1C->isNullValue())
2126     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2127   // fold (sdiv X, 1) -> X
2128   if (N1C && N1C->getAPIntValue() == 1LL)
2129     return N0;
2130   // fold (sdiv X, -1) -> 0-X
2131   if (N1C && N1C->isAllOnesValue()) {
2132     SDLoc DL(N);
2133     return DAG.getNode(ISD::SUB, DL, VT,
2134                        DAG.getConstant(0, DL, VT), N0);
2135   }
2136   // If we know the sign bits of both operands are zero, strength reduce to a
2137   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2138   if (!VT.isVector()) {
2139     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2140       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2141                          N0, N1);
2142   }
2143
2144   // fold (sdiv X, pow2) -> simple ops after legalize
2145   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2146                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2147     // If dividing by powers of two is cheap, then don't perform the following
2148     // fold.
2149     if (TLI.isPow2SDivCheap())
2150       return SDValue();
2151
2152     // Target-specific implementation of sdiv x, pow2.
2153     SDValue Res = BuildSDIVPow2(N);
2154     if (Res.getNode())
2155       return Res;
2156
2157     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2158     SDLoc DL(N);
2159
2160     // Splat the sign bit into the register
2161     SDValue SGN =
2162         DAG.getNode(ISD::SRA, DL, VT, N0,
2163                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2164                                     getShiftAmountTy(N0.getValueType())));
2165     AddToWorklist(SGN.getNode());
2166
2167     // Add (N0 < 0) ? abs2 - 1 : 0;
2168     SDValue SRL =
2169         DAG.getNode(ISD::SRL, DL, VT, SGN,
2170                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2171                                     getShiftAmountTy(SGN.getValueType())));
2172     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2173     AddToWorklist(SRL.getNode());
2174     AddToWorklist(ADD.getNode());    // Divide by pow2
2175     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2176                   DAG.getConstant(lg2, DL,
2177                                   getShiftAmountTy(ADD.getValueType())));
2178
2179     // If we're dividing by a positive value, we're done.  Otherwise, we must
2180     // negate the result.
2181     if (N1C->getAPIntValue().isNonNegative())
2182       return SRA;
2183
2184     AddToWorklist(SRA.getNode());
2185     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2186   }
2187
2188   // If integer divide is expensive and we satisfy the requirements, emit an
2189   // alternate sequence.
2190   if (N1C && !TLI.isIntDivCheap()) {
2191     SDValue Op = BuildSDIV(N);
2192     if (Op.getNode()) return Op;
2193   }
2194
2195   // undef / X -> 0
2196   if (N0.getOpcode() == ISD::UNDEF)
2197     return DAG.getConstant(0, SDLoc(N), VT);
2198   // X / undef -> undef
2199   if (N1.getOpcode() == ISD::UNDEF)
2200     return N1;
2201
2202   return SDValue();
2203 }
2204
2205 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2206   SDValue N0 = N->getOperand(0);
2207   SDValue N1 = N->getOperand(1);
2208   EVT VT = N->getValueType(0);
2209
2210   // fold vector ops
2211   if (VT.isVector())
2212     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2213       return FoldedVOp;
2214
2215   // fold (udiv c1, c2) -> c1/c2
2216   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2217   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2218   if (N0C && N1C && !N1C->isNullValue())
2219     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2220   // fold (udiv x, (1 << c)) -> x >>u c
2221   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2222     SDLoc DL(N);
2223     return DAG.getNode(ISD::SRL, DL, VT, N0,
2224                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2225                                        getShiftAmountTy(N0.getValueType())));
2226   }
2227   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2228   if (N1.getOpcode() == ISD::SHL) {
2229     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2230       if (SHC->getAPIntValue().isPowerOf2()) {
2231         EVT ADDVT = N1.getOperand(1).getValueType();
2232         SDLoc DL(N);
2233         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2234                                   N1.getOperand(1),
2235                                   DAG.getConstant(SHC->getAPIntValue()
2236                                                                   .logBase2(),
2237                                                   DL, ADDVT));
2238         AddToWorklist(Add.getNode());
2239         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2240       }
2241     }
2242   }
2243   // fold (udiv x, c) -> alternate
2244   if (N1C && !TLI.isIntDivCheap()) {
2245     SDValue Op = BuildUDIV(N);
2246     if (Op.getNode()) return Op;
2247   }
2248
2249   // undef / X -> 0
2250   if (N0.getOpcode() == ISD::UNDEF)
2251     return DAG.getConstant(0, SDLoc(N), VT);
2252   // X / undef -> undef
2253   if (N1.getOpcode() == ISD::UNDEF)
2254     return N1;
2255
2256   return SDValue();
2257 }
2258
2259 SDValue DAGCombiner::visitSREM(SDNode *N) {
2260   SDValue N0 = N->getOperand(0);
2261   SDValue N1 = N->getOperand(1);
2262   EVT VT = N->getValueType(0);
2263
2264   // fold (srem c1, c2) -> c1%c2
2265   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2266   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2267   if (N0C && N1C && !N1C->isNullValue())
2268     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2269   // If we know the sign bits of both operands are zero, strength reduce to a
2270   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2271   if (!VT.isVector()) {
2272     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2273       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2274   }
2275
2276   // If X/C can be simplified by the division-by-constant logic, lower
2277   // X%C to the equivalent of X-X/C*C.
2278   if (N1C && !N1C->isNullValue()) {
2279     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2280     AddToWorklist(Div.getNode());
2281     SDValue OptimizedDiv = combine(Div.getNode());
2282     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2283       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2284                                 OptimizedDiv, N1);
2285       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2286       AddToWorklist(Mul.getNode());
2287       return Sub;
2288     }
2289   }
2290
2291   // undef % X -> 0
2292   if (N0.getOpcode() == ISD::UNDEF)
2293     return DAG.getConstant(0, SDLoc(N), VT);
2294   // X % undef -> undef
2295   if (N1.getOpcode() == ISD::UNDEF)
2296     return N1;
2297
2298   return SDValue();
2299 }
2300
2301 SDValue DAGCombiner::visitUREM(SDNode *N) {
2302   SDValue N0 = N->getOperand(0);
2303   SDValue N1 = N->getOperand(1);
2304   EVT VT = N->getValueType(0);
2305
2306   // fold (urem c1, c2) -> c1%c2
2307   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2308   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2309   if (N0C && N1C && !N1C->isNullValue())
2310     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2311   // fold (urem x, pow2) -> (and x, pow2-1)
2312   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2313     SDLoc DL(N);
2314     return DAG.getNode(ISD::AND, DL, VT, N0,
2315                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2316   }
2317   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2318   if (N1.getOpcode() == ISD::SHL) {
2319     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2320       if (SHC->getAPIntValue().isPowerOf2()) {
2321         SDLoc DL(N);
2322         SDValue Add =
2323           DAG.getNode(ISD::ADD, DL, VT, N1,
2324                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2325                                  VT));
2326         AddToWorklist(Add.getNode());
2327         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2328       }
2329     }
2330   }
2331
2332   // If X/C can be simplified by the division-by-constant logic, lower
2333   // X%C to the equivalent of X-X/C*C.
2334   if (N1C && !N1C->isNullValue()) {
2335     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2336     AddToWorklist(Div.getNode());
2337     SDValue OptimizedDiv = combine(Div.getNode());
2338     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2339       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2340                                 OptimizedDiv, N1);
2341       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2342       AddToWorklist(Mul.getNode());
2343       return Sub;
2344     }
2345   }
2346
2347   // undef % X -> 0
2348   if (N0.getOpcode() == ISD::UNDEF)
2349     return DAG.getConstant(0, SDLoc(N), VT);
2350   // X % undef -> undef
2351   if (N1.getOpcode() == ISD::UNDEF)
2352     return N1;
2353
2354   return SDValue();
2355 }
2356
2357 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2358   SDValue N0 = N->getOperand(0);
2359   SDValue N1 = N->getOperand(1);
2360   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2361   EVT VT = N->getValueType(0);
2362   SDLoc DL(N);
2363
2364   // fold (mulhs x, 0) -> 0
2365   if (isNullConstant(N1))
2366     return N1;
2367   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2368   if (N1C && N1C->getAPIntValue() == 1) {
2369     SDLoc DL(N);
2370     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2371                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2372                                        DL,
2373                                        getShiftAmountTy(N0.getValueType())));
2374   }
2375   // fold (mulhs x, undef) -> 0
2376   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2377     return DAG.getConstant(0, SDLoc(N), VT);
2378
2379   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2380   // plus a shift.
2381   if (VT.isSimple() && !VT.isVector()) {
2382     MVT Simple = VT.getSimpleVT();
2383     unsigned SimpleSize = Simple.getSizeInBits();
2384     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2385     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2386       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2387       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2388       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2389       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2390             DAG.getConstant(SimpleSize, DL,
2391                             getShiftAmountTy(N1.getValueType())));
2392       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2393     }
2394   }
2395
2396   return SDValue();
2397 }
2398
2399 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2400   SDValue N0 = N->getOperand(0);
2401   SDValue N1 = N->getOperand(1);
2402   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2403   EVT VT = N->getValueType(0);
2404   SDLoc DL(N);
2405
2406   // fold (mulhu x, 0) -> 0
2407   if (isNullConstant(N1))
2408     return N1;
2409   // fold (mulhu x, 1) -> 0
2410   if (N1C && N1C->getAPIntValue() == 1)
2411     return DAG.getConstant(0, DL, N0.getValueType());
2412   // fold (mulhu x, undef) -> 0
2413   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2414     return DAG.getConstant(0, DL, VT);
2415
2416   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2417   // plus a shift.
2418   if (VT.isSimple() && !VT.isVector()) {
2419     MVT Simple = VT.getSimpleVT();
2420     unsigned SimpleSize = Simple.getSizeInBits();
2421     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2424       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2425       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2426       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2427             DAG.getConstant(SimpleSize, DL,
2428                             getShiftAmountTy(N1.getValueType())));
2429       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2430     }
2431   }
2432
2433   return SDValue();
2434 }
2435
2436 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2437 /// give the opcodes for the two computations that are being performed. Return
2438 /// true if a simplification was made.
2439 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2440                                                 unsigned HiOp) {
2441   // If the high half is not needed, just compute the low half.
2442   bool HiExists = N->hasAnyUseOfValue(1);
2443   if (!HiExists &&
2444       (!LegalOperations ||
2445        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2446     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2447     return CombineTo(N, Res, Res);
2448   }
2449
2450   // If the low half is not needed, just compute the high half.
2451   bool LoExists = N->hasAnyUseOfValue(0);
2452   if (!LoExists &&
2453       (!LegalOperations ||
2454        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2455     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2456     return CombineTo(N, Res, Res);
2457   }
2458
2459   // If both halves are used, return as it is.
2460   if (LoExists && HiExists)
2461     return SDValue();
2462
2463   // If the two computed results can be simplified separately, separate them.
2464   if (LoExists) {
2465     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2466     AddToWorklist(Lo.getNode());
2467     SDValue LoOpt = combine(Lo.getNode());
2468     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2469         (!LegalOperations ||
2470          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2471       return CombineTo(N, LoOpt, LoOpt);
2472   }
2473
2474   if (HiExists) {
2475     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2476     AddToWorklist(Hi.getNode());
2477     SDValue HiOpt = combine(Hi.getNode());
2478     if (HiOpt.getNode() && HiOpt != Hi &&
2479         (!LegalOperations ||
2480          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2481       return CombineTo(N, HiOpt, HiOpt);
2482   }
2483
2484   return SDValue();
2485 }
2486
2487 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2488   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2489   if (Res.getNode()) return Res;
2490
2491   EVT VT = N->getValueType(0);
2492   SDLoc DL(N);
2493
2494   // If the type is twice as wide is legal, transform the mulhu to a wider
2495   // multiply plus a shift.
2496   if (VT.isSimple() && !VT.isVector()) {
2497     MVT Simple = VT.getSimpleVT();
2498     unsigned SimpleSize = Simple.getSizeInBits();
2499     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2500     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2501       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2502       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2503       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2504       // Compute the high part as N1.
2505       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2506             DAG.getConstant(SimpleSize, DL,
2507                             getShiftAmountTy(Lo.getValueType())));
2508       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2509       // Compute the low part as N0.
2510       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2511       return CombineTo(N, Lo, Hi);
2512     }
2513   }
2514
2515   return SDValue();
2516 }
2517
2518 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2519   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2520   if (Res.getNode()) return Res;
2521
2522   EVT VT = N->getValueType(0);
2523   SDLoc DL(N);
2524
2525   // If the type is twice as wide is legal, transform the mulhu to a wider
2526   // multiply plus a shift.
2527   if (VT.isSimple() && !VT.isVector()) {
2528     MVT Simple = VT.getSimpleVT();
2529     unsigned SimpleSize = Simple.getSizeInBits();
2530     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2531     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2532       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2533       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2534       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2535       // Compute the high part as N1.
2536       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2537             DAG.getConstant(SimpleSize, DL,
2538                             getShiftAmountTy(Lo.getValueType())));
2539       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2540       // Compute the low part as N0.
2541       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2542       return CombineTo(N, Lo, Hi);
2543     }
2544   }
2545
2546   return SDValue();
2547 }
2548
2549 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2550   // (smulo x, 2) -> (saddo x, x)
2551   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2552     if (C2->getAPIntValue() == 2)
2553       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2554                          N->getOperand(0), N->getOperand(0));
2555
2556   return SDValue();
2557 }
2558
2559 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2560   // (umulo x, 2) -> (uaddo x, x)
2561   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2562     if (C2->getAPIntValue() == 2)
2563       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2564                          N->getOperand(0), N->getOperand(0));
2565
2566   return SDValue();
2567 }
2568
2569 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2570   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2571   if (Res.getNode()) return Res;
2572
2573   return SDValue();
2574 }
2575
2576 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2577   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2578   if (Res.getNode()) return Res;
2579
2580   return SDValue();
2581 }
2582
2583 /// If this is a binary operator with two operands of the same opcode, try to
2584 /// simplify it.
2585 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2586   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2587   EVT VT = N0.getValueType();
2588   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2589
2590   // Bail early if none of these transforms apply.
2591   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2592
2593   // For each of OP in AND/OR/XOR:
2594   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2595   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2596   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2597   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2598   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2599   //
2600   // do not sink logical op inside of a vector extend, since it may combine
2601   // into a vsetcc.
2602   EVT Op0VT = N0.getOperand(0).getValueType();
2603   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2604        N0.getOpcode() == ISD::SIGN_EXTEND ||
2605        N0.getOpcode() == ISD::BSWAP ||
2606        // Avoid infinite looping with PromoteIntBinOp.
2607        (N0.getOpcode() == ISD::ANY_EXTEND &&
2608         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2609        (N0.getOpcode() == ISD::TRUNCATE &&
2610         (!TLI.isZExtFree(VT, Op0VT) ||
2611          !TLI.isTruncateFree(Op0VT, VT)) &&
2612         TLI.isTypeLegal(Op0VT))) &&
2613       !VT.isVector() &&
2614       Op0VT == N1.getOperand(0).getValueType() &&
2615       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2616     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2617                                  N0.getOperand(0).getValueType(),
2618                                  N0.getOperand(0), N1.getOperand(0));
2619     AddToWorklist(ORNode.getNode());
2620     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2621   }
2622
2623   // For each of OP in SHL/SRL/SRA/AND...
2624   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2625   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2626   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2627   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2628        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2629       N0.getOperand(1) == N1.getOperand(1)) {
2630     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2631                                  N0.getOperand(0).getValueType(),
2632                                  N0.getOperand(0), N1.getOperand(0));
2633     AddToWorklist(ORNode.getNode());
2634     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2635                        ORNode, N0.getOperand(1));
2636   }
2637
2638   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2639   // Only perform this optimization after type legalization and before
2640   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2641   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2642   // we don't want to undo this promotion.
2643   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2644   // on scalars.
2645   if ((N0.getOpcode() == ISD::BITCAST ||
2646        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2647       Level == AfterLegalizeTypes) {
2648     SDValue In0 = N0.getOperand(0);
2649     SDValue In1 = N1.getOperand(0);
2650     EVT In0Ty = In0.getValueType();
2651     EVT In1Ty = In1.getValueType();
2652     SDLoc DL(N);
2653     // If both incoming values are integers, and the original types are the
2654     // same.
2655     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2656       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2657       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2658       AddToWorklist(Op.getNode());
2659       return BC;
2660     }
2661   }
2662
2663   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2664   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2665   // If both shuffles use the same mask, and both shuffle within a single
2666   // vector, then it is worthwhile to move the swizzle after the operation.
2667   // The type-legalizer generates this pattern when loading illegal
2668   // vector types from memory. In many cases this allows additional shuffle
2669   // optimizations.
2670   // There are other cases where moving the shuffle after the xor/and/or
2671   // is profitable even if shuffles don't perform a swizzle.
2672   // If both shuffles use the same mask, and both shuffles have the same first
2673   // or second operand, then it might still be profitable to move the shuffle
2674   // after the xor/and/or operation.
2675   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2676     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2677     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2678
2679     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2680            "Inputs to shuffles are not the same type");
2681
2682     // Check that both shuffles use the same mask. The masks are known to be of
2683     // the same length because the result vector type is the same.
2684     // Check also that shuffles have only one use to avoid introducing extra
2685     // instructions.
2686     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2687         SVN0->getMask().equals(SVN1->getMask())) {
2688       SDValue ShOp = N0->getOperand(1);
2689
2690       // Don't try to fold this node if it requires introducing a
2691       // build vector of all zeros that might be illegal at this stage.
2692       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2693         if (!LegalTypes)
2694           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2695         else
2696           ShOp = SDValue();
2697       }
2698
2699       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2700       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2701       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2702       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2703         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2704                                       N0->getOperand(0), N1->getOperand(0));
2705         AddToWorklist(NewNode.getNode());
2706         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2707                                     &SVN0->getMask()[0]);
2708       }
2709
2710       // Don't try to fold this node if it requires introducing a
2711       // build vector of all zeros that might be illegal at this stage.
2712       ShOp = N0->getOperand(0);
2713       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2714         if (!LegalTypes)
2715           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2716         else
2717           ShOp = SDValue();
2718       }
2719
2720       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2721       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2722       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2723       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2724         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2725                                       N0->getOperand(1), N1->getOperand(1));
2726         AddToWorklist(NewNode.getNode());
2727         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2728                                     &SVN0->getMask()[0]);
2729       }
2730     }
2731   }
2732
2733   return SDValue();
2734 }
2735
2736 /// This contains all DAGCombine rules which reduce two values combined by
2737 /// an And operation to a single value. This makes them reusable in the context
2738 /// of visitSELECT(). Rules involving constants are not included as
2739 /// visitSELECT() already handles those cases.
2740 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2741                                   SDNode *LocReference) {
2742   EVT VT = N1.getValueType();
2743
2744   // fold (and x, undef) -> 0
2745   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2746     return DAG.getConstant(0, SDLoc(LocReference), VT);
2747   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2748   SDValue LL, LR, RL, RR, CC0, CC1;
2749   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2750     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2751     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2752
2753     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2754         LL.getValueType().isInteger()) {
2755       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2756       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2757         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2758                                      LR.getValueType(), LL, RL);
2759         AddToWorklist(ORNode.getNode());
2760         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2761       }
2762       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2763       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2764         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2765                                       LR.getValueType(), LL, RL);
2766         AddToWorklist(ANDNode.getNode());
2767         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2768       }
2769       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2770       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2771         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2772                                      LR.getValueType(), LL, RL);
2773         AddToWorklist(ORNode.getNode());
2774         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2775       }
2776     }
2777     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2778     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2779         Op0 == Op1 && LL.getValueType().isInteger() &&
2780       Op0 == ISD::SETNE && ((isNullConstant(LR) &&
2781                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2782                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2783                                  isNullConstant(RR)))) {
2784       SDLoc DL(N0);
2785       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2786                                     LL, DAG.getConstant(1, DL,
2787                                                         LL.getValueType()));
2788       AddToWorklist(ADDNode.getNode());
2789       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2790                           DAG.getConstant(2, DL, LL.getValueType()),
2791                           ISD::SETUGE);
2792     }
2793     // canonicalize equivalent to ll == rl
2794     if (LL == RR && LR == RL) {
2795       Op1 = ISD::getSetCCSwappedOperands(Op1);
2796       std::swap(RL, RR);
2797     }
2798     if (LL == RL && LR == RR) {
2799       bool isInteger = LL.getValueType().isInteger();
2800       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2801       if (Result != ISD::SETCC_INVALID &&
2802           (!LegalOperations ||
2803            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2804             TLI.isOperationLegal(ISD::SETCC,
2805                             getSetCCResultType(N0.getSimpleValueType())))))
2806         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2807                             LL, LR, Result);
2808     }
2809   }
2810
2811   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2812       VT.getSizeInBits() <= 64) {
2813     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2814       APInt ADDC = ADDI->getAPIntValue();
2815       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2816         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2817         // immediate for an add, but it is legal if its top c2 bits are set,
2818         // transform the ADD so the immediate doesn't need to be materialized
2819         // in a register.
2820         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2821           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2822                                              SRLI->getZExtValue());
2823           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2824             ADDC |= Mask;
2825             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2826               SDLoc DL(N0);
2827               SDValue NewAdd =
2828                 DAG.getNode(ISD::ADD, DL, VT,
2829                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2830               CombineTo(N0.getNode(), NewAdd);
2831               // Return N so it doesn't get rechecked!
2832               return SDValue(LocReference, 0);
2833             }
2834           }
2835         }
2836       }
2837     }
2838   }
2839
2840   return SDValue();
2841 }
2842
2843 SDValue DAGCombiner::visitAND(SDNode *N) {
2844   SDValue N0 = N->getOperand(0);
2845   SDValue N1 = N->getOperand(1);
2846   EVT VT = N1.getValueType();
2847
2848   // fold vector ops
2849   if (VT.isVector()) {
2850     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2851       return FoldedVOp;
2852
2853     // fold (and x, 0) -> 0, vector edition
2854     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2855       // do not return N0, because undef node may exist in N0
2856       return DAG.getConstant(
2857           APInt::getNullValue(
2858               N0.getValueType().getScalarType().getSizeInBits()),
2859           SDLoc(N), N0.getValueType());
2860     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2861       // do not return N1, because undef node may exist in N1
2862       return DAG.getConstant(
2863           APInt::getNullValue(
2864               N1.getValueType().getScalarType().getSizeInBits()),
2865           SDLoc(N), N1.getValueType());
2866
2867     // fold (and x, -1) -> x, vector edition
2868     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2869       return N1;
2870     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2871       return N0;
2872   }
2873
2874   // fold (and c1, c2) -> c1&c2
2875   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2876   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2877   if (N0C && N1C)
2878     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2879   // canonicalize constant to RHS
2880   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2881      !isConstantIntBuildVectorOrConstantInt(N1))
2882     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2883   // fold (and x, -1) -> x
2884   if (N1C && N1C->isAllOnesValue())
2885     return N0;
2886   // if (and x, c) is known to be zero, return 0
2887   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2888   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2889                                    APInt::getAllOnesValue(BitWidth)))
2890     return DAG.getConstant(0, SDLoc(N), VT);
2891   // reassociate and
2892   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2893     return RAND;
2894   // fold (and (or x, C), D) -> D if (C & D) == D
2895   if (N1C && N0.getOpcode() == ISD::OR)
2896     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2897       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2898         return N1;
2899   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2900   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2901     SDValue N0Op0 = N0.getOperand(0);
2902     APInt Mask = ~N1C->getAPIntValue();
2903     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2904     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2905       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2906                                  N0.getValueType(), N0Op0);
2907
2908       // Replace uses of the AND with uses of the Zero extend node.
2909       CombineTo(N, Zext);
2910
2911       // We actually want to replace all uses of the any_extend with the
2912       // zero_extend, to avoid duplicating things.  This will later cause this
2913       // AND to be folded.
2914       CombineTo(N0.getNode(), Zext);
2915       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2916     }
2917   }
2918   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2919   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2920   // already be zero by virtue of the width of the base type of the load.
2921   //
2922   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2923   // more cases.
2924   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2925        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2926       N0.getOpcode() == ISD::LOAD) {
2927     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2928                                          N0 : N0.getOperand(0) );
2929
2930     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2931     // This can be a pure constant or a vector splat, in which case we treat the
2932     // vector as a scalar and use the splat value.
2933     APInt Constant = APInt::getNullValue(1);
2934     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2935       Constant = C->getAPIntValue();
2936     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2937       APInt SplatValue, SplatUndef;
2938       unsigned SplatBitSize;
2939       bool HasAnyUndefs;
2940       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2941                                              SplatBitSize, HasAnyUndefs);
2942       if (IsSplat) {
2943         // Undef bits can contribute to a possible optimisation if set, so
2944         // set them.
2945         SplatValue |= SplatUndef;
2946
2947         // The splat value may be something like "0x00FFFFFF", which means 0 for
2948         // the first vector value and FF for the rest, repeating. We need a mask
2949         // that will apply equally to all members of the vector, so AND all the
2950         // lanes of the constant together.
2951         EVT VT = Vector->getValueType(0);
2952         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2953
2954         // If the splat value has been compressed to a bitlength lower
2955         // than the size of the vector lane, we need to re-expand it to
2956         // the lane size.
2957         if (BitWidth > SplatBitSize)
2958           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2959                SplatBitSize < BitWidth;
2960                SplatBitSize = SplatBitSize * 2)
2961             SplatValue |= SplatValue.shl(SplatBitSize);
2962
2963         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2964         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2965         if (SplatBitSize % BitWidth == 0) {
2966           Constant = APInt::getAllOnesValue(BitWidth);
2967           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2968             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2969         }
2970       }
2971     }
2972
2973     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2974     // actually legal and isn't going to get expanded, else this is a false
2975     // optimisation.
2976     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2977                                                     Load->getValueType(0),
2978                                                     Load->getMemoryVT());
2979
2980     // Resize the constant to the same size as the original memory access before
2981     // extension. If it is still the AllOnesValue then this AND is completely
2982     // unneeded.
2983     Constant =
2984       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2985
2986     bool B;
2987     switch (Load->getExtensionType()) {
2988     default: B = false; break;
2989     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2990     case ISD::ZEXTLOAD:
2991     case ISD::NON_EXTLOAD: B = true; break;
2992     }
2993
2994     if (B && Constant.isAllOnesValue()) {
2995       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2996       // preserve semantics once we get rid of the AND.
2997       SDValue NewLoad(Load, 0);
2998       if (Load->getExtensionType() == ISD::EXTLOAD) {
2999         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3000                               Load->getValueType(0), SDLoc(Load),
3001                               Load->getChain(), Load->getBasePtr(),
3002                               Load->getOffset(), Load->getMemoryVT(),
3003                               Load->getMemOperand());
3004         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3005         if (Load->getNumValues() == 3) {
3006           // PRE/POST_INC loads have 3 values.
3007           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3008                            NewLoad.getValue(2) };
3009           CombineTo(Load, To, 3, true);
3010         } else {
3011           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3012         }
3013       }
3014
3015       // Fold the AND away, taking care not to fold to the old load node if we
3016       // replaced it.
3017       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3018
3019       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3020     }
3021   }
3022
3023   // fold (and (load x), 255) -> (zextload x, i8)
3024   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3025   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3026   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3027               (N0.getOpcode() == ISD::ANY_EXTEND &&
3028                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3029     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3030     LoadSDNode *LN0 = HasAnyExt
3031       ? cast<LoadSDNode>(N0.getOperand(0))
3032       : cast<LoadSDNode>(N0);
3033     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3034         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3035       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3036       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3037         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3038         EVT LoadedVT = LN0->getMemoryVT();
3039         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3040
3041         if (ExtVT == LoadedVT &&
3042             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3043                                                     ExtVT))) {
3044
3045           SDValue NewLoad =
3046             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3047                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3048                            LN0->getMemOperand());
3049           AddToWorklist(N);
3050           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3051           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3052         }
3053
3054         // Do not change the width of a volatile load.
3055         // Do not generate loads of non-round integer types since these can
3056         // be expensive (and would be wrong if the type is not byte sized).
3057         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3058             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3059                                                     ExtVT))) {
3060           EVT PtrType = LN0->getOperand(1).getValueType();
3061
3062           unsigned Alignment = LN0->getAlignment();
3063           SDValue NewPtr = LN0->getBasePtr();
3064
3065           // For big endian targets, we need to add an offset to the pointer
3066           // to load the correct bytes.  For little endian systems, we merely
3067           // need to read fewer bytes from the same pointer.
3068           if (TLI.isBigEndian()) {
3069             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3070             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3071             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3072             SDLoc DL(LN0);
3073             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3074                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3075             Alignment = MinAlign(Alignment, PtrOff);
3076           }
3077
3078           AddToWorklist(NewPtr.getNode());
3079
3080           SDValue Load =
3081             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3082                            LN0->getChain(), NewPtr,
3083                            LN0->getPointerInfo(),
3084                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3085                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3086           AddToWorklist(N);
3087           CombineTo(LN0, Load, Load.getValue(1));
3088           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3089         }
3090       }
3091     }
3092   }
3093
3094   if (SDValue Combined = visitANDLike(N0, N1, N))
3095     return Combined;
3096
3097   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3098   if (N0.getOpcode() == N1.getOpcode()) {
3099     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3100     if (Tmp.getNode()) return Tmp;
3101   }
3102
3103   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3104   // fold (and (sra)) -> (and (srl)) when possible.
3105   if (!VT.isVector() &&
3106       SimplifyDemandedBits(SDValue(N, 0)))
3107     return SDValue(N, 0);
3108
3109   // fold (zext_inreg (extload x)) -> (zextload x)
3110   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3111     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3112     EVT MemVT = LN0->getMemoryVT();
3113     // If we zero all the possible extended bits, then we can turn this into
3114     // a zextload if we are running before legalize or the operation is legal.
3115     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3116     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3117                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3118         ((!LegalOperations && !LN0->isVolatile()) ||
3119          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3120       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3121                                        LN0->getChain(), LN0->getBasePtr(),
3122                                        MemVT, LN0->getMemOperand());
3123       AddToWorklist(N);
3124       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3125       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3126     }
3127   }
3128   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3129   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3130       N0.hasOneUse()) {
3131     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3132     EVT MemVT = LN0->getMemoryVT();
3133     // If we zero all the possible extended bits, then we can turn this into
3134     // a zextload if we are running before legalize or the operation is legal.
3135     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3136     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3137                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3138         ((!LegalOperations && !LN0->isVolatile()) ||
3139          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3140       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3141                                        LN0->getChain(), LN0->getBasePtr(),
3142                                        MemVT, LN0->getMemOperand());
3143       AddToWorklist(N);
3144       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3145       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3146     }
3147   }
3148   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3149   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3150     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3151                                        N0.getOperand(1), false);
3152     if (BSwap.getNode())
3153       return BSwap;
3154   }
3155
3156   return SDValue();
3157 }
3158
3159 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3160 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3161                                         bool DemandHighBits) {
3162   if (!LegalOperations)
3163     return SDValue();
3164
3165   EVT VT = N->getValueType(0);
3166   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3167     return SDValue();
3168   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3169     return SDValue();
3170
3171   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3172   bool LookPassAnd0 = false;
3173   bool LookPassAnd1 = false;
3174   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3175       std::swap(N0, N1);
3176   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3177       std::swap(N0, N1);
3178   if (N0.getOpcode() == ISD::AND) {
3179     if (!N0.getNode()->hasOneUse())
3180       return SDValue();
3181     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3182     if (!N01C || N01C->getZExtValue() != 0xFF00)
3183       return SDValue();
3184     N0 = N0.getOperand(0);
3185     LookPassAnd0 = true;
3186   }
3187
3188   if (N1.getOpcode() == ISD::AND) {
3189     if (!N1.getNode()->hasOneUse())
3190       return SDValue();
3191     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3192     if (!N11C || N11C->getZExtValue() != 0xFF)
3193       return SDValue();
3194     N1 = N1.getOperand(0);
3195     LookPassAnd1 = true;
3196   }
3197
3198   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3199     std::swap(N0, N1);
3200   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3201     return SDValue();
3202   if (!N0.getNode()->hasOneUse() ||
3203       !N1.getNode()->hasOneUse())
3204     return SDValue();
3205
3206   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3208   if (!N01C || !N11C)
3209     return SDValue();
3210   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3211     return SDValue();
3212
3213   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3214   SDValue N00 = N0->getOperand(0);
3215   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3216     if (!N00.getNode()->hasOneUse())
3217       return SDValue();
3218     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3219     if (!N001C || N001C->getZExtValue() != 0xFF)
3220       return SDValue();
3221     N00 = N00.getOperand(0);
3222     LookPassAnd0 = true;
3223   }
3224
3225   SDValue N10 = N1->getOperand(0);
3226   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3227     if (!N10.getNode()->hasOneUse())
3228       return SDValue();
3229     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3230     if (!N101C || N101C->getZExtValue() != 0xFF00)
3231       return SDValue();
3232     N10 = N10.getOperand(0);
3233     LookPassAnd1 = true;
3234   }
3235
3236   if (N00 != N10)
3237     return SDValue();
3238
3239   // Make sure everything beyond the low halfword gets set to zero since the SRL
3240   // 16 will clear the top bits.
3241   unsigned OpSizeInBits = VT.getSizeInBits();
3242   if (DemandHighBits && OpSizeInBits > 16) {
3243     // If the left-shift isn't masked out then the only way this is a bswap is
3244     // if all bits beyond the low 8 are 0. In that case the entire pattern
3245     // reduces to a left shift anyway: leave it for other parts of the combiner.
3246     if (!LookPassAnd0)
3247       return SDValue();
3248
3249     // However, if the right shift isn't masked out then it might be because
3250     // it's not needed. See if we can spot that too.
3251     if (!LookPassAnd1 &&
3252         !DAG.MaskedValueIsZero(
3253             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3254       return SDValue();
3255   }
3256
3257   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3258   if (OpSizeInBits > 16) {
3259     SDLoc DL(N);
3260     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3261                       DAG.getConstant(OpSizeInBits - 16, DL,
3262                                       getShiftAmountTy(VT)));
3263   }
3264   return Res;
3265 }
3266
3267 /// Return true if the specified node is an element that makes up a 32-bit
3268 /// packed halfword byteswap.
3269 /// ((x & 0x000000ff) << 8) |
3270 /// ((x & 0x0000ff00) >> 8) |
3271 /// ((x & 0x00ff0000) << 8) |
3272 /// ((x & 0xff000000) >> 8)
3273 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3274   if (!N.getNode()->hasOneUse())
3275     return false;
3276
3277   unsigned Opc = N.getOpcode();
3278   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3279     return false;
3280
3281   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3282   if (!N1C)
3283     return false;
3284
3285   unsigned Num;
3286   switch (N1C->getZExtValue()) {
3287   default:
3288     return false;
3289   case 0xFF:       Num = 0; break;
3290   case 0xFF00:     Num = 1; break;
3291   case 0xFF0000:   Num = 2; break;
3292   case 0xFF000000: Num = 3; break;
3293   }
3294
3295   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3296   SDValue N0 = N.getOperand(0);
3297   if (Opc == ISD::AND) {
3298     if (Num == 0 || Num == 2) {
3299       // (x >> 8) & 0xff
3300       // (x >> 8) & 0xff0000
3301       if (N0.getOpcode() != ISD::SRL)
3302         return false;
3303       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3304       if (!C || C->getZExtValue() != 8)
3305         return false;
3306     } else {
3307       // (x << 8) & 0xff00
3308       // (x << 8) & 0xff000000
3309       if (N0.getOpcode() != ISD::SHL)
3310         return false;
3311       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3312       if (!C || C->getZExtValue() != 8)
3313         return false;
3314     }
3315   } else if (Opc == ISD::SHL) {
3316     // (x & 0xff) << 8
3317     // (x & 0xff0000) << 8
3318     if (Num != 0 && Num != 2)
3319       return false;
3320     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3321     if (!C || C->getZExtValue() != 8)
3322       return false;
3323   } else { // Opc == ISD::SRL
3324     // (x & 0xff00) >> 8
3325     // (x & 0xff000000) >> 8
3326     if (Num != 1 && Num != 3)
3327       return false;
3328     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3329     if (!C || C->getZExtValue() != 8)
3330       return false;
3331   }
3332
3333   if (Parts[Num])
3334     return false;
3335
3336   Parts[Num] = N0.getOperand(0).getNode();
3337   return true;
3338 }
3339
3340 /// Match a 32-bit packed halfword bswap. That is
3341 /// ((x & 0x000000ff) << 8) |
3342 /// ((x & 0x0000ff00) >> 8) |
3343 /// ((x & 0x00ff0000) << 8) |
3344 /// ((x & 0xff000000) >> 8)
3345 /// => (rotl (bswap x), 16)
3346 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3347   if (!LegalOperations)
3348     return SDValue();
3349
3350   EVT VT = N->getValueType(0);
3351   if (VT != MVT::i32)
3352     return SDValue();
3353   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3354     return SDValue();
3355
3356   // Look for either
3357   // (or (or (and), (and)), (or (and), (and)))
3358   // (or (or (or (and), (and)), (and)), (and))
3359   if (N0.getOpcode() != ISD::OR)
3360     return SDValue();
3361   SDValue N00 = N0.getOperand(0);
3362   SDValue N01 = N0.getOperand(1);
3363   SDNode *Parts[4] = {};
3364
3365   if (N1.getOpcode() == ISD::OR &&
3366       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3367     // (or (or (and), (and)), (or (and), (and)))
3368     SDValue N000 = N00.getOperand(0);
3369     if (!isBSwapHWordElement(N000, Parts))
3370       return SDValue();
3371
3372     SDValue N001 = N00.getOperand(1);
3373     if (!isBSwapHWordElement(N001, Parts))
3374       return SDValue();
3375     SDValue N010 = N01.getOperand(0);
3376     if (!isBSwapHWordElement(N010, Parts))
3377       return SDValue();
3378     SDValue N011 = N01.getOperand(1);
3379     if (!isBSwapHWordElement(N011, Parts))
3380       return SDValue();
3381   } else {
3382     // (or (or (or (and), (and)), (and)), (and))
3383     if (!isBSwapHWordElement(N1, Parts))
3384       return SDValue();
3385     if (!isBSwapHWordElement(N01, Parts))
3386       return SDValue();
3387     if (N00.getOpcode() != ISD::OR)
3388       return SDValue();
3389     SDValue N000 = N00.getOperand(0);
3390     if (!isBSwapHWordElement(N000, Parts))
3391       return SDValue();
3392     SDValue N001 = N00.getOperand(1);
3393     if (!isBSwapHWordElement(N001, Parts))
3394       return SDValue();
3395   }
3396
3397   // Make sure the parts are all coming from the same node.
3398   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3399     return SDValue();
3400
3401   SDLoc DL(N);
3402   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3403                               SDValue(Parts[0], 0));
3404
3405   // Result of the bswap should be rotated by 16. If it's not legal, then
3406   // do  (x << 16) | (x >> 16).
3407   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3408   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3409     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3410   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3411     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3412   return DAG.getNode(ISD::OR, DL, VT,
3413                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3414                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3415 }
3416
3417 /// This contains all DAGCombine rules which reduce two values combined by
3418 /// an Or operation to a single value \see visitANDLike().
3419 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3420   EVT VT = N1.getValueType();
3421   // fold (or x, undef) -> -1
3422   if (!LegalOperations &&
3423       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3424     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3425     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3426                            SDLoc(LocReference), VT);
3427   }
3428   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3429   SDValue LL, LR, RL, RR, CC0, CC1;
3430   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3431     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3432     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3433
3434     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3435         LL.getValueType().isInteger()) {
3436       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3437       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3438       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3439         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3440                                      LR.getValueType(), LL, RL);
3441         AddToWorklist(ORNode.getNode());
3442         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3443       }
3444       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3445       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3446       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3447           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3448         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3449                                       LR.getValueType(), LL, RL);
3450         AddToWorklist(ANDNode.getNode());
3451         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3452       }
3453     }
3454     // canonicalize equivalent to ll == rl
3455     if (LL == RR && LR == RL) {
3456       Op1 = ISD::getSetCCSwappedOperands(Op1);
3457       std::swap(RL, RR);
3458     }
3459     if (LL == RL && LR == RR) {
3460       bool isInteger = LL.getValueType().isInteger();
3461       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3462       if (Result != ISD::SETCC_INVALID &&
3463           (!LegalOperations ||
3464            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3465             TLI.isOperationLegal(ISD::SETCC,
3466               getSetCCResultType(N0.getValueType())))))
3467         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3468                             LL, LR, Result);
3469     }
3470   }
3471
3472   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3473   if (N0.getOpcode() == ISD::AND &&
3474       N1.getOpcode() == ISD::AND &&
3475       N0.getOperand(1).getOpcode() == ISD::Constant &&
3476       N1.getOperand(1).getOpcode() == ISD::Constant &&
3477       // Don't increase # computations.
3478       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3479     // We can only do this xform if we know that bits from X that are set in C2
3480     // but not in C1 are already zero.  Likewise for Y.
3481     const APInt &LHSMask =
3482       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3483     const APInt &RHSMask =
3484       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3485
3486     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3487         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3488       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3489                               N0.getOperand(0), N1.getOperand(0));
3490       SDLoc DL(LocReference);
3491       return DAG.getNode(ISD::AND, DL, VT, X,
3492                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3493     }
3494   }
3495
3496   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3497   if (N0.getOpcode() == ISD::AND &&
3498       N1.getOpcode() == ISD::AND &&
3499       N0.getOperand(0) == N1.getOperand(0) &&
3500       // Don't increase # computations.
3501       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3502     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3503                             N0.getOperand(1), N1.getOperand(1));
3504     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3505   }
3506
3507   return SDValue();
3508 }
3509
3510 SDValue DAGCombiner::visitOR(SDNode *N) {
3511   SDValue N0 = N->getOperand(0);
3512   SDValue N1 = N->getOperand(1);
3513   EVT VT = N1.getValueType();
3514
3515   // fold vector ops
3516   if (VT.isVector()) {
3517     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3518       return FoldedVOp;
3519
3520     // fold (or x, 0) -> x, vector edition
3521     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3522       return N1;
3523     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3524       return N0;
3525
3526     // fold (or x, -1) -> -1, vector edition
3527     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3528       // do not return N0, because undef node may exist in N0
3529       return DAG.getConstant(
3530           APInt::getAllOnesValue(
3531               N0.getValueType().getScalarType().getSizeInBits()),
3532           SDLoc(N), N0.getValueType());
3533     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3534       // do not return N1, because undef node may exist in N1
3535       return DAG.getConstant(
3536           APInt::getAllOnesValue(
3537               N1.getValueType().getScalarType().getSizeInBits()),
3538           SDLoc(N), N1.getValueType());
3539
3540     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3541     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3542     // Do this only if the resulting shuffle is legal.
3543     if (isa<ShuffleVectorSDNode>(N0) &&
3544         isa<ShuffleVectorSDNode>(N1) &&
3545         // Avoid folding a node with illegal type.
3546         TLI.isTypeLegal(VT) &&
3547         N0->getOperand(1) == N1->getOperand(1) &&
3548         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3549       bool CanFold = true;
3550       unsigned NumElts = VT.getVectorNumElements();
3551       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3552       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3553       // We construct two shuffle masks:
3554       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3555       // and N1 as the second operand.
3556       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3557       // and N0 as the second operand.
3558       // We do this because OR is commutable and therefore there might be
3559       // two ways to fold this node into a shuffle.
3560       SmallVector<int,4> Mask1;
3561       SmallVector<int,4> Mask2;
3562
3563       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3564         int M0 = SV0->getMaskElt(i);
3565         int M1 = SV1->getMaskElt(i);
3566
3567         // Both shuffle indexes are undef. Propagate Undef.
3568         if (M0 < 0 && M1 < 0) {
3569           Mask1.push_back(M0);
3570           Mask2.push_back(M0);
3571           continue;
3572         }
3573
3574         if (M0 < 0 || M1 < 0 ||
3575             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3576             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3577           CanFold = false;
3578           break;
3579         }
3580
3581         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3582         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3583       }
3584
3585       if (CanFold) {
3586         // Fold this sequence only if the resulting shuffle is 'legal'.
3587         if (TLI.isShuffleMaskLegal(Mask1, VT))
3588           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3589                                       N1->getOperand(0), &Mask1[0]);
3590         if (TLI.isShuffleMaskLegal(Mask2, VT))
3591           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3592                                       N0->getOperand(0), &Mask2[0]);
3593       }
3594     }
3595   }
3596
3597   // fold (or c1, c2) -> c1|c2
3598   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3599   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3600   if (N0C && N1C)
3601     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3602   // canonicalize constant to RHS
3603   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3604      !isConstantIntBuildVectorOrConstantInt(N1))
3605     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3606   // fold (or x, 0) -> x
3607   if (isNullConstant(N1))
3608     return N0;
3609   // fold (or x, -1) -> -1
3610   if (N1C && N1C->isAllOnesValue())
3611     return N1;
3612   // fold (or x, c) -> c iff (x & ~c) == 0
3613   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3614     return N1;
3615
3616   if (SDValue Combined = visitORLike(N0, N1, N))
3617     return Combined;
3618
3619   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3620   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3621   if (BSwap.getNode())
3622     return BSwap;
3623   BSwap = MatchBSwapHWordLow(N, N0, N1);
3624   if (BSwap.getNode())
3625     return BSwap;
3626
3627   // reassociate or
3628   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3629     return ROR;
3630   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3631   // iff (c1 & c2) == 0.
3632   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3633              isa<ConstantSDNode>(N0.getOperand(1))) {
3634     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3635     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3636       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3637                                                    N1C, C1))
3638         return DAG.getNode(
3639             ISD::AND, SDLoc(N), VT,
3640             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3641       return SDValue();
3642     }
3643   }
3644   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3645   if (N0.getOpcode() == N1.getOpcode()) {
3646     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3647     if (Tmp.getNode()) return Tmp;
3648   }
3649
3650   // See if this is some rotate idiom.
3651   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3652     return SDValue(Rot, 0);
3653
3654   // Simplify the operands using demanded-bits information.
3655   if (!VT.isVector() &&
3656       SimplifyDemandedBits(SDValue(N, 0)))
3657     return SDValue(N, 0);
3658
3659   return SDValue();
3660 }
3661
3662 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3663 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3664   if (Op.getOpcode() == ISD::AND) {
3665     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3666       Mask = Op.getOperand(1);
3667       Op = Op.getOperand(0);
3668     } else {
3669       return false;
3670     }
3671   }
3672
3673   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3674     Shift = Op;
3675     return true;
3676   }
3677
3678   return false;
3679 }
3680
3681 // Return true if we can prove that, whenever Neg and Pos are both in the
3682 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3683 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3684 //
3685 //     (or (shift1 X, Neg), (shift2 X, Pos))
3686 //
3687 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3688 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3689 // to consider shift amounts with defined behavior.
3690 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3691   // If OpSize is a power of 2 then:
3692   //
3693   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3694   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3695   //
3696   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3697   // for the stronger condition:
3698   //
3699   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3700   //
3701   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3702   // we can just replace Neg with Neg' for the rest of the function.
3703   //
3704   // In other cases we check for the even stronger condition:
3705   //
3706   //     Neg == OpSize - Pos                                    [B]
3707   //
3708   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3709   // behavior if Pos == 0 (and consequently Neg == OpSize).
3710   //
3711   // We could actually use [A] whenever OpSize is a power of 2, but the
3712   // only extra cases that it would match are those uninteresting ones
3713   // where Neg and Pos are never in range at the same time.  E.g. for
3714   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3715   // as well as (sub 32, Pos), but:
3716   //
3717   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3718   //
3719   // always invokes undefined behavior for 32-bit X.
3720   //
3721   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3722   unsigned MaskLoBits = 0;
3723   if (Neg.getOpcode() == ISD::AND &&
3724       isPowerOf2_64(OpSize) &&
3725       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3726       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3727     Neg = Neg.getOperand(0);
3728     MaskLoBits = Log2_64(OpSize);
3729   }
3730
3731   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3732   if (Neg.getOpcode() != ISD::SUB)
3733     return 0;
3734   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3735   if (!NegC)
3736     return 0;
3737   SDValue NegOp1 = Neg.getOperand(1);
3738
3739   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3740   // Pos'.  The truncation is redundant for the purpose of the equality.
3741   if (MaskLoBits &&
3742       Pos.getOpcode() == ISD::AND &&
3743       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3744       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3745     Pos = Pos.getOperand(0);
3746
3747   // The condition we need is now:
3748   //
3749   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3750   //
3751   // If NegOp1 == Pos then we need:
3752   //
3753   //              OpSize & Mask == NegC & Mask
3754   //
3755   // (because "x & Mask" is a truncation and distributes through subtraction).
3756   APInt Width;
3757   if (Pos == NegOp1)
3758     Width = NegC->getAPIntValue();
3759   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3760   // Then the condition we want to prove becomes:
3761   //
3762   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3763   //
3764   // which, again because "x & Mask" is a truncation, becomes:
3765   //
3766   //                NegC & Mask == (OpSize - PosC) & Mask
3767   //              OpSize & Mask == (NegC + PosC) & Mask
3768   else if (Pos.getOpcode() == ISD::ADD &&
3769            Pos.getOperand(0) == NegOp1 &&
3770            Pos.getOperand(1).getOpcode() == ISD::Constant)
3771     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3772              NegC->getAPIntValue());
3773   else
3774     return false;
3775
3776   // Now we just need to check that OpSize & Mask == Width & Mask.
3777   if (MaskLoBits)
3778     // Opsize & Mask is 0 since Mask is Opsize - 1.
3779     return Width.getLoBits(MaskLoBits) == 0;
3780   return Width == OpSize;
3781 }
3782
3783 // A subroutine of MatchRotate used once we have found an OR of two opposite
3784 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3785 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3786 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3787 // Neg with outer conversions stripped away.
3788 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3789                                        SDValue Neg, SDValue InnerPos,
3790                                        SDValue InnerNeg, unsigned PosOpcode,
3791                                        unsigned NegOpcode, SDLoc DL) {
3792   // fold (or (shl x, (*ext y)),
3793   //          (srl x, (*ext (sub 32, y)))) ->
3794   //   (rotl x, y) or (rotr x, (sub 32, y))
3795   //
3796   // fold (or (shl x, (*ext (sub 32, y))),
3797   //          (srl x, (*ext y))) ->
3798   //   (rotr x, y) or (rotl x, (sub 32, y))
3799   EVT VT = Shifted.getValueType();
3800   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3801     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3802     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3803                        HasPos ? Pos : Neg).getNode();
3804   }
3805
3806   return nullptr;
3807 }
3808
3809 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3810 // idioms for rotate, and if the target supports rotation instructions, generate
3811 // a rot[lr].
3812 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3813   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3814   EVT VT = LHS.getValueType();
3815   if (!TLI.isTypeLegal(VT)) return nullptr;
3816
3817   // The target must have at least one rotate flavor.
3818   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3819   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3820   if (!HasROTL && !HasROTR) return nullptr;
3821
3822   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3823   SDValue LHSShift;   // The shift.
3824   SDValue LHSMask;    // AND value if any.
3825   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3826     return nullptr; // Not part of a rotate.
3827
3828   SDValue RHSShift;   // The shift.
3829   SDValue RHSMask;    // AND value if any.
3830   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3831     return nullptr; // Not part of a rotate.
3832
3833   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3834     return nullptr;   // Not shifting the same value.
3835
3836   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3837     return nullptr;   // Shifts must disagree.
3838
3839   // Canonicalize shl to left side in a shl/srl pair.
3840   if (RHSShift.getOpcode() == ISD::SHL) {
3841     std::swap(LHS, RHS);
3842     std::swap(LHSShift, RHSShift);
3843     std::swap(LHSMask , RHSMask );
3844   }
3845
3846   unsigned OpSizeInBits = VT.getSizeInBits();
3847   SDValue LHSShiftArg = LHSShift.getOperand(0);
3848   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3849   SDValue RHSShiftArg = RHSShift.getOperand(0);
3850   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3851
3852   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3853   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3854   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3855       RHSShiftAmt.getOpcode() == ISD::Constant) {
3856     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3857     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3858     if ((LShVal + RShVal) != OpSizeInBits)
3859       return nullptr;
3860
3861     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3862                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3863
3864     // If there is an AND of either shifted operand, apply it to the result.
3865     if (LHSMask.getNode() || RHSMask.getNode()) {
3866       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3867
3868       if (LHSMask.getNode()) {
3869         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3870         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3871       }
3872       if (RHSMask.getNode()) {
3873         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3874         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3875       }
3876
3877       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3878     }
3879
3880     return Rot.getNode();
3881   }
3882
3883   // If there is a mask here, and we have a variable shift, we can't be sure
3884   // that we're masking out the right stuff.
3885   if (LHSMask.getNode() || RHSMask.getNode())
3886     return nullptr;
3887
3888   // If the shift amount is sign/zext/any-extended just peel it off.
3889   SDValue LExtOp0 = LHSShiftAmt;
3890   SDValue RExtOp0 = RHSShiftAmt;
3891   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3892        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3893        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3894        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3895       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3896        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3897        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3898        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3899     LExtOp0 = LHSShiftAmt.getOperand(0);
3900     RExtOp0 = RHSShiftAmt.getOperand(0);
3901   }
3902
3903   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3904                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3905   if (TryL)
3906     return TryL;
3907
3908   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3909                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3910   if (TryR)
3911     return TryR;
3912
3913   return nullptr;
3914 }
3915
3916 SDValue DAGCombiner::visitXOR(SDNode *N) {
3917   SDValue N0 = N->getOperand(0);
3918   SDValue N1 = N->getOperand(1);
3919   EVT VT = N0.getValueType();
3920
3921   // fold vector ops
3922   if (VT.isVector()) {
3923     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3924       return FoldedVOp;
3925
3926     // fold (xor x, 0) -> x, vector edition
3927     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3928       return N1;
3929     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3930       return N0;
3931   }
3932
3933   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3934   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3935     return DAG.getConstant(0, SDLoc(N), VT);
3936   // fold (xor x, undef) -> undef
3937   if (N0.getOpcode() == ISD::UNDEF)
3938     return N0;
3939   if (N1.getOpcode() == ISD::UNDEF)
3940     return N1;
3941   // fold (xor c1, c2) -> c1^c2
3942   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3943   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3944   if (N0C && N1C)
3945     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3946   // canonicalize constant to RHS
3947   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3948      !isConstantIntBuildVectorOrConstantInt(N1))
3949     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3950   // fold (xor x, 0) -> x
3951   if (isNullConstant(N1))
3952     return N0;
3953   // reassociate xor
3954   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3955     return RXOR;
3956
3957   // fold !(x cc y) -> (x !cc y)
3958   SDValue LHS, RHS, CC;
3959   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3960     bool isInt = LHS.getValueType().isInteger();
3961     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3962                                                isInt);
3963
3964     if (!LegalOperations ||
3965         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3966       switch (N0.getOpcode()) {
3967       default:
3968         llvm_unreachable("Unhandled SetCC Equivalent!");
3969       case ISD::SETCC:
3970         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3971       case ISD::SELECT_CC:
3972         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3973                                N0.getOperand(3), NotCC);
3974       }
3975     }
3976   }
3977
3978   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3979   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3980       N0.getNode()->hasOneUse() &&
3981       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3982     SDValue V = N0.getOperand(0);
3983     SDLoc DL(N0);
3984     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3985                     DAG.getConstant(1, DL, V.getValueType()));
3986     AddToWorklist(V.getNode());
3987     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3988   }
3989
3990   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3991   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3992       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3993     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3994     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3995       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3996       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3997       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3998       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3999       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4000     }
4001   }
4002   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4003   if (N1C && N1C->isAllOnesValue() &&
4004       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4005     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4006     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4007       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4008       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4009       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4010       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4011       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4012     }
4013   }
4014   // fold (xor (and x, y), y) -> (and (not x), y)
4015   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4016       N0->getOperand(1) == N1) {
4017     SDValue X = N0->getOperand(0);
4018     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4019     AddToWorklist(NotX.getNode());
4020     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4021   }
4022   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4023   if (N1C && N0.getOpcode() == ISD::XOR) {
4024     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4025     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4026     if (N00C) {
4027       SDLoc DL(N);
4028       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4029                          DAG.getConstant(N1C->getAPIntValue() ^
4030                                          N00C->getAPIntValue(), DL, VT));
4031     }
4032     if (N01C) {
4033       SDLoc DL(N);
4034       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4035                          DAG.getConstant(N1C->getAPIntValue() ^
4036                                          N01C->getAPIntValue(), DL, VT));
4037     }
4038   }
4039   // fold (xor x, x) -> 0
4040   if (N0 == N1)
4041     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4042
4043   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4044   // Here is a concrete example of this equivalence:
4045   // i16   x ==  14
4046   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4047   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4048   //
4049   // =>
4050   //
4051   // i16     ~1      == 0b1111111111111110
4052   // i16 rol(~1, 14) == 0b1011111111111111
4053   //
4054   // Some additional tips to help conceptualize this transform:
4055   // - Try to see the operation as placing a single zero in a value of all ones.
4056   // - There exists no value for x which would allow the result to contain zero.
4057   // - Values of x larger than the bitwidth are undefined and do not require a
4058   //   consistent result.
4059   // - Pushing the zero left requires shifting one bits in from the right.
4060   // A rotate left of ~1 is a nice way of achieving the desired result.
4061   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4062     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4063       if (N0.getOpcode() == ISD::SHL)
4064         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4065           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4066             SDLoc DL(N);
4067             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4068                                N0.getOperand(1));
4069           }
4070
4071   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4072   if (N0.getOpcode() == N1.getOpcode()) {
4073     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4074     if (Tmp.getNode()) return Tmp;
4075   }
4076
4077   // Simplify the expression using non-local knowledge.
4078   if (!VT.isVector() &&
4079       SimplifyDemandedBits(SDValue(N, 0)))
4080     return SDValue(N, 0);
4081
4082   return SDValue();
4083 }
4084
4085 /// Handle transforms common to the three shifts, when the shift amount is a
4086 /// constant.
4087 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4088   // We can't and shouldn't fold opaque constants.
4089   if (Amt->isOpaque())
4090     return SDValue();
4091
4092   SDNode *LHS = N->getOperand(0).getNode();
4093   if (!LHS->hasOneUse()) return SDValue();
4094
4095   // We want to pull some binops through shifts, so that we have (and (shift))
4096   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4097   // thing happens with address calculations, so it's important to canonicalize
4098   // it.
4099   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4100
4101   switch (LHS->getOpcode()) {
4102   default: return SDValue();
4103   case ISD::OR:
4104   case ISD::XOR:
4105     HighBitSet = false; // We can only transform sra if the high bit is clear.
4106     break;
4107   case ISD::AND:
4108     HighBitSet = true;  // We can only transform sra if the high bit is set.
4109     break;
4110   case ISD::ADD:
4111     if (N->getOpcode() != ISD::SHL)
4112       return SDValue(); // only shl(add) not sr[al](add).
4113     HighBitSet = false; // We can only transform sra if the high bit is clear.
4114     break;
4115   }
4116
4117   // We require the RHS of the binop to be a constant and not opaque as well.
4118   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4119   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4120
4121   // FIXME: disable this unless the input to the binop is a shift by a constant.
4122   // If it is not a shift, it pessimizes some common cases like:
4123   //
4124   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4125   //    int bar(int *X, int i) { return X[i & 255]; }
4126   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4127   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4128        BinOpLHSVal->getOpcode() != ISD::SRA &&
4129        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4130       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4131     return SDValue();
4132
4133   EVT VT = N->getValueType(0);
4134
4135   // If this is a signed shift right, and the high bit is modified by the
4136   // logical operation, do not perform the transformation. The highBitSet
4137   // boolean indicates the value of the high bit of the constant which would
4138   // cause it to be modified for this operation.
4139   if (N->getOpcode() == ISD::SRA) {
4140     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4141     if (BinOpRHSSignSet != HighBitSet)
4142       return SDValue();
4143   }
4144
4145   if (!TLI.isDesirableToCommuteWithShift(LHS))
4146     return SDValue();
4147
4148   // Fold the constants, shifting the binop RHS by the shift amount.
4149   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4150                                N->getValueType(0),
4151                                LHS->getOperand(1), N->getOperand(1));
4152   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4153
4154   // Create the new shift.
4155   SDValue NewShift = DAG.getNode(N->getOpcode(),
4156                                  SDLoc(LHS->getOperand(0)),
4157                                  VT, LHS->getOperand(0), N->getOperand(1));
4158
4159   // Create the new binop.
4160   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4161 }
4162
4163 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4164   assert(N->getOpcode() == ISD::TRUNCATE);
4165   assert(N->getOperand(0).getOpcode() == ISD::AND);
4166
4167   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4168   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4169     SDValue N01 = N->getOperand(0).getOperand(1);
4170
4171     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4172       EVT TruncVT = N->getValueType(0);
4173       SDValue N00 = N->getOperand(0).getOperand(0);
4174       APInt TruncC = N01C->getAPIntValue();
4175       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4176       SDLoc DL(N);
4177
4178       return DAG.getNode(ISD::AND, DL, TruncVT,
4179                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4180                          DAG.getConstant(TruncC, DL, TruncVT));
4181     }
4182   }
4183
4184   return SDValue();
4185 }
4186
4187 SDValue DAGCombiner::visitRotate(SDNode *N) {
4188   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4189   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4190       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4191     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4192     if (NewOp1.getNode())
4193       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4194                          N->getOperand(0), NewOp1);
4195   }
4196   return SDValue();
4197 }
4198
4199 SDValue DAGCombiner::visitSHL(SDNode *N) {
4200   SDValue N0 = N->getOperand(0);
4201   SDValue N1 = N->getOperand(1);
4202   EVT VT = N0.getValueType();
4203   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4204
4205   // fold vector ops
4206   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4207   if (VT.isVector()) {
4208     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4209       return FoldedVOp;
4210
4211     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4212     // If setcc produces all-one true value then:
4213     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4214     if (N1CV && N1CV->isConstant()) {
4215       if (N0.getOpcode() == ISD::AND) {
4216         SDValue N00 = N0->getOperand(0);
4217         SDValue N01 = N0->getOperand(1);
4218         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4219
4220         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4221             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4222                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4223           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4224                                                      N01CV, N1CV))
4225             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4226         }
4227       } else {
4228         N1C = isConstOrConstSplat(N1);
4229       }
4230     }
4231   }
4232
4233   // fold (shl c1, c2) -> c1<<c2
4234   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4235   if (N0C && N1C)
4236     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4237   // fold (shl 0, x) -> 0
4238   if (isNullConstant(N0))
4239     return N0;
4240   // fold (shl x, c >= size(x)) -> undef
4241   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4242     return DAG.getUNDEF(VT);
4243   // fold (shl x, 0) -> x
4244   if (N1C && N1C->isNullValue())
4245     return N0;
4246   // fold (shl undef, x) -> 0
4247   if (N0.getOpcode() == ISD::UNDEF)
4248     return DAG.getConstant(0, SDLoc(N), VT);
4249   // if (shl x, c) is known to be zero, return 0
4250   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4251                             APInt::getAllOnesValue(OpSizeInBits)))
4252     return DAG.getConstant(0, SDLoc(N), VT);
4253   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4254   if (N1.getOpcode() == ISD::TRUNCATE &&
4255       N1.getOperand(0).getOpcode() == ISD::AND) {
4256     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4257     if (NewOp1.getNode())
4258       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4259   }
4260
4261   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4262     return SDValue(N, 0);
4263
4264   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4265   if (N1C && N0.getOpcode() == ISD::SHL) {
4266     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4267       uint64_t c1 = N0C1->getZExtValue();
4268       uint64_t c2 = N1C->getZExtValue();
4269       SDLoc DL(N);
4270       if (c1 + c2 >= OpSizeInBits)
4271         return DAG.getConstant(0, DL, VT);
4272       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4273                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4274     }
4275   }
4276
4277   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4278   // For this to be valid, the second form must not preserve any of the bits
4279   // that are shifted out by the inner shift in the first form.  This means
4280   // the outer shift size must be >= the number of bits added by the ext.
4281   // As a corollary, we don't care what kind of ext it is.
4282   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4283               N0.getOpcode() == ISD::ANY_EXTEND ||
4284               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4285       N0.getOperand(0).getOpcode() == ISD::SHL) {
4286     SDValue N0Op0 = N0.getOperand(0);
4287     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4288       uint64_t c1 = N0Op0C1->getZExtValue();
4289       uint64_t c2 = N1C->getZExtValue();
4290       EVT InnerShiftVT = N0Op0.getValueType();
4291       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4292       if (c2 >= OpSizeInBits - InnerShiftSize) {
4293         SDLoc DL(N0);
4294         if (c1 + c2 >= OpSizeInBits)
4295           return DAG.getConstant(0, DL, VT);
4296         return DAG.getNode(ISD::SHL, DL, VT,
4297                            DAG.getNode(N0.getOpcode(), DL, VT,
4298                                        N0Op0->getOperand(0)),
4299                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4300       }
4301     }
4302   }
4303
4304   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4305   // Only fold this if the inner zext has no other uses to avoid increasing
4306   // the total number of instructions.
4307   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4308       N0.getOperand(0).getOpcode() == ISD::SRL) {
4309     SDValue N0Op0 = N0.getOperand(0);
4310     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4311       uint64_t c1 = N0Op0C1->getZExtValue();
4312       if (c1 < VT.getScalarSizeInBits()) {
4313         uint64_t c2 = N1C->getZExtValue();
4314         if (c1 == c2) {
4315           SDValue NewOp0 = N0.getOperand(0);
4316           EVT CountVT = NewOp0.getOperand(1).getValueType();
4317           SDLoc DL(N);
4318           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4319                                        NewOp0,
4320                                        DAG.getConstant(c2, DL, CountVT));
4321           AddToWorklist(NewSHL.getNode());
4322           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4323         }
4324       }
4325     }
4326   }
4327
4328   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4329   //                               (and (srl x, (sub c1, c2), MASK)
4330   // Only fold this if the inner shift has no other uses -- if it does, folding
4331   // this will increase the total number of instructions.
4332   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4333     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4334       uint64_t c1 = N0C1->getZExtValue();
4335       if (c1 < OpSizeInBits) {
4336         uint64_t c2 = N1C->getZExtValue();
4337         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4338         SDValue Shift;
4339         if (c2 > c1) {
4340           Mask = Mask.shl(c2 - c1);
4341           SDLoc DL(N);
4342           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4343                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4344         } else {
4345           Mask = Mask.lshr(c1 - c2);
4346           SDLoc DL(N);
4347           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4348                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4349         }
4350         SDLoc DL(N0);
4351         return DAG.getNode(ISD::AND, DL, VT, Shift,
4352                            DAG.getConstant(Mask, DL, VT));
4353       }
4354     }
4355   }
4356   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4357   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4358     unsigned BitSize = VT.getScalarSizeInBits();
4359     SDLoc DL(N);
4360     SDValue HiBitsMask =
4361       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4362                                             BitSize - N1C->getZExtValue()),
4363                       DL, VT);
4364     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4365                        HiBitsMask);
4366   }
4367
4368   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4369   // Variant of version done on multiply, except mul by a power of 2 is turned
4370   // into a shift.
4371   APInt Val;
4372   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4373       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4374        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4375     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4376     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4377     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4378   }
4379
4380   if (N1C) {
4381     SDValue NewSHL = visitShiftByConstant(N, N1C);
4382     if (NewSHL.getNode())
4383       return NewSHL;
4384   }
4385
4386   return SDValue();
4387 }
4388
4389 SDValue DAGCombiner::visitSRA(SDNode *N) {
4390   SDValue N0 = N->getOperand(0);
4391   SDValue N1 = N->getOperand(1);
4392   EVT VT = N0.getValueType();
4393   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4394
4395   // fold vector ops
4396   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4397   if (VT.isVector()) {
4398     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4399       return FoldedVOp;
4400
4401     N1C = isConstOrConstSplat(N1);
4402   }
4403
4404   // fold (sra c1, c2) -> (sra c1, c2)
4405   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4406   if (N0C && N1C)
4407     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4408   // fold (sra 0, x) -> 0
4409   if (isNullConstant(N0))
4410     return N0;
4411   // fold (sra -1, x) -> -1
4412   if (N0C && N0C->isAllOnesValue())
4413     return N0;
4414   // fold (sra x, (setge c, size(x))) -> undef
4415   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4416     return DAG.getUNDEF(VT);
4417   // fold (sra x, 0) -> x
4418   if (N1C && N1C->isNullValue())
4419     return N0;
4420   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4421   // sext_inreg.
4422   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4423     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4424     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4425     if (VT.isVector())
4426       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4427                                ExtVT, VT.getVectorNumElements());
4428     if ((!LegalOperations ||
4429          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4430       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4431                          N0.getOperand(0), DAG.getValueType(ExtVT));
4432   }
4433
4434   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4435   if (N1C && N0.getOpcode() == ISD::SRA) {
4436     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4437       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4438       if (Sum >= OpSizeInBits)
4439         Sum = OpSizeInBits - 1;
4440       SDLoc DL(N);
4441       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4442                          DAG.getConstant(Sum, DL, N1.getValueType()));
4443     }
4444   }
4445
4446   // fold (sra (shl X, m), (sub result_size, n))
4447   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4448   // result_size - n != m.
4449   // If truncate is free for the target sext(shl) is likely to result in better
4450   // code.
4451   if (N0.getOpcode() == ISD::SHL && N1C) {
4452     // Get the two constanst of the shifts, CN0 = m, CN = n.
4453     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4454     if (N01C) {
4455       LLVMContext &Ctx = *DAG.getContext();
4456       // Determine what the truncate's result bitsize and type would be.
4457       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4458
4459       if (VT.isVector())
4460         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4461
4462       // Determine the residual right-shift amount.
4463       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4464
4465       // If the shift is not a no-op (in which case this should be just a sign
4466       // extend already), the truncated to type is legal, sign_extend is legal
4467       // on that type, and the truncate to that type is both legal and free,
4468       // perform the transform.
4469       if ((ShiftAmt > 0) &&
4470           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4471           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4472           TLI.isTruncateFree(VT, TruncVT)) {
4473
4474         SDLoc DL(N);
4475         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4476             getShiftAmountTy(N0.getOperand(0).getValueType()));
4477         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4478                                     N0.getOperand(0), Amt);
4479         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4480                                     Shift);
4481         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4482                            N->getValueType(0), Trunc);
4483       }
4484     }
4485   }
4486
4487   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4488   if (N1.getOpcode() == ISD::TRUNCATE &&
4489       N1.getOperand(0).getOpcode() == ISD::AND) {
4490     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4491     if (NewOp1.getNode())
4492       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4493   }
4494
4495   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4496   //      if c1 is equal to the number of bits the trunc removes
4497   if (N0.getOpcode() == ISD::TRUNCATE &&
4498       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4499        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4500       N0.getOperand(0).hasOneUse() &&
4501       N0.getOperand(0).getOperand(1).hasOneUse() &&
4502       N1C) {
4503     SDValue N0Op0 = N0.getOperand(0);
4504     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4505       unsigned LargeShiftVal = LargeShift->getZExtValue();
4506       EVT LargeVT = N0Op0.getValueType();
4507
4508       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4509         SDLoc DL(N);
4510         SDValue Amt =
4511           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4512                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4513         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4514                                   N0Op0.getOperand(0), Amt);
4515         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4516       }
4517     }
4518   }
4519
4520   // Simplify, based on bits shifted out of the LHS.
4521   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4522     return SDValue(N, 0);
4523
4524
4525   // If the sign bit is known to be zero, switch this to a SRL.
4526   if (DAG.SignBitIsZero(N0))
4527     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4528
4529   if (N1C) {
4530     SDValue NewSRA = visitShiftByConstant(N, N1C);
4531     if (NewSRA.getNode())
4532       return NewSRA;
4533   }
4534
4535   return SDValue();
4536 }
4537
4538 SDValue DAGCombiner::visitSRL(SDNode *N) {
4539   SDValue N0 = N->getOperand(0);
4540   SDValue N1 = N->getOperand(1);
4541   EVT VT = N0.getValueType();
4542   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4543
4544   // fold vector ops
4545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4546   if (VT.isVector()) {
4547     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4548       return FoldedVOp;
4549
4550     N1C = isConstOrConstSplat(N1);
4551   }
4552
4553   // fold (srl c1, c2) -> c1 >>u c2
4554   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4555   if (N0C && N1C)
4556     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4557   // fold (srl 0, x) -> 0
4558   if (isNullConstant(N0))
4559     return N0;
4560   // fold (srl x, c >= size(x)) -> undef
4561   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4562     return DAG.getUNDEF(VT);
4563   // fold (srl x, 0) -> x
4564   if (N1C && N1C->isNullValue())
4565     return N0;
4566   // if (srl x, c) is known to be zero, return 0
4567   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4568                                    APInt::getAllOnesValue(OpSizeInBits)))
4569     return DAG.getConstant(0, SDLoc(N), VT);
4570
4571   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4572   if (N1C && N0.getOpcode() == ISD::SRL) {
4573     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4574       uint64_t c1 = N01C->getZExtValue();
4575       uint64_t c2 = N1C->getZExtValue();
4576       SDLoc DL(N);
4577       if (c1 + c2 >= OpSizeInBits)
4578         return DAG.getConstant(0, DL, VT);
4579       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4580                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4581     }
4582   }
4583
4584   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4585   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4586       N0.getOperand(0).getOpcode() == ISD::SRL &&
4587       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4588     uint64_t c1 =
4589       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4590     uint64_t c2 = N1C->getZExtValue();
4591     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4592     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4593     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4594     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4595     if (c1 + OpSizeInBits == InnerShiftSize) {
4596       SDLoc DL(N0);
4597       if (c1 + c2 >= InnerShiftSize)
4598         return DAG.getConstant(0, DL, VT);
4599       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4600                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4601                                      N0.getOperand(0)->getOperand(0),
4602                                      DAG.getConstant(c1 + c2, DL,
4603                                                      ShiftCountVT)));
4604     }
4605   }
4606
4607   // fold (srl (shl x, c), c) -> (and x, cst2)
4608   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4609     unsigned BitSize = N0.getScalarValueSizeInBits();
4610     if (BitSize <= 64) {
4611       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4612       SDLoc DL(N);
4613       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4614                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4615     }
4616   }
4617
4618   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4619   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4620     // Shifting in all undef bits?
4621     EVT SmallVT = N0.getOperand(0).getValueType();
4622     unsigned BitSize = SmallVT.getScalarSizeInBits();
4623     if (N1C->getZExtValue() >= BitSize)
4624       return DAG.getUNDEF(VT);
4625
4626     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4627       uint64_t ShiftAmt = N1C->getZExtValue();
4628       SDLoc DL0(N0);
4629       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4630                                        N0.getOperand(0),
4631                           DAG.getConstant(ShiftAmt, DL0,
4632                                           getShiftAmountTy(SmallVT)));
4633       AddToWorklist(SmallShift.getNode());
4634       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4635       SDLoc DL(N);
4636       return DAG.getNode(ISD::AND, DL, VT,
4637                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4638                          DAG.getConstant(Mask, DL, VT));
4639     }
4640   }
4641
4642   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4643   // bit, which is unmodified by sra.
4644   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4645     if (N0.getOpcode() == ISD::SRA)
4646       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4647   }
4648
4649   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4650   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4651       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4652     APInt KnownZero, KnownOne;
4653     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4654
4655     // If any of the input bits are KnownOne, then the input couldn't be all
4656     // zeros, thus the result of the srl will always be zero.
4657     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4658
4659     // If all of the bits input the to ctlz node are known to be zero, then
4660     // the result of the ctlz is "32" and the result of the shift is one.
4661     APInt UnknownBits = ~KnownZero;
4662     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4663
4664     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4665     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4666       // Okay, we know that only that the single bit specified by UnknownBits
4667       // could be set on input to the CTLZ node. If this bit is set, the SRL
4668       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4669       // to an SRL/XOR pair, which is likely to simplify more.
4670       unsigned ShAmt = UnknownBits.countTrailingZeros();
4671       SDValue Op = N0.getOperand(0);
4672
4673       if (ShAmt) {
4674         SDLoc DL(N0);
4675         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4676                   DAG.getConstant(ShAmt, DL,
4677                                   getShiftAmountTy(Op.getValueType())));
4678         AddToWorklist(Op.getNode());
4679       }
4680
4681       SDLoc DL(N);
4682       return DAG.getNode(ISD::XOR, DL, VT,
4683                          Op, DAG.getConstant(1, DL, VT));
4684     }
4685   }
4686
4687   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4688   if (N1.getOpcode() == ISD::TRUNCATE &&
4689       N1.getOperand(0).getOpcode() == ISD::AND) {
4690     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4691     if (NewOp1.getNode())
4692       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4693   }
4694
4695   // fold operands of srl based on knowledge that the low bits are not
4696   // demanded.
4697   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4698     return SDValue(N, 0);
4699
4700   if (N1C) {
4701     SDValue NewSRL = visitShiftByConstant(N, N1C);
4702     if (NewSRL.getNode())
4703       return NewSRL;
4704   }
4705
4706   // Attempt to convert a srl of a load into a narrower zero-extending load.
4707   SDValue NarrowLoad = ReduceLoadWidth(N);
4708   if (NarrowLoad.getNode())
4709     return NarrowLoad;
4710
4711   // Here is a common situation. We want to optimize:
4712   //
4713   //   %a = ...
4714   //   %b = and i32 %a, 2
4715   //   %c = srl i32 %b, 1
4716   //   brcond i32 %c ...
4717   //
4718   // into
4719   //
4720   //   %a = ...
4721   //   %b = and %a, 2
4722   //   %c = setcc eq %b, 0
4723   //   brcond %c ...
4724   //
4725   // However when after the source operand of SRL is optimized into AND, the SRL
4726   // itself may not be optimized further. Look for it and add the BRCOND into
4727   // the worklist.
4728   if (N->hasOneUse()) {
4729     SDNode *Use = *N->use_begin();
4730     if (Use->getOpcode() == ISD::BRCOND)
4731       AddToWorklist(Use);
4732     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4733       // Also look pass the truncate.
4734       Use = *Use->use_begin();
4735       if (Use->getOpcode() == ISD::BRCOND)
4736         AddToWorklist(Use);
4737     }
4738   }
4739
4740   return SDValue();
4741 }
4742
4743 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4744   SDValue N0 = N->getOperand(0);
4745   EVT VT = N->getValueType(0);
4746
4747   // fold (ctlz c1) -> c2
4748   if (isa<ConstantSDNode>(N0))
4749     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4750   return SDValue();
4751 }
4752
4753 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4754   SDValue N0 = N->getOperand(0);
4755   EVT VT = N->getValueType(0);
4756
4757   // fold (ctlz_zero_undef c1) -> c2
4758   if (isa<ConstantSDNode>(N0))
4759     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4760   return SDValue();
4761 }
4762
4763 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4764   SDValue N0 = N->getOperand(0);
4765   EVT VT = N->getValueType(0);
4766
4767   // fold (cttz c1) -> c2
4768   if (isa<ConstantSDNode>(N0))
4769     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4770   return SDValue();
4771 }
4772
4773 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4774   SDValue N0 = N->getOperand(0);
4775   EVT VT = N->getValueType(0);
4776
4777   // fold (cttz_zero_undef c1) -> c2
4778   if (isa<ConstantSDNode>(N0))
4779     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4780   return SDValue();
4781 }
4782
4783 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4784   SDValue N0 = N->getOperand(0);
4785   EVT VT = N->getValueType(0);
4786
4787   // fold (ctpop c1) -> c2
4788   if (isa<ConstantSDNode>(N0))
4789     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4790   return SDValue();
4791 }
4792
4793
4794 /// \brief Generate Min/Max node
4795 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4796                                    SDValue True, SDValue False,
4797                                    ISD::CondCode CC, const TargetLowering &TLI,
4798                                    SelectionDAG &DAG) {
4799   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4800     return SDValue();
4801
4802   switch (CC) {
4803   case ISD::SETOLT:
4804   case ISD::SETOLE:
4805   case ISD::SETLT:
4806   case ISD::SETLE:
4807   case ISD::SETULT:
4808   case ISD::SETULE: {
4809     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4810     if (TLI.isOperationLegal(Opcode, VT))
4811       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4812     return SDValue();
4813   }
4814   case ISD::SETOGT:
4815   case ISD::SETOGE:
4816   case ISD::SETGT:
4817   case ISD::SETGE:
4818   case ISD::SETUGT:
4819   case ISD::SETUGE: {
4820     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4821     if (TLI.isOperationLegal(Opcode, VT))
4822       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4823     return SDValue();
4824   }
4825   default:
4826     return SDValue();
4827   }
4828 }
4829
4830 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4831   SDValue N0 = N->getOperand(0);
4832   SDValue N1 = N->getOperand(1);
4833   SDValue N2 = N->getOperand(2);
4834   EVT VT = N->getValueType(0);
4835   EVT VT0 = N0.getValueType();
4836
4837   // fold (select C, X, X) -> X
4838   if (N1 == N2)
4839     return N1;
4840   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4841     // fold (select true, X, Y) -> X
4842     // fold (select false, X, Y) -> Y
4843     return !N0C->isNullValue() ? N1 : N2;
4844   }
4845   // fold (select C, 1, X) -> (or C, X)
4846   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4847   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4848     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4849   // fold (select C, 0, 1) -> (xor C, 1)
4850   // We can't do this reliably if integer based booleans have different contents
4851   // to floating point based booleans. This is because we can't tell whether we
4852   // have an integer-based boolean or a floating-point-based boolean unless we
4853   // can find the SETCC that produced it and inspect its operands. This is
4854   // fairly easy if C is the SETCC node, but it can potentially be
4855   // undiscoverable (or not reasonably discoverable). For example, it could be
4856   // in another basic block or it could require searching a complicated
4857   // expression.
4858   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4859   if (VT.isInteger() &&
4860       (VT0 == MVT::i1 || (VT0.isInteger() &&
4861                           TLI.getBooleanContents(false, false) ==
4862                               TLI.getBooleanContents(false, true) &&
4863                           TLI.getBooleanContents(false, false) ==
4864                               TargetLowering::ZeroOrOneBooleanContent)) &&
4865       isNullConstant(N1) && N2C && N2C->isOne()) {
4866     SDValue XORNode;
4867     if (VT == VT0) {
4868       SDLoc DL(N);
4869       return DAG.getNode(ISD::XOR, DL, VT0,
4870                          N0, DAG.getConstant(1, DL, VT0));
4871     }
4872     SDLoc DL0(N0);
4873     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4874                           N0, DAG.getConstant(1, DL0, VT0));
4875     AddToWorklist(XORNode.getNode());
4876     if (VT.bitsGT(VT0))
4877       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4878     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4879   }
4880   // fold (select C, 0, X) -> (and (not C), X)
4881   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4882     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4883     AddToWorklist(NOTNode.getNode());
4884     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4885   }
4886   // fold (select C, X, 1) -> (or (not C), X)
4887   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4888     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4889     AddToWorklist(NOTNode.getNode());
4890     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4891   }
4892   // fold (select C, X, 0) -> (and C, X)
4893   if (VT == MVT::i1 && isNullConstant(N2))
4894     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4895   // fold (select X, X, Y) -> (or X, Y)
4896   // fold (select X, 1, Y) -> (or X, Y)
4897   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4898     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4899   // fold (select X, Y, X) -> (and X, Y)
4900   // fold (select X, Y, 0) -> (and X, Y)
4901   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4902     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4903
4904   // If we can fold this based on the true/false value, do so.
4905   if (SimplifySelectOps(N, N1, N2))
4906     return SDValue(N, 0);  // Don't revisit N.
4907
4908   // fold selects based on a setcc into other things, such as min/max/abs
4909   if (N0.getOpcode() == ISD::SETCC) {
4910     // select x, y (fcmp lt x, y) -> fminnum x, y
4911     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4912     //
4913     // This is OK if we don't care about what happens if either operand is a
4914     // NaN.
4915     //
4916
4917     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4918     // no signed zeros as well as no nans.
4919     const TargetOptions &Options = DAG.getTarget().Options;
4920     if (Options.UnsafeFPMath &&
4921         VT.isFloatingPoint() && N0.hasOneUse() &&
4922         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4923       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4924
4925       SDValue FMinMax =
4926           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4927                               N1, N2, CC, TLI, DAG);
4928       if (FMinMax)
4929         return FMinMax;
4930     }
4931
4932     if ((!LegalOperations &&
4933          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4934         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4935       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4936                          N0.getOperand(0), N0.getOperand(1),
4937                          N1, N2, N0.getOperand(2));
4938     return SimplifySelect(SDLoc(N), N0, N1, N2);
4939   }
4940
4941   if (VT0 == MVT::i1) {
4942     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4943       // select (and Cond0, Cond1), X, Y
4944       //   -> select Cond0, (select Cond1, X, Y), Y
4945       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4946         SDValue Cond0 = N0->getOperand(0);
4947         SDValue Cond1 = N0->getOperand(1);
4948         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4949                                           N1.getValueType(), Cond1, N1, N2);
4950         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4951                            InnerSelect, N2);
4952       }
4953       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4954       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4955         SDValue Cond0 = N0->getOperand(0);
4956         SDValue Cond1 = N0->getOperand(1);
4957         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4958                                           N1.getValueType(), Cond1, N1, N2);
4959         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4960                            InnerSelect);
4961       }
4962     }
4963
4964     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4965     if (N1->getOpcode() == ISD::SELECT) {
4966       SDValue N1_0 = N1->getOperand(0);
4967       SDValue N1_1 = N1->getOperand(1);
4968       SDValue N1_2 = N1->getOperand(2);
4969       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4970         // Create the actual and node if we can generate good code for it.
4971         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4972           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4973                                     N0, N1_0);
4974           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4975                              N1_1, N2);
4976         }
4977         // Otherwise see if we can optimize the "and" to a better pattern.
4978         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4979           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4980                              N1_1, N2);
4981       }
4982     }
4983     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4984     if (N2->getOpcode() == ISD::SELECT) {
4985       SDValue N2_0 = N2->getOperand(0);
4986       SDValue N2_1 = N2->getOperand(1);
4987       SDValue N2_2 = N2->getOperand(2);
4988       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4989         // Create the actual or node if we can generate good code for it.
4990         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4991           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4992                                    N0, N2_0);
4993           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4994                              N1, N2_2);
4995         }
4996         // Otherwise see if we can optimize to a better pattern.
4997         if (SDValue Combined = visitORLike(N0, N2_0, N))
4998           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4999                              N1, N2_2);
5000       }
5001     }
5002   }
5003
5004   return SDValue();
5005 }
5006
5007 static
5008 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5009   SDLoc DL(N);
5010   EVT LoVT, HiVT;
5011   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5012
5013   // Split the inputs.
5014   SDValue Lo, Hi, LL, LH, RL, RH;
5015   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5016   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5017
5018   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5019   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5020
5021   return std::make_pair(Lo, Hi);
5022 }
5023
5024 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5025 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5026 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5027   SDLoc dl(N);
5028   SDValue Cond = N->getOperand(0);
5029   SDValue LHS = N->getOperand(1);
5030   SDValue RHS = N->getOperand(2);
5031   EVT VT = N->getValueType(0);
5032   int NumElems = VT.getVectorNumElements();
5033   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5034          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5035          Cond.getOpcode() == ISD::BUILD_VECTOR);
5036
5037   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5038   // binary ones here.
5039   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5040     return SDValue();
5041
5042   // We're sure we have an even number of elements due to the
5043   // concat_vectors we have as arguments to vselect.
5044   // Skip BV elements until we find one that's not an UNDEF
5045   // After we find an UNDEF element, keep looping until we get to half the
5046   // length of the BV and see if all the non-undef nodes are the same.
5047   ConstantSDNode *BottomHalf = nullptr;
5048   for (int i = 0; i < NumElems / 2; ++i) {
5049     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5050       continue;
5051
5052     if (BottomHalf == nullptr)
5053       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5054     else if (Cond->getOperand(i).getNode() != BottomHalf)
5055       return SDValue();
5056   }
5057
5058   // Do the same for the second half of the BuildVector
5059   ConstantSDNode *TopHalf = nullptr;
5060   for (int i = NumElems / 2; i < NumElems; ++i) {
5061     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5062       continue;
5063
5064     if (TopHalf == nullptr)
5065       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5066     else if (Cond->getOperand(i).getNode() != TopHalf)
5067       return SDValue();
5068   }
5069
5070   assert(TopHalf && BottomHalf &&
5071          "One half of the selector was all UNDEFs and the other was all the "
5072          "same value. This should have been addressed before this function.");
5073   return DAG.getNode(
5074       ISD::CONCAT_VECTORS, dl, VT,
5075       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5076       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5077 }
5078
5079 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5080
5081   if (Level >= AfterLegalizeTypes)
5082     return SDValue();
5083
5084   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5085   SDValue Mask = MSC->getMask();
5086   SDValue Data  = MSC->getValue();
5087   SDLoc DL(N);
5088
5089   // If the MSCATTER data type requires splitting and the mask is provided by a
5090   // SETCC, then split both nodes and its operands before legalization. This
5091   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5092   // and enables future optimizations (e.g. min/max pattern matching on X86).
5093   if (Mask.getOpcode() != ISD::SETCC)
5094     return SDValue();
5095
5096   // Check if any splitting is required.
5097   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5098       TargetLowering::TypeSplitVector)
5099     return SDValue();
5100   SDValue MaskLo, MaskHi, Lo, Hi;
5101   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5102
5103   EVT LoVT, HiVT;
5104   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5105
5106   SDValue Chain = MSC->getChain();
5107
5108   EVT MemoryVT = MSC->getMemoryVT();
5109   unsigned Alignment = MSC->getOriginalAlignment();
5110
5111   EVT LoMemVT, HiMemVT;
5112   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5113
5114   SDValue DataLo, DataHi;
5115   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5116
5117   SDValue BasePtr = MSC->getBasePtr();
5118   SDValue IndexLo, IndexHi;
5119   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5120
5121   MachineMemOperand *MMO = DAG.getMachineFunction().
5122     getMachineMemOperand(MSC->getPointerInfo(), 
5123                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5124                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5125
5126   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5127   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5128                             DL, OpsLo, MMO);
5129
5130   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5131   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5132                             DL, OpsHi, MMO);
5133
5134   AddToWorklist(Lo.getNode());
5135   AddToWorklist(Hi.getNode());
5136
5137   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5138 }
5139
5140 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5141
5142   if (Level >= AfterLegalizeTypes)
5143     return SDValue();
5144
5145   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5146   SDValue Mask = MST->getMask();
5147   SDValue Data  = MST->getValue();
5148   SDLoc DL(N);
5149
5150   // If the MSTORE data type requires splitting and the mask is provided by a
5151   // SETCC, then split both nodes and its operands before legalization. This
5152   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5153   // and enables future optimizations (e.g. min/max pattern matching on X86).
5154   if (Mask.getOpcode() == ISD::SETCC) {
5155
5156     // Check if any splitting is required.
5157     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5158         TargetLowering::TypeSplitVector)
5159       return SDValue();
5160
5161     SDValue MaskLo, MaskHi, Lo, Hi;
5162     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5163
5164     EVT LoVT, HiVT;
5165     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5166
5167     SDValue Chain = MST->getChain();
5168     SDValue Ptr   = MST->getBasePtr();
5169
5170     EVT MemoryVT = MST->getMemoryVT();
5171     unsigned Alignment = MST->getOriginalAlignment();
5172
5173     // if Alignment is equal to the vector size,
5174     // take the half of it for the second part
5175     unsigned SecondHalfAlignment =
5176       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5177          Alignment/2 : Alignment;
5178
5179     EVT LoMemVT, HiMemVT;
5180     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5181
5182     SDValue DataLo, DataHi;
5183     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5184
5185     MachineMemOperand *MMO = DAG.getMachineFunction().
5186       getMachineMemOperand(MST->getPointerInfo(),
5187                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5188                            Alignment, MST->getAAInfo(), MST->getRanges());
5189
5190     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5191                             MST->isTruncatingStore());
5192
5193     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5194     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5195                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5196
5197     MMO = DAG.getMachineFunction().
5198       getMachineMemOperand(MST->getPointerInfo(),
5199                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5200                            SecondHalfAlignment, MST->getAAInfo(),
5201                            MST->getRanges());
5202
5203     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5204                             MST->isTruncatingStore());
5205
5206     AddToWorklist(Lo.getNode());
5207     AddToWorklist(Hi.getNode());
5208
5209     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5210   }
5211   return SDValue();
5212 }
5213
5214 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5215
5216   if (Level >= AfterLegalizeTypes)
5217     return SDValue();
5218
5219   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5220   SDValue Mask = MGT->getMask();
5221   SDLoc DL(N);
5222
5223   // If the MGATHER result requires splitting and the mask is provided by a
5224   // SETCC, then split both nodes and its operands before legalization. This
5225   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5226   // and enables future optimizations (e.g. min/max pattern matching on X86).
5227
5228   if (Mask.getOpcode() != ISD::SETCC)
5229     return SDValue();
5230
5231   EVT VT = N->getValueType(0);
5232
5233   // Check if any splitting is required.
5234   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5235       TargetLowering::TypeSplitVector)
5236     return SDValue();
5237
5238   SDValue MaskLo, MaskHi, Lo, Hi;
5239   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5240
5241   SDValue Src0 = MGT->getValue();
5242   SDValue Src0Lo, Src0Hi;
5243   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5244
5245   EVT LoVT, HiVT;
5246   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5247
5248   SDValue Chain = MGT->getChain();
5249   EVT MemoryVT = MGT->getMemoryVT();
5250   unsigned Alignment = MGT->getOriginalAlignment();
5251
5252   EVT LoMemVT, HiMemVT;
5253   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5254
5255   SDValue BasePtr = MGT->getBasePtr();
5256   SDValue Index = MGT->getIndex();
5257   SDValue IndexLo, IndexHi;
5258   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5259
5260   MachineMemOperand *MMO = DAG.getMachineFunction().
5261     getMachineMemOperand(MGT->getPointerInfo(), 
5262                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5263                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5264
5265   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5266   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5267                             MMO);
5268
5269   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5270   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5271                             MMO);
5272
5273   AddToWorklist(Lo.getNode());
5274   AddToWorklist(Hi.getNode());
5275
5276   // Build a factor node to remember that this load is independent of the
5277   // other one.
5278   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5279                       Hi.getValue(1));
5280
5281   // Legalized the chain result - switch anything that used the old chain to
5282   // use the new one.
5283   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5284
5285   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5286
5287   SDValue RetOps[] = { GatherRes, Chain };
5288   return DAG.getMergeValues(RetOps, DL);
5289 }
5290
5291 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5292
5293   if (Level >= AfterLegalizeTypes)
5294     return SDValue();
5295
5296   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5297   SDValue Mask = MLD->getMask();
5298   SDLoc DL(N);
5299
5300   // If the MLOAD result requires splitting and the mask is provided by a
5301   // SETCC, then split both nodes and its operands before legalization. This
5302   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5303   // and enables future optimizations (e.g. min/max pattern matching on X86).
5304
5305   if (Mask.getOpcode() == ISD::SETCC) {
5306     EVT VT = N->getValueType(0);
5307
5308     // Check if any splitting is required.
5309     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5310         TargetLowering::TypeSplitVector)
5311       return SDValue();
5312
5313     SDValue MaskLo, MaskHi, Lo, Hi;
5314     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5315
5316     SDValue Src0 = MLD->getSrc0();
5317     SDValue Src0Lo, Src0Hi;
5318     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5319
5320     EVT LoVT, HiVT;
5321     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5322
5323     SDValue Chain = MLD->getChain();
5324     SDValue Ptr   = MLD->getBasePtr();
5325     EVT MemoryVT = MLD->getMemoryVT();
5326     unsigned Alignment = MLD->getOriginalAlignment();
5327
5328     // if Alignment is equal to the vector size,
5329     // take the half of it for the second part
5330     unsigned SecondHalfAlignment =
5331       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5332          Alignment/2 : Alignment;
5333
5334     EVT LoMemVT, HiMemVT;
5335     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5336
5337     MachineMemOperand *MMO = DAG.getMachineFunction().
5338     getMachineMemOperand(MLD->getPointerInfo(),
5339                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5340                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5341
5342     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5343                            ISD::NON_EXTLOAD);
5344
5345     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5346     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5347                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5348
5349     MMO = DAG.getMachineFunction().
5350     getMachineMemOperand(MLD->getPointerInfo(),
5351                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5352                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5353
5354     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5355                            ISD::NON_EXTLOAD);
5356
5357     AddToWorklist(Lo.getNode());
5358     AddToWorklist(Hi.getNode());
5359
5360     // Build a factor node to remember that this load is independent of the
5361     // other one.
5362     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5363                         Hi.getValue(1));
5364
5365     // Legalized the chain result - switch anything that used the old chain to
5366     // use the new one.
5367     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5368
5369     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5370
5371     SDValue RetOps[] = { LoadRes, Chain };
5372     return DAG.getMergeValues(RetOps, DL);
5373   }
5374   return SDValue();
5375 }
5376
5377 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5378   SDValue N0 = N->getOperand(0);
5379   SDValue N1 = N->getOperand(1);
5380   SDValue N2 = N->getOperand(2);
5381   SDLoc DL(N);
5382
5383   // Canonicalize integer abs.
5384   // vselect (setg[te] X,  0),  X, -X ->
5385   // vselect (setgt    X, -1),  X, -X ->
5386   // vselect (setl[te] X,  0), -X,  X ->
5387   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5388   if (N0.getOpcode() == ISD::SETCC) {
5389     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5390     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5391     bool isAbs = false;
5392     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5393
5394     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5395          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5396         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5397       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5398     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5399              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5400       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5401
5402     if (isAbs) {
5403       EVT VT = LHS.getValueType();
5404       SDValue Shift = DAG.getNode(
5405           ISD::SRA, DL, VT, LHS,
5406           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5407       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5408       AddToWorklist(Shift.getNode());
5409       AddToWorklist(Add.getNode());
5410       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5411     }
5412   }
5413
5414   if (SimplifySelectOps(N, N1, N2))
5415     return SDValue(N, 0);  // Don't revisit N.
5416
5417   // If the VSELECT result requires splitting and the mask is provided by a
5418   // SETCC, then split both nodes and its operands before legalization. This
5419   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5420   // and enables future optimizations (e.g. min/max pattern matching on X86).
5421   if (N0.getOpcode() == ISD::SETCC) {
5422     EVT VT = N->getValueType(0);
5423
5424     // Check if any splitting is required.
5425     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5426         TargetLowering::TypeSplitVector)
5427       return SDValue();
5428
5429     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5430     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5431     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5432     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5433
5434     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5435     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5436
5437     // Add the new VSELECT nodes to the work list in case they need to be split
5438     // again.
5439     AddToWorklist(Lo.getNode());
5440     AddToWorklist(Hi.getNode());
5441
5442     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5443   }
5444
5445   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5446   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5447     return N1;
5448   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5449   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5450     return N2;
5451
5452   // The ConvertSelectToConcatVector function is assuming both the above
5453   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5454   // and addressed.
5455   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5456       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5457       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5458     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5459     if (CV.getNode())
5460       return CV;
5461   }
5462
5463   return SDValue();
5464 }
5465
5466 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5467   SDValue N0 = N->getOperand(0);
5468   SDValue N1 = N->getOperand(1);
5469   SDValue N2 = N->getOperand(2);
5470   SDValue N3 = N->getOperand(3);
5471   SDValue N4 = N->getOperand(4);
5472   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5473
5474   // fold select_cc lhs, rhs, x, x, cc -> x
5475   if (N2 == N3)
5476     return N2;
5477
5478   // Determine if the condition we're dealing with is constant
5479   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5480                               N0, N1, CC, SDLoc(N), false);
5481   if (SCC.getNode()) {
5482     AddToWorklist(SCC.getNode());
5483
5484     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5485       if (!SCCC->isNullValue())
5486         return N2;    // cond always true -> true val
5487       else
5488         return N3;    // cond always false -> false val
5489     } else if (SCC->getOpcode() == ISD::UNDEF) {
5490       // When the condition is UNDEF, just return the first operand. This is
5491       // coherent the DAG creation, no setcc node is created in this case
5492       return N2;
5493     } else if (SCC.getOpcode() == ISD::SETCC) {
5494       // Fold to a simpler select_cc
5495       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5496                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5497                          SCC.getOperand(2));
5498     }
5499   }
5500
5501   // If we can fold this based on the true/false value, do so.
5502   if (SimplifySelectOps(N, N2, N3))
5503     return SDValue(N, 0);  // Don't revisit N.
5504
5505   // fold select_cc into other things, such as min/max/abs
5506   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5507 }
5508
5509 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5510   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5511                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5512                        SDLoc(N));
5513 }
5514
5515 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5516 // dag node into a ConstantSDNode or a build_vector of constants.
5517 // This function is called by the DAGCombiner when visiting sext/zext/aext
5518 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5519 // Vector extends are not folded if operations are legal; this is to
5520 // avoid introducing illegal build_vector dag nodes.
5521 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5522                                          SelectionDAG &DAG, bool LegalTypes,
5523                                          bool LegalOperations) {
5524   unsigned Opcode = N->getOpcode();
5525   SDValue N0 = N->getOperand(0);
5526   EVT VT = N->getValueType(0);
5527
5528   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5529          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5530
5531   // fold (sext c1) -> c1
5532   // fold (zext c1) -> c1
5533   // fold (aext c1) -> c1
5534   if (isa<ConstantSDNode>(N0))
5535     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5536
5537   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5538   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5539   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5540   EVT SVT = VT.getScalarType();
5541   if (!(VT.isVector() &&
5542       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5543       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5544     return nullptr;
5545
5546   // We can fold this node into a build_vector.
5547   unsigned VTBits = SVT.getSizeInBits();
5548   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5549   unsigned ShAmt = VTBits - EVTBits;
5550   SmallVector<SDValue, 8> Elts;
5551   unsigned NumElts = N0->getNumOperands();
5552   SDLoc DL(N);
5553
5554   for (unsigned i=0; i != NumElts; ++i) {
5555     SDValue Op = N0->getOperand(i);
5556     if (Op->getOpcode() == ISD::UNDEF) {
5557       Elts.push_back(DAG.getUNDEF(SVT));
5558       continue;
5559     }
5560
5561     SDLoc DL(Op);
5562     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5563     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5564     if (Opcode == ISD::SIGN_EXTEND)
5565       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5566                                      DL, SVT));
5567     else
5568       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5569                                      DL, SVT));
5570   }
5571
5572   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5573 }
5574
5575 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5576 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5577 // transformation. Returns true if extension are possible and the above
5578 // mentioned transformation is profitable.
5579 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5580                                     unsigned ExtOpc,
5581                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5582                                     const TargetLowering &TLI) {
5583   bool HasCopyToRegUses = false;
5584   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5585   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5586                             UE = N0.getNode()->use_end();
5587        UI != UE; ++UI) {
5588     SDNode *User = *UI;
5589     if (User == N)
5590       continue;
5591     if (UI.getUse().getResNo() != N0.getResNo())
5592       continue;
5593     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5594     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5595       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5596       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5597         // Sign bits will be lost after a zext.
5598         return false;
5599       bool Add = false;
5600       for (unsigned i = 0; i != 2; ++i) {
5601         SDValue UseOp = User->getOperand(i);
5602         if (UseOp == N0)
5603           continue;
5604         if (!isa<ConstantSDNode>(UseOp))
5605           return false;
5606         Add = true;
5607       }
5608       if (Add)
5609         ExtendNodes.push_back(User);
5610       continue;
5611     }
5612     // If truncates aren't free and there are users we can't
5613     // extend, it isn't worthwhile.
5614     if (!isTruncFree)
5615       return false;
5616     // Remember if this value is live-out.
5617     if (User->getOpcode() == ISD::CopyToReg)
5618       HasCopyToRegUses = true;
5619   }
5620
5621   if (HasCopyToRegUses) {
5622     bool BothLiveOut = false;
5623     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5624          UI != UE; ++UI) {
5625       SDUse &Use = UI.getUse();
5626       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5627         BothLiveOut = true;
5628         break;
5629       }
5630     }
5631     if (BothLiveOut)
5632       // Both unextended and extended values are live out. There had better be
5633       // a good reason for the transformation.
5634       return ExtendNodes.size();
5635   }
5636   return true;
5637 }
5638
5639 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5640                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5641                                   ISD::NodeType ExtType) {
5642   // Extend SetCC uses if necessary.
5643   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5644     SDNode *SetCC = SetCCs[i];
5645     SmallVector<SDValue, 4> Ops;
5646
5647     for (unsigned j = 0; j != 2; ++j) {
5648       SDValue SOp = SetCC->getOperand(j);
5649       if (SOp == Trunc)
5650         Ops.push_back(ExtLoad);
5651       else
5652         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5653     }
5654
5655     Ops.push_back(SetCC->getOperand(2));
5656     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5657   }
5658 }
5659
5660 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5661 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5662   SDValue N0 = N->getOperand(0);
5663   EVT DstVT = N->getValueType(0);
5664   EVT SrcVT = N0.getValueType();
5665
5666   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5667           N->getOpcode() == ISD::ZERO_EXTEND) &&
5668          "Unexpected node type (not an extend)!");
5669
5670   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5671   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5672   //   (v8i32 (sext (v8i16 (load x))))
5673   // into:
5674   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5675   //                          (v4i32 (sextload (x + 16)))))
5676   // Where uses of the original load, i.e.:
5677   //   (v8i16 (load x))
5678   // are replaced with:
5679   //   (v8i16 (truncate
5680   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5681   //                            (v4i32 (sextload (x + 16)))))))
5682   //
5683   // This combine is only applicable to illegal, but splittable, vectors.
5684   // All legal types, and illegal non-vector types, are handled elsewhere.
5685   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5686   //
5687   if (N0->getOpcode() != ISD::LOAD)
5688     return SDValue();
5689
5690   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5691
5692   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5693       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5694       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5695     return SDValue();
5696
5697   SmallVector<SDNode *, 4> SetCCs;
5698   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5699     return SDValue();
5700
5701   ISD::LoadExtType ExtType =
5702       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5703
5704   // Try to split the vector types to get down to legal types.
5705   EVT SplitSrcVT = SrcVT;
5706   EVT SplitDstVT = DstVT;
5707   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5708          SplitSrcVT.getVectorNumElements() > 1) {
5709     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5710     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5711   }
5712
5713   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5714     return SDValue();
5715
5716   SDLoc DL(N);
5717   const unsigned NumSplits =
5718       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5719   const unsigned Stride = SplitSrcVT.getStoreSize();
5720   SmallVector<SDValue, 4> Loads;
5721   SmallVector<SDValue, 4> Chains;
5722
5723   SDValue BasePtr = LN0->getBasePtr();
5724   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5725     const unsigned Offset = Idx * Stride;
5726     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5727
5728     SDValue SplitLoad = DAG.getExtLoad(
5729         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5730         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5731         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5732         Align, LN0->getAAInfo());
5733
5734     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5735                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5736
5737     Loads.push_back(SplitLoad.getValue(0));
5738     Chains.push_back(SplitLoad.getValue(1));
5739   }
5740
5741   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5742   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5743
5744   CombineTo(N, NewValue);
5745
5746   // Replace uses of the original load (before extension)
5747   // with a truncate of the concatenated sextloaded vectors.
5748   SDValue Trunc =
5749       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5750   CombineTo(N0.getNode(), Trunc, NewChain);
5751   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5752                   (ISD::NodeType)N->getOpcode());
5753   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5754 }
5755
5756 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5757   SDValue N0 = N->getOperand(0);
5758   EVT VT = N->getValueType(0);
5759
5760   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5761                                               LegalOperations))
5762     return SDValue(Res, 0);
5763
5764   // fold (sext (sext x)) -> (sext x)
5765   // fold (sext (aext x)) -> (sext x)
5766   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5767     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5768                        N0.getOperand(0));
5769
5770   if (N0.getOpcode() == ISD::TRUNCATE) {
5771     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5772     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5773     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5774     if (NarrowLoad.getNode()) {
5775       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5776       if (NarrowLoad.getNode() != N0.getNode()) {
5777         CombineTo(N0.getNode(), NarrowLoad);
5778         // CombineTo deleted the truncate, if needed, but not what's under it.
5779         AddToWorklist(oye);
5780       }
5781       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5782     }
5783
5784     // See if the value being truncated is already sign extended.  If so, just
5785     // eliminate the trunc/sext pair.
5786     SDValue Op = N0.getOperand(0);
5787     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5788     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5789     unsigned DestBits = VT.getScalarType().getSizeInBits();
5790     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5791
5792     if (OpBits == DestBits) {
5793       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5794       // bits, it is already ready.
5795       if (NumSignBits > DestBits-MidBits)
5796         return Op;
5797     } else if (OpBits < DestBits) {
5798       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5799       // bits, just sext from i32.
5800       if (NumSignBits > OpBits-MidBits)
5801         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5802     } else {
5803       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5804       // bits, just truncate to i32.
5805       if (NumSignBits > OpBits-MidBits)
5806         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5807     }
5808
5809     // fold (sext (truncate x)) -> (sextinreg x).
5810     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5811                                                  N0.getValueType())) {
5812       if (OpBits < DestBits)
5813         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5814       else if (OpBits > DestBits)
5815         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5816       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5817                          DAG.getValueType(N0.getValueType()));
5818     }
5819   }
5820
5821   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5822   // Only generate vector extloads when 1) they're legal, and 2) they are
5823   // deemed desirable by the target.
5824   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5825       ((!LegalOperations && !VT.isVector() &&
5826         !cast<LoadSDNode>(N0)->isVolatile()) ||
5827        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5828     bool DoXform = true;
5829     SmallVector<SDNode*, 4> SetCCs;
5830     if (!N0.hasOneUse())
5831       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5832     if (VT.isVector())
5833       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5834     if (DoXform) {
5835       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5836       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5837                                        LN0->getChain(),
5838                                        LN0->getBasePtr(), N0.getValueType(),
5839                                        LN0->getMemOperand());
5840       CombineTo(N, ExtLoad);
5841       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5842                                   N0.getValueType(), ExtLoad);
5843       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5844       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5845                       ISD::SIGN_EXTEND);
5846       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5847     }
5848   }
5849
5850   // fold (sext (load x)) to multiple smaller sextloads.
5851   // Only on illegal but splittable vectors.
5852   if (SDValue ExtLoad = CombineExtLoad(N))
5853     return ExtLoad;
5854
5855   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5856   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5857   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5858       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5859     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5860     EVT MemVT = LN0->getMemoryVT();
5861     if ((!LegalOperations && !LN0->isVolatile()) ||
5862         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5863       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5864                                        LN0->getChain(),
5865                                        LN0->getBasePtr(), MemVT,
5866                                        LN0->getMemOperand());
5867       CombineTo(N, ExtLoad);
5868       CombineTo(N0.getNode(),
5869                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5870                             N0.getValueType(), ExtLoad),
5871                 ExtLoad.getValue(1));
5872       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5873     }
5874   }
5875
5876   // fold (sext (and/or/xor (load x), cst)) ->
5877   //      (and/or/xor (sextload x), (sext cst))
5878   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5879        N0.getOpcode() == ISD::XOR) &&
5880       isa<LoadSDNode>(N0.getOperand(0)) &&
5881       N0.getOperand(1).getOpcode() == ISD::Constant &&
5882       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5883       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5884     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5885     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5886       bool DoXform = true;
5887       SmallVector<SDNode*, 4> SetCCs;
5888       if (!N0.hasOneUse())
5889         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5890                                           SetCCs, TLI);
5891       if (DoXform) {
5892         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5893                                          LN0->getChain(), LN0->getBasePtr(),
5894                                          LN0->getMemoryVT(),
5895                                          LN0->getMemOperand());
5896         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5897         Mask = Mask.sext(VT.getSizeInBits());
5898         SDLoc DL(N);
5899         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5900                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5901         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5902                                     SDLoc(N0.getOperand(0)),
5903                                     N0.getOperand(0).getValueType(), ExtLoad);
5904         CombineTo(N, And);
5905         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5906         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5907                         ISD::SIGN_EXTEND);
5908         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5909       }
5910     }
5911   }
5912
5913   if (N0.getOpcode() == ISD::SETCC) {
5914     EVT N0VT = N0.getOperand(0).getValueType();
5915     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5916     // Only do this before legalize for now.
5917     if (VT.isVector() && !LegalOperations &&
5918         TLI.getBooleanContents(N0VT) ==
5919             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5920       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5921       // of the same size as the compared operands. Only optimize sext(setcc())
5922       // if this is the case.
5923       EVT SVT = getSetCCResultType(N0VT);
5924
5925       // We know that the # elements of the results is the same as the
5926       // # elements of the compare (and the # elements of the compare result
5927       // for that matter).  Check to see that they are the same size.  If so,
5928       // we know that the element size of the sext'd result matches the
5929       // element size of the compare operands.
5930       if (VT.getSizeInBits() == SVT.getSizeInBits())
5931         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5932                              N0.getOperand(1),
5933                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5934
5935       // If the desired elements are smaller or larger than the source
5936       // elements we can use a matching integer vector type and then
5937       // truncate/sign extend
5938       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5939       if (SVT == MatchingVectorType) {
5940         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5941                                N0.getOperand(0), N0.getOperand(1),
5942                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5943         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5944       }
5945     }
5946
5947     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5948     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5949     SDLoc DL(N);
5950     SDValue NegOne =
5951       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5952     SDValue SCC =
5953       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5954                        NegOne, DAG.getConstant(0, DL, VT),
5955                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5956     if (SCC.getNode()) return SCC;
5957
5958     if (!VT.isVector()) {
5959       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5960       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5961         SDLoc DL(N);
5962         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5963         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5964                                      N0.getOperand(0), N0.getOperand(1), CC);
5965         return DAG.getSelect(DL, VT, SetCC,
5966                              NegOne, DAG.getConstant(0, DL, VT));
5967       }
5968     }
5969   }
5970
5971   // fold (sext x) -> (zext x) if the sign bit is known zero.
5972   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5973       DAG.SignBitIsZero(N0))
5974     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5975
5976   return SDValue();
5977 }
5978
5979 // isTruncateOf - If N is a truncate of some other value, return true, record
5980 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5981 // This function computes KnownZero to avoid a duplicated call to
5982 // computeKnownBits in the caller.
5983 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5984                          APInt &KnownZero) {
5985   APInt KnownOne;
5986   if (N->getOpcode() == ISD::TRUNCATE) {
5987     Op = N->getOperand(0);
5988     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5989     return true;
5990   }
5991
5992   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5993       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5994     return false;
5995
5996   SDValue Op0 = N->getOperand(0);
5997   SDValue Op1 = N->getOperand(1);
5998   assert(Op0.getValueType() == Op1.getValueType());
5999
6000   if (isNullConstant(Op0))
6001     Op = Op1;
6002   else if (isNullConstant(Op1))
6003     Op = Op0;
6004   else
6005     return false;
6006
6007   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6008
6009   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6010     return false;
6011
6012   return true;
6013 }
6014
6015 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6016   SDValue N0 = N->getOperand(0);
6017   EVT VT = N->getValueType(0);
6018
6019   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6020                                               LegalOperations))
6021     return SDValue(Res, 0);
6022
6023   // fold (zext (zext x)) -> (zext x)
6024   // fold (zext (aext x)) -> (zext x)
6025   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6026     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6027                        N0.getOperand(0));
6028
6029   // fold (zext (truncate x)) -> (zext x) or
6030   //      (zext (truncate x)) -> (truncate x)
6031   // This is valid when the truncated bits of x are already zero.
6032   // FIXME: We should extend this to work for vectors too.
6033   SDValue Op;
6034   APInt KnownZero;
6035   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6036     APInt TruncatedBits =
6037       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6038       APInt(Op.getValueSizeInBits(), 0) :
6039       APInt::getBitsSet(Op.getValueSizeInBits(),
6040                         N0.getValueSizeInBits(),
6041                         std::min(Op.getValueSizeInBits(),
6042                                  VT.getSizeInBits()));
6043     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6044       if (VT.bitsGT(Op.getValueType()))
6045         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6046       if (VT.bitsLT(Op.getValueType()))
6047         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6048
6049       return Op;
6050     }
6051   }
6052
6053   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6054   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6055   if (N0.getOpcode() == ISD::TRUNCATE) {
6056     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6057     if (NarrowLoad.getNode()) {
6058       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6059       if (NarrowLoad.getNode() != N0.getNode()) {
6060         CombineTo(N0.getNode(), NarrowLoad);
6061         // CombineTo deleted the truncate, if needed, but not what's under it.
6062         AddToWorklist(oye);
6063       }
6064       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6065     }
6066   }
6067
6068   // fold (zext (truncate x)) -> (and x, mask)
6069   if (N0.getOpcode() == ISD::TRUNCATE &&
6070       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6071
6072     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6073     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6074     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6075     if (NarrowLoad.getNode()) {
6076       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6077       if (NarrowLoad.getNode() != N0.getNode()) {
6078         CombineTo(N0.getNode(), NarrowLoad);
6079         // CombineTo deleted the truncate, if needed, but not what's under it.
6080         AddToWorklist(oye);
6081       }
6082       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6083     }
6084
6085     SDValue Op = N0.getOperand(0);
6086     if (Op.getValueType().bitsLT(VT)) {
6087       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6088       AddToWorklist(Op.getNode());
6089     } else if (Op.getValueType().bitsGT(VT)) {
6090       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6091       AddToWorklist(Op.getNode());
6092     }
6093     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6094                                   N0.getValueType().getScalarType());
6095   }
6096
6097   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6098   // if either of the casts is not free.
6099   if (N0.getOpcode() == ISD::AND &&
6100       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6101       N0.getOperand(1).getOpcode() == ISD::Constant &&
6102       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6103                            N0.getValueType()) ||
6104        !TLI.isZExtFree(N0.getValueType(), VT))) {
6105     SDValue X = N0.getOperand(0).getOperand(0);
6106     if (X.getValueType().bitsLT(VT)) {
6107       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6108     } else if (X.getValueType().bitsGT(VT)) {
6109       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6110     }
6111     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6112     Mask = Mask.zext(VT.getSizeInBits());
6113     SDLoc DL(N);
6114     return DAG.getNode(ISD::AND, DL, VT,
6115                        X, DAG.getConstant(Mask, DL, VT));
6116   }
6117
6118   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6119   // Only generate vector extloads when 1) they're legal, and 2) they are
6120   // deemed desirable by the target.
6121   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6122       ((!LegalOperations && !VT.isVector() &&
6123         !cast<LoadSDNode>(N0)->isVolatile()) ||
6124        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6125     bool DoXform = true;
6126     SmallVector<SDNode*, 4> SetCCs;
6127     if (!N0.hasOneUse())
6128       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6129     if (VT.isVector())
6130       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6131     if (DoXform) {
6132       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6133       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6134                                        LN0->getChain(),
6135                                        LN0->getBasePtr(), N0.getValueType(),
6136                                        LN0->getMemOperand());
6137       CombineTo(N, ExtLoad);
6138       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6139                                   N0.getValueType(), ExtLoad);
6140       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6141
6142       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6143                       ISD::ZERO_EXTEND);
6144       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6145     }
6146   }
6147
6148   // fold (zext (load x)) to multiple smaller zextloads.
6149   // Only on illegal but splittable vectors.
6150   if (SDValue ExtLoad = CombineExtLoad(N))
6151     return ExtLoad;
6152
6153   // fold (zext (and/or/xor (load x), cst)) ->
6154   //      (and/or/xor (zextload x), (zext cst))
6155   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6156        N0.getOpcode() == ISD::XOR) &&
6157       isa<LoadSDNode>(N0.getOperand(0)) &&
6158       N0.getOperand(1).getOpcode() == ISD::Constant &&
6159       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6160       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6161     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6162     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6163       bool DoXform = true;
6164       SmallVector<SDNode*, 4> SetCCs;
6165       if (!N0.hasOneUse())
6166         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6167                                           SetCCs, TLI);
6168       if (DoXform) {
6169         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6170                                          LN0->getChain(), LN0->getBasePtr(),
6171                                          LN0->getMemoryVT(),
6172                                          LN0->getMemOperand());
6173         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6174         Mask = Mask.zext(VT.getSizeInBits());
6175         SDLoc DL(N);
6176         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6177                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6178         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6179                                     SDLoc(N0.getOperand(0)),
6180                                     N0.getOperand(0).getValueType(), ExtLoad);
6181         CombineTo(N, And);
6182         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6183         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6184                         ISD::ZERO_EXTEND);
6185         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6186       }
6187     }
6188   }
6189
6190   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6191   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6192   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6193       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6194     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6195     EVT MemVT = LN0->getMemoryVT();
6196     if ((!LegalOperations && !LN0->isVolatile()) ||
6197         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6198       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6199                                        LN0->getChain(),
6200                                        LN0->getBasePtr(), MemVT,
6201                                        LN0->getMemOperand());
6202       CombineTo(N, ExtLoad);
6203       CombineTo(N0.getNode(),
6204                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6205                             ExtLoad),
6206                 ExtLoad.getValue(1));
6207       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6208     }
6209   }
6210
6211   if (N0.getOpcode() == ISD::SETCC) {
6212     if (!LegalOperations && VT.isVector() &&
6213         N0.getValueType().getVectorElementType() == MVT::i1) {
6214       EVT N0VT = N0.getOperand(0).getValueType();
6215       if (getSetCCResultType(N0VT) == N0.getValueType())
6216         return SDValue();
6217
6218       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6219       // Only do this before legalize for now.
6220       EVT EltVT = VT.getVectorElementType();
6221       SDLoc DL(N);
6222       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6223                                     DAG.getConstant(1, DL, EltVT));
6224       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6225         // We know that the # elements of the results is the same as the
6226         // # elements of the compare (and the # elements of the compare result
6227         // for that matter).  Check to see that they are the same size.  If so,
6228         // we know that the element size of the sext'd result matches the
6229         // element size of the compare operands.
6230         return DAG.getNode(ISD::AND, DL, VT,
6231                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6232                                          N0.getOperand(1),
6233                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6234                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6235                                        OneOps));
6236
6237       // If the desired elements are smaller or larger than the source
6238       // elements we can use a matching integer vector type and then
6239       // truncate/sign extend
6240       EVT MatchingElementType =
6241         EVT::getIntegerVT(*DAG.getContext(),
6242                           N0VT.getScalarType().getSizeInBits());
6243       EVT MatchingVectorType =
6244         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6245                          N0VT.getVectorNumElements());
6246       SDValue VsetCC =
6247         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6248                       N0.getOperand(1),
6249                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6250       return DAG.getNode(ISD::AND, DL, VT,
6251                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6252                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6253     }
6254
6255     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6256     SDLoc DL(N);
6257     SDValue SCC =
6258       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6259                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6260                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6261     if (SCC.getNode()) return SCC;
6262   }
6263
6264   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6265   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6266       isa<ConstantSDNode>(N0.getOperand(1)) &&
6267       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6268       N0.hasOneUse()) {
6269     SDValue ShAmt = N0.getOperand(1);
6270     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6271     if (N0.getOpcode() == ISD::SHL) {
6272       SDValue InnerZExt = N0.getOperand(0);
6273       // If the original shl may be shifting out bits, do not perform this
6274       // transformation.
6275       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6276         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6277       if (ShAmtVal > KnownZeroBits)
6278         return SDValue();
6279     }
6280
6281     SDLoc DL(N);
6282
6283     // Ensure that the shift amount is wide enough for the shifted value.
6284     if (VT.getSizeInBits() >= 256)
6285       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6286
6287     return DAG.getNode(N0.getOpcode(), DL, VT,
6288                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6289                        ShAmt);
6290   }
6291
6292   return SDValue();
6293 }
6294
6295 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6296   SDValue N0 = N->getOperand(0);
6297   EVT VT = N->getValueType(0);
6298
6299   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6300                                               LegalOperations))
6301     return SDValue(Res, 0);
6302
6303   // fold (aext (aext x)) -> (aext x)
6304   // fold (aext (zext x)) -> (zext x)
6305   // fold (aext (sext x)) -> (sext x)
6306   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6307       N0.getOpcode() == ISD::ZERO_EXTEND ||
6308       N0.getOpcode() == ISD::SIGN_EXTEND)
6309     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6310
6311   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6312   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6313   if (N0.getOpcode() == ISD::TRUNCATE) {
6314     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6315     if (NarrowLoad.getNode()) {
6316       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6317       if (NarrowLoad.getNode() != N0.getNode()) {
6318         CombineTo(N0.getNode(), NarrowLoad);
6319         // CombineTo deleted the truncate, if needed, but not what's under it.
6320         AddToWorklist(oye);
6321       }
6322       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6323     }
6324   }
6325
6326   // fold (aext (truncate x))
6327   if (N0.getOpcode() == ISD::TRUNCATE) {
6328     SDValue TruncOp = N0.getOperand(0);
6329     if (TruncOp.getValueType() == VT)
6330       return TruncOp; // x iff x size == zext size.
6331     if (TruncOp.getValueType().bitsGT(VT))
6332       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6333     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6334   }
6335
6336   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6337   // if the trunc is not free.
6338   if (N0.getOpcode() == ISD::AND &&
6339       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6340       N0.getOperand(1).getOpcode() == ISD::Constant &&
6341       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6342                           N0.getValueType())) {
6343     SDValue X = N0.getOperand(0).getOperand(0);
6344     if (X.getValueType().bitsLT(VT)) {
6345       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6346     } else if (X.getValueType().bitsGT(VT)) {
6347       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6348     }
6349     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6350     Mask = Mask.zext(VT.getSizeInBits());
6351     SDLoc DL(N);
6352     return DAG.getNode(ISD::AND, DL, VT,
6353                        X, DAG.getConstant(Mask, DL, VT));
6354   }
6355
6356   // fold (aext (load x)) -> (aext (truncate (extload x)))
6357   // None of the supported targets knows how to perform load and any_ext
6358   // on vectors in one instruction.  We only perform this transformation on
6359   // scalars.
6360   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6361       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6362       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6363     bool DoXform = true;
6364     SmallVector<SDNode*, 4> SetCCs;
6365     if (!N0.hasOneUse())
6366       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6367     if (DoXform) {
6368       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6369       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6370                                        LN0->getChain(),
6371                                        LN0->getBasePtr(), N0.getValueType(),
6372                                        LN0->getMemOperand());
6373       CombineTo(N, ExtLoad);
6374       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6375                                   N0.getValueType(), ExtLoad);
6376       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6377       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6378                       ISD::ANY_EXTEND);
6379       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6380     }
6381   }
6382
6383   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6384   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6385   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6386   if (N0.getOpcode() == ISD::LOAD &&
6387       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6388       N0.hasOneUse()) {
6389     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6390     ISD::LoadExtType ExtType = LN0->getExtensionType();
6391     EVT MemVT = LN0->getMemoryVT();
6392     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6393       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6394                                        VT, LN0->getChain(), LN0->getBasePtr(),
6395                                        MemVT, LN0->getMemOperand());
6396       CombineTo(N, ExtLoad);
6397       CombineTo(N0.getNode(),
6398                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6399                             N0.getValueType(), ExtLoad),
6400                 ExtLoad.getValue(1));
6401       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6402     }
6403   }
6404
6405   if (N0.getOpcode() == ISD::SETCC) {
6406     // For vectors:
6407     // aext(setcc) -> vsetcc
6408     // aext(setcc) -> truncate(vsetcc)
6409     // aext(setcc) -> aext(vsetcc)
6410     // Only do this before legalize for now.
6411     if (VT.isVector() && !LegalOperations) {
6412       EVT N0VT = N0.getOperand(0).getValueType();
6413         // We know that the # elements of the results is the same as the
6414         // # elements of the compare (and the # elements of the compare result
6415         // for that matter).  Check to see that they are the same size.  If so,
6416         // we know that the element size of the sext'd result matches the
6417         // element size of the compare operands.
6418       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6419         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6420                              N0.getOperand(1),
6421                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6422       // If the desired elements are smaller or larger than the source
6423       // elements we can use a matching integer vector type and then
6424       // truncate/any extend
6425       else {
6426         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6427         SDValue VsetCC =
6428           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6429                         N0.getOperand(1),
6430                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6431         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6432       }
6433     }
6434
6435     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6436     SDLoc DL(N);
6437     SDValue SCC =
6438       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6439                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6440                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6441     if (SCC.getNode())
6442       return SCC;
6443   }
6444
6445   return SDValue();
6446 }
6447
6448 /// See if the specified operand can be simplified with the knowledge that only
6449 /// the bits specified by Mask are used.  If so, return the simpler operand,
6450 /// otherwise return a null SDValue.
6451 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6452   switch (V.getOpcode()) {
6453   default: break;
6454   case ISD::Constant: {
6455     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6456     assert(CV && "Const value should be ConstSDNode.");
6457     const APInt &CVal = CV->getAPIntValue();
6458     APInt NewVal = CVal & Mask;
6459     if (NewVal != CVal)
6460       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6461     break;
6462   }
6463   case ISD::OR:
6464   case ISD::XOR:
6465     // If the LHS or RHS don't contribute bits to the or, drop them.
6466     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6467       return V.getOperand(1);
6468     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6469       return V.getOperand(0);
6470     break;
6471   case ISD::SRL:
6472     // Only look at single-use SRLs.
6473     if (!V.getNode()->hasOneUse())
6474       break;
6475     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6476       // See if we can recursively simplify the LHS.
6477       unsigned Amt = RHSC->getZExtValue();
6478
6479       // Watch out for shift count overflow though.
6480       if (Amt >= Mask.getBitWidth()) break;
6481       APInt NewMask = Mask << Amt;
6482       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6483       if (SimplifyLHS.getNode())
6484         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6485                            SimplifyLHS, V.getOperand(1));
6486     }
6487   }
6488   return SDValue();
6489 }
6490
6491 /// If the result of a wider load is shifted to right of N  bits and then
6492 /// truncated to a narrower type and where N is a multiple of number of bits of
6493 /// the narrower type, transform it to a narrower load from address + N / num of
6494 /// bits of new type. If the result is to be extended, also fold the extension
6495 /// to form a extending load.
6496 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6497   unsigned Opc = N->getOpcode();
6498
6499   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6500   SDValue N0 = N->getOperand(0);
6501   EVT VT = N->getValueType(0);
6502   EVT ExtVT = VT;
6503
6504   // This transformation isn't valid for vector loads.
6505   if (VT.isVector())
6506     return SDValue();
6507
6508   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6509   // extended to VT.
6510   if (Opc == ISD::SIGN_EXTEND_INREG) {
6511     ExtType = ISD::SEXTLOAD;
6512     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6513   } else if (Opc == ISD::SRL) {
6514     // Another special-case: SRL is basically zero-extending a narrower value.
6515     ExtType = ISD::ZEXTLOAD;
6516     N0 = SDValue(N, 0);
6517     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6518     if (!N01) return SDValue();
6519     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6520                               VT.getSizeInBits() - N01->getZExtValue());
6521   }
6522   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6523     return SDValue();
6524
6525   unsigned EVTBits = ExtVT.getSizeInBits();
6526
6527   // Do not generate loads of non-round integer types since these can
6528   // be expensive (and would be wrong if the type is not byte sized).
6529   if (!ExtVT.isRound())
6530     return SDValue();
6531
6532   unsigned ShAmt = 0;
6533   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6534     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6535       ShAmt = N01->getZExtValue();
6536       // Is the shift amount a multiple of size of VT?
6537       if ((ShAmt & (EVTBits-1)) == 0) {
6538         N0 = N0.getOperand(0);
6539         // Is the load width a multiple of size of VT?
6540         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6541           return SDValue();
6542       }
6543
6544       // At this point, we must have a load or else we can't do the transform.
6545       if (!isa<LoadSDNode>(N0)) return SDValue();
6546
6547       // Because a SRL must be assumed to *need* to zero-extend the high bits
6548       // (as opposed to anyext the high bits), we can't combine the zextload
6549       // lowering of SRL and an sextload.
6550       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6551         return SDValue();
6552
6553       // If the shift amount is larger than the input type then we're not
6554       // accessing any of the loaded bytes.  If the load was a zextload/extload
6555       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6556       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6557         return SDValue();
6558     }
6559   }
6560
6561   // If the load is shifted left (and the result isn't shifted back right),
6562   // we can fold the truncate through the shift.
6563   unsigned ShLeftAmt = 0;
6564   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6565       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6566     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6567       ShLeftAmt = N01->getZExtValue();
6568       N0 = N0.getOperand(0);
6569     }
6570   }
6571
6572   // If we haven't found a load, we can't narrow it.  Don't transform one with
6573   // multiple uses, this would require adding a new load.
6574   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6575     return SDValue();
6576
6577   // Don't change the width of a volatile load.
6578   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6579   if (LN0->isVolatile())
6580     return SDValue();
6581
6582   // Verify that we are actually reducing a load width here.
6583   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6584     return SDValue();
6585
6586   // For the transform to be legal, the load must produce only two values
6587   // (the value loaded and the chain).  Don't transform a pre-increment
6588   // load, for example, which produces an extra value.  Otherwise the
6589   // transformation is not equivalent, and the downstream logic to replace
6590   // uses gets things wrong.
6591   if (LN0->getNumValues() > 2)
6592     return SDValue();
6593
6594   // If the load that we're shrinking is an extload and we're not just
6595   // discarding the extension we can't simply shrink the load. Bail.
6596   // TODO: It would be possible to merge the extensions in some cases.
6597   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6598       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6599     return SDValue();
6600
6601   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6602     return SDValue();
6603
6604   EVT PtrType = N0.getOperand(1).getValueType();
6605
6606   if (PtrType == MVT::Untyped || PtrType.isExtended())
6607     // It's not possible to generate a constant of extended or untyped type.
6608     return SDValue();
6609
6610   // For big endian targets, we need to adjust the offset to the pointer to
6611   // load the correct bytes.
6612   if (TLI.isBigEndian()) {
6613     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6614     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6615     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6616   }
6617
6618   uint64_t PtrOff = ShAmt / 8;
6619   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6620   SDLoc DL(LN0);
6621   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6622                                PtrType, LN0->getBasePtr(),
6623                                DAG.getConstant(PtrOff, DL, PtrType));
6624   AddToWorklist(NewPtr.getNode());
6625
6626   SDValue Load;
6627   if (ExtType == ISD::NON_EXTLOAD)
6628     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6629                         LN0->getPointerInfo().getWithOffset(PtrOff),
6630                         LN0->isVolatile(), LN0->isNonTemporal(),
6631                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6632   else
6633     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6634                           LN0->getPointerInfo().getWithOffset(PtrOff),
6635                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6636                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6637
6638   // Replace the old load's chain with the new load's chain.
6639   WorklistRemover DeadNodes(*this);
6640   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6641
6642   // Shift the result left, if we've swallowed a left shift.
6643   SDValue Result = Load;
6644   if (ShLeftAmt != 0) {
6645     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6646     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6647       ShImmTy = VT;
6648     // If the shift amount is as large as the result size (but, presumably,
6649     // no larger than the source) then the useful bits of the result are
6650     // zero; we can't simply return the shortened shift, because the result
6651     // of that operation is undefined.
6652     SDLoc DL(N0);
6653     if (ShLeftAmt >= VT.getSizeInBits())
6654       Result = DAG.getConstant(0, DL, VT);
6655     else
6656       Result = DAG.getNode(ISD::SHL, DL, VT,
6657                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6658   }
6659
6660   // Return the new loaded value.
6661   return Result;
6662 }
6663
6664 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6665   SDValue N0 = N->getOperand(0);
6666   SDValue N1 = N->getOperand(1);
6667   EVT VT = N->getValueType(0);
6668   EVT EVT = cast<VTSDNode>(N1)->getVT();
6669   unsigned VTBits = VT.getScalarType().getSizeInBits();
6670   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6671
6672   // fold (sext_in_reg c1) -> c1
6673   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6674     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6675
6676   // If the input is already sign extended, just drop the extension.
6677   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6678     return N0;
6679
6680   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6681   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6682       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6683     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6684                        N0.getOperand(0), N1);
6685
6686   // fold (sext_in_reg (sext x)) -> (sext x)
6687   // fold (sext_in_reg (aext x)) -> (sext x)
6688   // if x is small enough.
6689   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6690     SDValue N00 = N0.getOperand(0);
6691     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6692         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6693       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6694   }
6695
6696   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6697   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6698     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6699
6700   // fold operands of sext_in_reg based on knowledge that the top bits are not
6701   // demanded.
6702   if (SimplifyDemandedBits(SDValue(N, 0)))
6703     return SDValue(N, 0);
6704
6705   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6706   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6707   SDValue NarrowLoad = ReduceLoadWidth(N);
6708   if (NarrowLoad.getNode())
6709     return NarrowLoad;
6710
6711   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6712   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6713   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6714   if (N0.getOpcode() == ISD::SRL) {
6715     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6716       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6717         // We can turn this into an SRA iff the input to the SRL is already sign
6718         // extended enough.
6719         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6720         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6721           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6722                              N0.getOperand(0), N0.getOperand(1));
6723       }
6724   }
6725
6726   // fold (sext_inreg (extload x)) -> (sextload x)
6727   if (ISD::isEXTLoad(N0.getNode()) &&
6728       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6729       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6730       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6731        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6732     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6733     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6734                                      LN0->getChain(),
6735                                      LN0->getBasePtr(), EVT,
6736                                      LN0->getMemOperand());
6737     CombineTo(N, ExtLoad);
6738     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6739     AddToWorklist(ExtLoad.getNode());
6740     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6741   }
6742   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6743   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6744       N0.hasOneUse() &&
6745       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6746       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6747        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6748     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6749     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6750                                      LN0->getChain(),
6751                                      LN0->getBasePtr(), EVT,
6752                                      LN0->getMemOperand());
6753     CombineTo(N, ExtLoad);
6754     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6755     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6756   }
6757
6758   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6759   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6760     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6761                                        N0.getOperand(1), false);
6762     if (BSwap.getNode())
6763       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6764                          BSwap, N1);
6765   }
6766
6767   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6768   // into a build_vector.
6769   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6770     SmallVector<SDValue, 8> Elts;
6771     unsigned NumElts = N0->getNumOperands();
6772     unsigned ShAmt = VTBits - EVTBits;
6773
6774     for (unsigned i = 0; i != NumElts; ++i) {
6775       SDValue Op = N0->getOperand(i);
6776       if (Op->getOpcode() == ISD::UNDEF) {
6777         Elts.push_back(Op);
6778         continue;
6779       }
6780
6781       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6782       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6783       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6784                                      SDLoc(Op), Op.getValueType()));
6785     }
6786
6787     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6788   }
6789
6790   return SDValue();
6791 }
6792
6793 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6794   SDValue N0 = N->getOperand(0);
6795   EVT VT = N->getValueType(0);
6796   bool isLE = TLI.isLittleEndian();
6797
6798   // noop truncate
6799   if (N0.getValueType() == N->getValueType(0))
6800     return N0;
6801   // fold (truncate c1) -> c1
6802   if (isConstantIntBuildVectorOrConstantInt(N0))
6803     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6804   // fold (truncate (truncate x)) -> (truncate x)
6805   if (N0.getOpcode() == ISD::TRUNCATE)
6806     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6807   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6808   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6809       N0.getOpcode() == ISD::SIGN_EXTEND ||
6810       N0.getOpcode() == ISD::ANY_EXTEND) {
6811     if (N0.getOperand(0).getValueType().bitsLT(VT))
6812       // if the source is smaller than the dest, we still need an extend
6813       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6814                          N0.getOperand(0));
6815     if (N0.getOperand(0).getValueType().bitsGT(VT))
6816       // if the source is larger than the dest, than we just need the truncate
6817       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6818     // if the source and dest are the same type, we can drop both the extend
6819     // and the truncate.
6820     return N0.getOperand(0);
6821   }
6822
6823   // Fold extract-and-trunc into a narrow extract. For example:
6824   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6825   //   i32 y = TRUNCATE(i64 x)
6826   //        -- becomes --
6827   //   v16i8 b = BITCAST (v2i64 val)
6828   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6829   //
6830   // Note: We only run this optimization after type legalization (which often
6831   // creates this pattern) and before operation legalization after which
6832   // we need to be more careful about the vector instructions that we generate.
6833   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6834       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6835
6836     EVT VecTy = N0.getOperand(0).getValueType();
6837     EVT ExTy = N0.getValueType();
6838     EVT TrTy = N->getValueType(0);
6839
6840     unsigned NumElem = VecTy.getVectorNumElements();
6841     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6842
6843     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6844     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6845
6846     SDValue EltNo = N0->getOperand(1);
6847     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6848       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6849       EVT IndexTy = TLI.getVectorIdxTy();
6850       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6851
6852       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6853                               NVT, N0.getOperand(0));
6854
6855       SDLoc DL(N);
6856       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6857                          DL, TrTy, V,
6858                          DAG.getConstant(Index, DL, IndexTy));
6859     }
6860   }
6861
6862   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6863   if (N0.getOpcode() == ISD::SELECT) {
6864     EVT SrcVT = N0.getValueType();
6865     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6866         TLI.isTruncateFree(SrcVT, VT)) {
6867       SDLoc SL(N0);
6868       SDValue Cond = N0.getOperand(0);
6869       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6870       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6871       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6872     }
6873   }
6874
6875   // Fold a series of buildvector, bitcast, and truncate if possible.
6876   // For example fold
6877   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6878   //   (2xi32 (buildvector x, y)).
6879   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6880       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6881       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6882       N0.getOperand(0).hasOneUse()) {
6883
6884     SDValue BuildVect = N0.getOperand(0);
6885     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6886     EVT TruncVecEltTy = VT.getVectorElementType();
6887
6888     // Check that the element types match.
6889     if (BuildVectEltTy == TruncVecEltTy) {
6890       // Now we only need to compute the offset of the truncated elements.
6891       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6892       unsigned TruncVecNumElts = VT.getVectorNumElements();
6893       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6894
6895       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6896              "Invalid number of elements");
6897
6898       SmallVector<SDValue, 8> Opnds;
6899       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6900         Opnds.push_back(BuildVect.getOperand(i));
6901
6902       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6903     }
6904   }
6905
6906   // See if we can simplify the input to this truncate through knowledge that
6907   // only the low bits are being used.
6908   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6909   // Currently we only perform this optimization on scalars because vectors
6910   // may have different active low bits.
6911   if (!VT.isVector()) {
6912     SDValue Shorter =
6913       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6914                                                VT.getSizeInBits()));
6915     if (Shorter.getNode())
6916       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6917   }
6918   // fold (truncate (load x)) -> (smaller load x)
6919   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6920   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6921     SDValue Reduced = ReduceLoadWidth(N);
6922     if (Reduced.getNode())
6923       return Reduced;
6924     // Handle the case where the load remains an extending load even
6925     // after truncation.
6926     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6927       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6928       if (!LN0->isVolatile() &&
6929           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6930         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6931                                          VT, LN0->getChain(), LN0->getBasePtr(),
6932                                          LN0->getMemoryVT(),
6933                                          LN0->getMemOperand());
6934         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6935         return NewLoad;
6936       }
6937     }
6938   }
6939   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6940   // where ... are all 'undef'.
6941   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6942     SmallVector<EVT, 8> VTs;
6943     SDValue V;
6944     unsigned Idx = 0;
6945     unsigned NumDefs = 0;
6946
6947     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6948       SDValue X = N0.getOperand(i);
6949       if (X.getOpcode() != ISD::UNDEF) {
6950         V = X;
6951         Idx = i;
6952         NumDefs++;
6953       }
6954       // Stop if more than one members are non-undef.
6955       if (NumDefs > 1)
6956         break;
6957       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6958                                      VT.getVectorElementType(),
6959                                      X.getValueType().getVectorNumElements()));
6960     }
6961
6962     if (NumDefs == 0)
6963       return DAG.getUNDEF(VT);
6964
6965     if (NumDefs == 1) {
6966       assert(V.getNode() && "The single defined operand is empty!");
6967       SmallVector<SDValue, 8> Opnds;
6968       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6969         if (i != Idx) {
6970           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6971           continue;
6972         }
6973         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6974         AddToWorklist(NV.getNode());
6975         Opnds.push_back(NV);
6976       }
6977       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6978     }
6979   }
6980
6981   // Simplify the operands using demanded-bits information.
6982   if (!VT.isVector() &&
6983       SimplifyDemandedBits(SDValue(N, 0)))
6984     return SDValue(N, 0);
6985
6986   return SDValue();
6987 }
6988
6989 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6990   SDValue Elt = N->getOperand(i);
6991   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6992     return Elt.getNode();
6993   return Elt.getOperand(Elt.getResNo()).getNode();
6994 }
6995
6996 /// build_pair (load, load) -> load
6997 /// if load locations are consecutive.
6998 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6999   assert(N->getOpcode() == ISD::BUILD_PAIR);
7000
7001   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7002   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7003   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7004       LD1->getAddressSpace() != LD2->getAddressSpace())
7005     return SDValue();
7006   EVT LD1VT = LD1->getValueType(0);
7007
7008   if (ISD::isNON_EXTLoad(LD2) &&
7009       LD2->hasOneUse() &&
7010       // If both are volatile this would reduce the number of volatile loads.
7011       // If one is volatile it might be ok, but play conservative and bail out.
7012       !LD1->isVolatile() &&
7013       !LD2->isVolatile() &&
7014       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7015     unsigned Align = LD1->getAlignment();
7016     unsigned NewAlign = TLI.getDataLayout()->
7017       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7018
7019     if (NewAlign <= Align &&
7020         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7021       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7022                          LD1->getBasePtr(), LD1->getPointerInfo(),
7023                          false, false, false, Align);
7024   }
7025
7026   return SDValue();
7027 }
7028
7029 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7030   SDValue N0 = N->getOperand(0);
7031   EVT VT = N->getValueType(0);
7032
7033   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7034   // Only do this before legalize, since afterward the target may be depending
7035   // on the bitconvert.
7036   // First check to see if this is all constant.
7037   if (!LegalTypes &&
7038       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7039       VT.isVector()) {
7040     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7041
7042     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7043     assert(!DestEltVT.isVector() &&
7044            "Element type of vector ValueType must not be vector!");
7045     if (isSimple)
7046       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7047   }
7048
7049   // If the input is a constant, let getNode fold it.
7050   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7051     // If we can't allow illegal operations, we need to check that this is just
7052     // a fp -> int or int -> conversion and that the resulting operation will
7053     // be legal.
7054     if (!LegalOperations ||
7055         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7056          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7057         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7058          TLI.isOperationLegal(ISD::Constant, VT)))
7059       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7060   }
7061
7062   // (conv (conv x, t1), t2) -> (conv x, t2)
7063   if (N0.getOpcode() == ISD::BITCAST)
7064     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7065                        N0.getOperand(0));
7066
7067   // fold (conv (load x)) -> (load (conv*)x)
7068   // If the resultant load doesn't need a higher alignment than the original!
7069   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7070       // Do not change the width of a volatile load.
7071       !cast<LoadSDNode>(N0)->isVolatile() &&
7072       // Do not remove the cast if the types differ in endian layout.
7073       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7074       TLI.hasBigEndianPartOrdering(VT) &&
7075       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7076       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7077     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7078     unsigned Align = TLI.getDataLayout()->
7079       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7080     unsigned OrigAlign = LN0->getAlignment();
7081
7082     if (Align <= OrigAlign) {
7083       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7084                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7085                                  LN0->isVolatile(), LN0->isNonTemporal(),
7086                                  LN0->isInvariant(), OrigAlign,
7087                                  LN0->getAAInfo());
7088       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7089       return Load;
7090     }
7091   }
7092
7093   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7094   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7095   // This often reduces constant pool loads.
7096   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7097        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7098       N0.getNode()->hasOneUse() && VT.isInteger() &&
7099       !VT.isVector() && !N0.getValueType().isVector()) {
7100     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7101                                   N0.getOperand(0));
7102     AddToWorklist(NewConv.getNode());
7103
7104     SDLoc DL(N);
7105     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7106     if (N0.getOpcode() == ISD::FNEG)
7107       return DAG.getNode(ISD::XOR, DL, VT,
7108                          NewConv, DAG.getConstant(SignBit, DL, VT));
7109     assert(N0.getOpcode() == ISD::FABS);
7110     return DAG.getNode(ISD::AND, DL, VT,
7111                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7112   }
7113
7114   // fold (bitconvert (fcopysign cst, x)) ->
7115   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7116   // Note that we don't handle (copysign x, cst) because this can always be
7117   // folded to an fneg or fabs.
7118   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7119       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7120       VT.isInteger() && !VT.isVector()) {
7121     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7122     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7123     if (isTypeLegal(IntXVT)) {
7124       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7125                               IntXVT, N0.getOperand(1));
7126       AddToWorklist(X.getNode());
7127
7128       // If X has a different width than the result/lhs, sext it or truncate it.
7129       unsigned VTWidth = VT.getSizeInBits();
7130       if (OrigXWidth < VTWidth) {
7131         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7132         AddToWorklist(X.getNode());
7133       } else if (OrigXWidth > VTWidth) {
7134         // To get the sign bit in the right place, we have to shift it right
7135         // before truncating.
7136         SDLoc DL(X);
7137         X = DAG.getNode(ISD::SRL, DL,
7138                         X.getValueType(), X,
7139                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7140                                         X.getValueType()));
7141         AddToWorklist(X.getNode());
7142         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7143         AddToWorklist(X.getNode());
7144       }
7145
7146       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7147       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7148                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7149       AddToWorklist(X.getNode());
7150
7151       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7152                                 VT, N0.getOperand(0));
7153       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7154                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7155       AddToWorklist(Cst.getNode());
7156
7157       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7158     }
7159   }
7160
7161   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7162   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7163     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7164     if (CombineLD.getNode())
7165       return CombineLD;
7166   }
7167
7168   // Remove double bitcasts from shuffles - this is often a legacy of
7169   // XformToShuffleWithZero being used to combine bitmaskings (of
7170   // float vectors bitcast to integer vectors) into shuffles.
7171   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7172   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7173       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7174       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7175       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7176     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7177
7178     // If operands are a bitcast, peek through if it casts the original VT.
7179     // If operands are a UNDEF or constant, just bitcast back to original VT.
7180     auto PeekThroughBitcast = [&](SDValue Op) {
7181       if (Op.getOpcode() == ISD::BITCAST &&
7182           Op.getOperand(0)->getValueType(0) == VT)
7183         return SDValue(Op.getOperand(0));
7184       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7185           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7186         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7187       return SDValue();
7188     };
7189
7190     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7191     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7192     if (!(SV0 && SV1))
7193       return SDValue();
7194
7195     int MaskScale =
7196         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7197     SmallVector<int, 8> NewMask;
7198     for (int M : SVN->getMask())
7199       for (int i = 0; i != MaskScale; ++i)
7200         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7201
7202     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7203     if (!LegalMask) {
7204       std::swap(SV0, SV1);
7205       ShuffleVectorSDNode::commuteMask(NewMask);
7206       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7207     }
7208
7209     if (LegalMask)
7210       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7211   }
7212
7213   return SDValue();
7214 }
7215
7216 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7217   EVT VT = N->getValueType(0);
7218   return CombineConsecutiveLoads(N, VT);
7219 }
7220
7221 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7222 /// operands. DstEltVT indicates the destination element value type.
7223 SDValue DAGCombiner::
7224 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7225   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7226
7227   // If this is already the right type, we're done.
7228   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7229
7230   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7231   unsigned DstBitSize = DstEltVT.getSizeInBits();
7232
7233   // If this is a conversion of N elements of one type to N elements of another
7234   // type, convert each element.  This handles FP<->INT cases.
7235   if (SrcBitSize == DstBitSize) {
7236     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7237                               BV->getValueType(0).getVectorNumElements());
7238
7239     // Due to the FP element handling below calling this routine recursively,
7240     // we can end up with a scalar-to-vector node here.
7241     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7242       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7243                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7244                                      DstEltVT, BV->getOperand(0)));
7245
7246     SmallVector<SDValue, 8> Ops;
7247     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7248       SDValue Op = BV->getOperand(i);
7249       // If the vector element type is not legal, the BUILD_VECTOR operands
7250       // are promoted and implicitly truncated.  Make that explicit here.
7251       if (Op.getValueType() != SrcEltVT)
7252         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7253       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7254                                 DstEltVT, Op));
7255       AddToWorklist(Ops.back().getNode());
7256     }
7257     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7258   }
7259
7260   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7261   // handle annoying details of growing/shrinking FP values, we convert them to
7262   // int first.
7263   if (SrcEltVT.isFloatingPoint()) {
7264     // Convert the input float vector to a int vector where the elements are the
7265     // same sizes.
7266     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7267     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7268     SrcEltVT = IntVT;
7269   }
7270
7271   // Now we know the input is an integer vector.  If the output is a FP type,
7272   // convert to integer first, then to FP of the right size.
7273   if (DstEltVT.isFloatingPoint()) {
7274     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7275     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7276
7277     // Next, convert to FP elements of the same size.
7278     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7279   }
7280
7281   SDLoc DL(BV);
7282
7283   // Okay, we know the src/dst types are both integers of differing types.
7284   // Handling growing first.
7285   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7286   if (SrcBitSize < DstBitSize) {
7287     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7288
7289     SmallVector<SDValue, 8> Ops;
7290     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7291          i += NumInputsPerOutput) {
7292       bool isLE = TLI.isLittleEndian();
7293       APInt NewBits = APInt(DstBitSize, 0);
7294       bool EltIsUndef = true;
7295       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7296         // Shift the previously computed bits over.
7297         NewBits <<= SrcBitSize;
7298         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7299         if (Op.getOpcode() == ISD::UNDEF) continue;
7300         EltIsUndef = false;
7301
7302         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7303                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7304       }
7305
7306       if (EltIsUndef)
7307         Ops.push_back(DAG.getUNDEF(DstEltVT));
7308       else
7309         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7310     }
7311
7312     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7313     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7314   }
7315
7316   // Finally, this must be the case where we are shrinking elements: each input
7317   // turns into multiple outputs.
7318   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7319   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7320                             NumOutputsPerInput*BV->getNumOperands());
7321   SmallVector<SDValue, 8> Ops;
7322
7323   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7324     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7325       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7326       continue;
7327     }
7328
7329     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7330                   getAPIntValue().zextOrTrunc(SrcBitSize);
7331
7332     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7333       APInt ThisVal = OpVal.trunc(DstBitSize);
7334       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7335       OpVal = OpVal.lshr(DstBitSize);
7336     }
7337
7338     // For big endian targets, swap the order of the pieces of each element.
7339     if (TLI.isBigEndian())
7340       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7341   }
7342
7343   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7344 }
7345
7346 /// Try to perform FMA combining on a given FADD node.
7347 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7348   SDValue N0 = N->getOperand(0);
7349   SDValue N1 = N->getOperand(1);
7350   EVT VT = N->getValueType(0);
7351   SDLoc SL(N);
7352
7353   const TargetOptions &Options = DAG.getTarget().Options;
7354   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7355                        Options.UnsafeFPMath);
7356
7357   // Floating-point multiply-add with intermediate rounding.
7358   bool HasFMAD = (LegalOperations &&
7359                   TLI.isOperationLegal(ISD::FMAD, VT));
7360
7361   // Floating-point multiply-add without intermediate rounding.
7362   bool HasFMA = ((!LegalOperations ||
7363                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7364                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7365                  UnsafeFPMath);
7366
7367   // No valid opcode, do not combine.
7368   if (!HasFMAD && !HasFMA)
7369     return SDValue();
7370
7371   // Always prefer FMAD to FMA for precision.
7372   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7373   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7374   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7375
7376   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7377   if (N0.getOpcode() == ISD::FMUL &&
7378       (Aggressive || N0->hasOneUse())) {
7379     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7380                        N0.getOperand(0), N0.getOperand(1), N1);
7381   }
7382
7383   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7384   // Note: Commutes FADD operands.
7385   if (N1.getOpcode() == ISD::FMUL &&
7386       (Aggressive || N1->hasOneUse())) {
7387     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7388                        N1.getOperand(0), N1.getOperand(1), N0);
7389   }
7390
7391   // Look through FP_EXTEND nodes to do more combining.
7392   if (UnsafeFPMath && LookThroughFPExt) {
7393     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7394     if (N0.getOpcode() == ISD::FP_EXTEND) {
7395       SDValue N00 = N0.getOperand(0);
7396       if (N00.getOpcode() == ISD::FMUL)
7397         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7398                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7399                                        N00.getOperand(0)),
7400                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7401                                        N00.getOperand(1)), N1);
7402     }
7403
7404     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7405     // Note: Commutes FADD operands.
7406     if (N1.getOpcode() == ISD::FP_EXTEND) {
7407       SDValue N10 = N1.getOperand(0);
7408       if (N10.getOpcode() == ISD::FMUL)
7409         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7410                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7411                                        N10.getOperand(0)),
7412                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7413                                        N10.getOperand(1)), N0);
7414     }
7415   }
7416
7417   // More folding opportunities when target permits.
7418   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7419     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7420     if (N0.getOpcode() == PreferredFusedOpcode &&
7421         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7422       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7423                          N0.getOperand(0), N0.getOperand(1),
7424                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7425                                      N0.getOperand(2).getOperand(0),
7426                                      N0.getOperand(2).getOperand(1),
7427                                      N1));
7428     }
7429
7430     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7431     if (N1->getOpcode() == PreferredFusedOpcode &&
7432         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7433       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7434                          N1.getOperand(0), N1.getOperand(1),
7435                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7436                                      N1.getOperand(2).getOperand(0),
7437                                      N1.getOperand(2).getOperand(1),
7438                                      N0));
7439     }
7440
7441     if (UnsafeFPMath && LookThroughFPExt) {
7442       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7443       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7444       auto FoldFAddFMAFPExtFMul = [&] (
7445           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7446         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7447                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7448                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7449                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7450                                        Z));
7451       };
7452       if (N0.getOpcode() == PreferredFusedOpcode) {
7453         SDValue N02 = N0.getOperand(2);
7454         if (N02.getOpcode() == ISD::FP_EXTEND) {
7455           SDValue N020 = N02.getOperand(0);
7456           if (N020.getOpcode() == ISD::FMUL)
7457             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7458                                         N020.getOperand(0), N020.getOperand(1),
7459                                         N1);
7460         }
7461       }
7462
7463       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7464       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7465       // FIXME: This turns two single-precision and one double-precision
7466       // operation into two double-precision operations, which might not be
7467       // interesting for all targets, especially GPUs.
7468       auto FoldFAddFPExtFMAFMul = [&] (
7469           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7470         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7472                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7473                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7475                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7476                                        Z));
7477       };
7478       if (N0.getOpcode() == ISD::FP_EXTEND) {
7479         SDValue N00 = N0.getOperand(0);
7480         if (N00.getOpcode() == PreferredFusedOpcode) {
7481           SDValue N002 = N00.getOperand(2);
7482           if (N002.getOpcode() == ISD::FMUL)
7483             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7484                                         N002.getOperand(0), N002.getOperand(1),
7485                                         N1);
7486         }
7487       }
7488
7489       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7490       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7491       if (N1.getOpcode() == PreferredFusedOpcode) {
7492         SDValue N12 = N1.getOperand(2);
7493         if (N12.getOpcode() == ISD::FP_EXTEND) {
7494           SDValue N120 = N12.getOperand(0);
7495           if (N120.getOpcode() == ISD::FMUL)
7496             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7497                                         N120.getOperand(0), N120.getOperand(1),
7498                                         N0);
7499         }
7500       }
7501
7502       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7503       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7504       // FIXME: This turns two single-precision and one double-precision
7505       // operation into two double-precision operations, which might not be
7506       // interesting for all targets, especially GPUs.
7507       if (N1.getOpcode() == ISD::FP_EXTEND) {
7508         SDValue N10 = N1.getOperand(0);
7509         if (N10.getOpcode() == PreferredFusedOpcode) {
7510           SDValue N102 = N10.getOperand(2);
7511           if (N102.getOpcode() == ISD::FMUL)
7512             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7513                                         N102.getOperand(0), N102.getOperand(1),
7514                                         N0);
7515         }
7516       }
7517     }
7518   }
7519
7520   return SDValue();
7521 }
7522
7523 /// Try to perform FMA combining on a given FSUB node.
7524 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7525   SDValue N0 = N->getOperand(0);
7526   SDValue N1 = N->getOperand(1);
7527   EVT VT = N->getValueType(0);
7528   SDLoc SL(N);
7529
7530   const TargetOptions &Options = DAG.getTarget().Options;
7531   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7532                        Options.UnsafeFPMath);
7533
7534   // Floating-point multiply-add with intermediate rounding.
7535   bool HasFMAD = (LegalOperations &&
7536                   TLI.isOperationLegal(ISD::FMAD, VT));
7537
7538   // Floating-point multiply-add without intermediate rounding.
7539   bool HasFMA = ((!LegalOperations ||
7540                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7541                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7542                  UnsafeFPMath);
7543
7544   // No valid opcode, do not combine.
7545   if (!HasFMAD && !HasFMA)
7546     return SDValue();
7547
7548   // Always prefer FMAD to FMA for precision.
7549   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7550   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7551   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7552
7553   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7554   if (N0.getOpcode() == ISD::FMUL &&
7555       (Aggressive || N0->hasOneUse())) {
7556     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7557                        N0.getOperand(0), N0.getOperand(1),
7558                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7559   }
7560
7561   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7562   // Note: Commutes FSUB operands.
7563   if (N1.getOpcode() == ISD::FMUL &&
7564       (Aggressive || N1->hasOneUse()))
7565     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7566                        DAG.getNode(ISD::FNEG, SL, VT,
7567                                    N1.getOperand(0)),
7568                        N1.getOperand(1), N0);
7569
7570   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7571   if (N0.getOpcode() == ISD::FNEG &&
7572       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7573       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7574     SDValue N00 = N0.getOperand(0).getOperand(0);
7575     SDValue N01 = N0.getOperand(0).getOperand(1);
7576     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7577                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7578                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7579   }
7580
7581   // Look through FP_EXTEND nodes to do more combining.
7582   if (UnsafeFPMath && LookThroughFPExt) {
7583     // fold (fsub (fpext (fmul x, y)), z)
7584     //   -> (fma (fpext x), (fpext y), (fneg z))
7585     if (N0.getOpcode() == ISD::FP_EXTEND) {
7586       SDValue N00 = N0.getOperand(0);
7587       if (N00.getOpcode() == ISD::FMUL)
7588         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7589                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7590                                        N00.getOperand(0)),
7591                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7592                                        N00.getOperand(1)),
7593                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7594     }
7595
7596     // fold (fsub x, (fpext (fmul y, z)))
7597     //   -> (fma (fneg (fpext y)), (fpext z), x)
7598     // Note: Commutes FSUB operands.
7599     if (N1.getOpcode() == ISD::FP_EXTEND) {
7600       SDValue N10 = N1.getOperand(0);
7601       if (N10.getOpcode() == ISD::FMUL)
7602         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7603                            DAG.getNode(ISD::FNEG, SL, VT,
7604                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7605                                                    N10.getOperand(0))),
7606                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7607                                        N10.getOperand(1)),
7608                            N0);
7609     }
7610
7611     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7612     //   -> (fneg (fma (fpext x), (fpext y), z))
7613     // Note: This could be removed with appropriate canonicalization of the
7614     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7615     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7616     // from implementing the canonicalization in visitFSUB.
7617     if (N0.getOpcode() == ISD::FP_EXTEND) {
7618       SDValue N00 = N0.getOperand(0);
7619       if (N00.getOpcode() == ISD::FNEG) {
7620         SDValue N000 = N00.getOperand(0);
7621         if (N000.getOpcode() == ISD::FMUL) {
7622           return DAG.getNode(ISD::FNEG, SL, VT,
7623                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7624                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7625                                                      N000.getOperand(0)),
7626                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7627                                                      N000.getOperand(1)),
7628                                          N1));
7629         }
7630       }
7631     }
7632
7633     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7634     //   -> (fneg (fma (fpext x)), (fpext y), z)
7635     // Note: This could be removed with appropriate canonicalization of the
7636     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7637     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7638     // from implementing the canonicalization in visitFSUB.
7639     if (N0.getOpcode() == ISD::FNEG) {
7640       SDValue N00 = N0.getOperand(0);
7641       if (N00.getOpcode() == ISD::FP_EXTEND) {
7642         SDValue N000 = N00.getOperand(0);
7643         if (N000.getOpcode() == ISD::FMUL) {
7644           return DAG.getNode(ISD::FNEG, SL, VT,
7645                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7646                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7647                                                      N000.getOperand(0)),
7648                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7649                                                      N000.getOperand(1)),
7650                                          N1));
7651         }
7652       }
7653     }
7654
7655   }
7656
7657   // More folding opportunities when target permits.
7658   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7659     // fold (fsub (fma x, y, (fmul u, v)), z)
7660     //   -> (fma x, y (fma u, v, (fneg z)))
7661     if (N0.getOpcode() == PreferredFusedOpcode &&
7662         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7663       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7664                          N0.getOperand(0), N0.getOperand(1),
7665                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7666                                      N0.getOperand(2).getOperand(0),
7667                                      N0.getOperand(2).getOperand(1),
7668                                      DAG.getNode(ISD::FNEG, SL, VT,
7669                                                  N1)));
7670     }
7671
7672     // fold (fsub x, (fma y, z, (fmul u, v)))
7673     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7674     if (N1.getOpcode() == PreferredFusedOpcode &&
7675         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7676       SDValue N20 = N1.getOperand(2).getOperand(0);
7677       SDValue N21 = N1.getOperand(2).getOperand(1);
7678       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7679                          DAG.getNode(ISD::FNEG, SL, VT,
7680                                      N1.getOperand(0)),
7681                          N1.getOperand(1),
7682                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7683                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7684
7685                                      N21, N0));
7686     }
7687
7688     if (UnsafeFPMath && LookThroughFPExt) {
7689       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7690       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7691       if (N0.getOpcode() == PreferredFusedOpcode) {
7692         SDValue N02 = N0.getOperand(2);
7693         if (N02.getOpcode() == ISD::FP_EXTEND) {
7694           SDValue N020 = N02.getOperand(0);
7695           if (N020.getOpcode() == ISD::FMUL)
7696             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7697                                N0.getOperand(0), N0.getOperand(1),
7698                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7699                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7700                                                        N020.getOperand(0)),
7701                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7702                                                        N020.getOperand(1)),
7703                                            DAG.getNode(ISD::FNEG, SL, VT,
7704                                                        N1)));
7705         }
7706       }
7707
7708       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7709       //   -> (fma (fpext x), (fpext y),
7710       //           (fma (fpext u), (fpext v), (fneg z)))
7711       // FIXME: This turns two single-precision and one double-precision
7712       // operation into two double-precision operations, which might not be
7713       // interesting for all targets, especially GPUs.
7714       if (N0.getOpcode() == ISD::FP_EXTEND) {
7715         SDValue N00 = N0.getOperand(0);
7716         if (N00.getOpcode() == PreferredFusedOpcode) {
7717           SDValue N002 = N00.getOperand(2);
7718           if (N002.getOpcode() == ISD::FMUL)
7719             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7720                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721                                            N00.getOperand(0)),
7722                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7723                                            N00.getOperand(1)),
7724                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7725                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                                        N002.getOperand(0)),
7727                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                                        N002.getOperand(1)),
7729                                            DAG.getNode(ISD::FNEG, SL, VT,
7730                                                        N1)));
7731         }
7732       }
7733
7734       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7735       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7736       if (N1.getOpcode() == PreferredFusedOpcode &&
7737         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7738         SDValue N120 = N1.getOperand(2).getOperand(0);
7739         if (N120.getOpcode() == ISD::FMUL) {
7740           SDValue N1200 = N120.getOperand(0);
7741           SDValue N1201 = N120.getOperand(1);
7742           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7744                              N1.getOperand(1),
7745                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7746                                          DAG.getNode(ISD::FNEG, SL, VT,
7747                                              DAG.getNode(ISD::FP_EXTEND, SL,
7748                                                          VT, N1200)),
7749                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7750                                                      N1201),
7751                                          N0));
7752         }
7753       }
7754
7755       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7756       //   -> (fma (fneg (fpext y)), (fpext z),
7757       //           (fma (fneg (fpext u)), (fpext v), x))
7758       // FIXME: This turns two single-precision and one double-precision
7759       // operation into two double-precision operations, which might not be
7760       // interesting for all targets, especially GPUs.
7761       if (N1.getOpcode() == ISD::FP_EXTEND &&
7762         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7763         SDValue N100 = N1.getOperand(0).getOperand(0);
7764         SDValue N101 = N1.getOperand(0).getOperand(1);
7765         SDValue N102 = N1.getOperand(0).getOperand(2);
7766         if (N102.getOpcode() == ISD::FMUL) {
7767           SDValue N1020 = N102.getOperand(0);
7768           SDValue N1021 = N102.getOperand(1);
7769           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7770                              DAG.getNode(ISD::FNEG, SL, VT,
7771                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772                                                      N100)),
7773                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7774                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7775                                          DAG.getNode(ISD::FNEG, SL, VT,
7776                                              DAG.getNode(ISD::FP_EXTEND, SL,
7777                                                          VT, N1020)),
7778                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                                      N1021),
7780                                          N0));
7781         }
7782       }
7783     }
7784   }
7785
7786   return SDValue();
7787 }
7788
7789 SDValue DAGCombiner::visitFADD(SDNode *N) {
7790   SDValue N0 = N->getOperand(0);
7791   SDValue N1 = N->getOperand(1);
7792   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7793   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7794   EVT VT = N->getValueType(0);
7795   SDLoc DL(N);
7796   const TargetOptions &Options = DAG.getTarget().Options;
7797
7798   // fold vector ops
7799   if (VT.isVector())
7800     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7801       return FoldedVOp;
7802
7803   // fold (fadd c1, c2) -> c1 + c2
7804   if (N0CFP && N1CFP)
7805     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7806
7807   // canonicalize constant to RHS
7808   if (N0CFP && !N1CFP)
7809     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7810
7811   // fold (fadd A, (fneg B)) -> (fsub A, B)
7812   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7813       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7814     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7815                        GetNegatedExpression(N1, DAG, LegalOperations));
7816
7817   // fold (fadd (fneg A), B) -> (fsub B, A)
7818   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7819       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7820     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7821                        GetNegatedExpression(N0, DAG, LegalOperations));
7822
7823   // If 'unsafe math' is enabled, fold lots of things.
7824   if (Options.UnsafeFPMath) {
7825     // No FP constant should be created after legalization as Instruction
7826     // Selection pass has a hard time dealing with FP constants.
7827     bool AllowNewConst = (Level < AfterLegalizeDAG);
7828
7829     // fold (fadd A, 0) -> A
7830     if (N1CFP && N1CFP->getValueAPF().isZero())
7831       return N0;
7832
7833     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7834     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7835         isa<ConstantFPSDNode>(N0.getOperand(1)))
7836       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7837                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7838
7839     // If allowed, fold (fadd (fneg x), x) -> 0.0
7840     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7841       return DAG.getConstantFP(0.0, DL, VT);
7842
7843     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7844     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7845       return DAG.getConstantFP(0.0, DL, VT);
7846
7847     // We can fold chains of FADD's of the same value into multiplications.
7848     // This transform is not safe in general because we are reducing the number
7849     // of rounding steps.
7850     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7851       if (N0.getOpcode() == ISD::FMUL) {
7852         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7853         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7854
7855         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7856         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7857           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7858                                        DAG.getConstantFP(1.0, DL, VT));
7859           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7860         }
7861
7862         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7863         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7864             N1.getOperand(0) == N1.getOperand(1) &&
7865             N0.getOperand(0) == N1.getOperand(0)) {
7866           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7867                                        DAG.getConstantFP(2.0, DL, VT));
7868           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7869         }
7870       }
7871
7872       if (N1.getOpcode() == ISD::FMUL) {
7873         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7874         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7875
7876         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7877         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7878           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7879                                        DAG.getConstantFP(1.0, DL, VT));
7880           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7881         }
7882
7883         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7884         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7885             N0.getOperand(0) == N0.getOperand(1) &&
7886             N1.getOperand(0) == N0.getOperand(0)) {
7887           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7888                                        DAG.getConstantFP(2.0, DL, VT));
7889           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7890         }
7891       }
7892
7893       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7894         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7895         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7896         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7897             (N0.getOperand(0) == N1)) {
7898           return DAG.getNode(ISD::FMUL, DL, VT,
7899                              N1, DAG.getConstantFP(3.0, DL, VT));
7900         }
7901       }
7902
7903       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7904         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7905         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7906         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7907             N1.getOperand(0) == N0) {
7908           return DAG.getNode(ISD::FMUL, DL, VT,
7909                              N0, DAG.getConstantFP(3.0, DL, VT));
7910         }
7911       }
7912
7913       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7914       if (AllowNewConst &&
7915           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7916           N0.getOperand(0) == N0.getOperand(1) &&
7917           N1.getOperand(0) == N1.getOperand(1) &&
7918           N0.getOperand(0) == N1.getOperand(0)) {
7919         return DAG.getNode(ISD::FMUL, DL, VT,
7920                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7921       }
7922     }
7923   } // enable-unsafe-fp-math
7924
7925   // FADD -> FMA combines:
7926   SDValue Fused = visitFADDForFMACombine(N);
7927   if (Fused) {
7928     AddToWorklist(Fused.getNode());
7929     return Fused;
7930   }
7931
7932   return SDValue();
7933 }
7934
7935 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7936   SDValue N0 = N->getOperand(0);
7937   SDValue N1 = N->getOperand(1);
7938   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7939   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7940   EVT VT = N->getValueType(0);
7941   SDLoc dl(N);
7942   const TargetOptions &Options = DAG.getTarget().Options;
7943
7944   // fold vector ops
7945   if (VT.isVector())
7946     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7947       return FoldedVOp;
7948
7949   // fold (fsub c1, c2) -> c1-c2
7950   if (N0CFP && N1CFP)
7951     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7952
7953   // fold (fsub A, (fneg B)) -> (fadd A, B)
7954   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7955     return DAG.getNode(ISD::FADD, dl, VT, N0,
7956                        GetNegatedExpression(N1, DAG, LegalOperations));
7957
7958   // If 'unsafe math' is enabled, fold lots of things.
7959   if (Options.UnsafeFPMath) {
7960     // (fsub A, 0) -> A
7961     if (N1CFP && N1CFP->getValueAPF().isZero())
7962       return N0;
7963
7964     // (fsub 0, B) -> -B
7965     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7966       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7967         return GetNegatedExpression(N1, DAG, LegalOperations);
7968       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7969         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7970     }
7971
7972     // (fsub x, x) -> 0.0
7973     if (N0 == N1)
7974       return DAG.getConstantFP(0.0f, dl, VT);
7975
7976     // (fsub x, (fadd x, y)) -> (fneg y)
7977     // (fsub x, (fadd y, x)) -> (fneg y)
7978     if (N1.getOpcode() == ISD::FADD) {
7979       SDValue N10 = N1->getOperand(0);
7980       SDValue N11 = N1->getOperand(1);
7981
7982       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7983         return GetNegatedExpression(N11, DAG, LegalOperations);
7984
7985       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7986         return GetNegatedExpression(N10, DAG, LegalOperations);
7987     }
7988   }
7989
7990   // FSUB -> FMA combines:
7991   SDValue Fused = visitFSUBForFMACombine(N);
7992   if (Fused) {
7993     AddToWorklist(Fused.getNode());
7994     return Fused;
7995   }
7996
7997   return SDValue();
7998 }
7999
8000 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8001   SDValue N0 = N->getOperand(0);
8002   SDValue N1 = N->getOperand(1);
8003   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8004   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8005   EVT VT = N->getValueType(0);
8006   SDLoc DL(N);
8007   const TargetOptions &Options = DAG.getTarget().Options;
8008
8009   // fold vector ops
8010   if (VT.isVector()) {
8011     // This just handles C1 * C2 for vectors. Other vector folds are below.
8012     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8013       return FoldedVOp;
8014   }
8015
8016   // fold (fmul c1, c2) -> c1*c2
8017   if (N0CFP && N1CFP)
8018     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8019
8020   // canonicalize constant to RHS
8021   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8022      !isConstantFPBuildVectorOrConstantFP(N1))
8023     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8024
8025   // fold (fmul A, 1.0) -> A
8026   if (N1CFP && N1CFP->isExactlyValue(1.0))
8027     return N0;
8028
8029   if (Options.UnsafeFPMath) {
8030     // fold (fmul A, 0) -> 0
8031     if (N1CFP && N1CFP->getValueAPF().isZero())
8032       return N1;
8033
8034     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8035     if (N0.getOpcode() == ISD::FMUL) {
8036       // Fold scalars or any vector constants (not just splats).
8037       // This fold is done in general by InstCombine, but extra fmul insts
8038       // may have been generated during lowering.
8039       SDValue N00 = N0.getOperand(0);
8040       SDValue N01 = N0.getOperand(1);
8041       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8042       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8043       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8044       
8045       // Check 1: Make sure that the first operand of the inner multiply is NOT
8046       // a constant. Otherwise, we may induce infinite looping.
8047       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8048         // Check 2: Make sure that the second operand of the inner multiply and
8049         // the second operand of the outer multiply are constants.
8050         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8051             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8052           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8053           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8054         }
8055       }
8056     }
8057
8058     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8059     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8060     // during an early run of DAGCombiner can prevent folding with fmuls
8061     // inserted during lowering.
8062     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8063       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8064       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8065       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8066     }
8067   }
8068
8069   // fold (fmul X, 2.0) -> (fadd X, X)
8070   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8071     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8072
8073   // fold (fmul X, -1.0) -> (fneg X)
8074   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8075     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8076       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8077
8078   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8079   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8080     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8081       // Both can be negated for free, check to see if at least one is cheaper
8082       // negated.
8083       if (LHSNeg == 2 || RHSNeg == 2)
8084         return DAG.getNode(ISD::FMUL, DL, VT,
8085                            GetNegatedExpression(N0, DAG, LegalOperations),
8086                            GetNegatedExpression(N1, DAG, LegalOperations));
8087     }
8088   }
8089
8090   return SDValue();
8091 }
8092
8093 SDValue DAGCombiner::visitFMA(SDNode *N) {
8094   SDValue N0 = N->getOperand(0);
8095   SDValue N1 = N->getOperand(1);
8096   SDValue N2 = N->getOperand(2);
8097   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8098   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8099   EVT VT = N->getValueType(0);
8100   SDLoc dl(N);
8101   const TargetOptions &Options = DAG.getTarget().Options;
8102
8103   // Constant fold FMA.
8104   if (isa<ConstantFPSDNode>(N0) &&
8105       isa<ConstantFPSDNode>(N1) &&
8106       isa<ConstantFPSDNode>(N2)) {
8107     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8108   }
8109
8110   if (Options.UnsafeFPMath) {
8111     if (N0CFP && N0CFP->isZero())
8112       return N2;
8113     if (N1CFP && N1CFP->isZero())
8114       return N2;
8115   }
8116   if (N0CFP && N0CFP->isExactlyValue(1.0))
8117     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8118   if (N1CFP && N1CFP->isExactlyValue(1.0))
8119     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8120
8121   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8122   if (N0CFP && !N1CFP)
8123     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8124
8125   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8126   if (Options.UnsafeFPMath && N1CFP &&
8127       N2.getOpcode() == ISD::FMUL &&
8128       N0 == N2.getOperand(0) &&
8129       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8130     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8131                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8132   }
8133
8134
8135   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8136   if (Options.UnsafeFPMath &&
8137       N0.getOpcode() == ISD::FMUL && N1CFP &&
8138       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8139     return DAG.getNode(ISD::FMA, dl, VT,
8140                        N0.getOperand(0),
8141                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8142                        N2);
8143   }
8144
8145   // (fma x, 1, y) -> (fadd x, y)
8146   // (fma x, -1, y) -> (fadd (fneg x), y)
8147   if (N1CFP) {
8148     if (N1CFP->isExactlyValue(1.0))
8149       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8150
8151     if (N1CFP->isExactlyValue(-1.0) &&
8152         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8153       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8154       AddToWorklist(RHSNeg.getNode());
8155       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8156     }
8157   }
8158
8159   // (fma x, c, x) -> (fmul x, (c+1))
8160   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8161     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8162                        DAG.getNode(ISD::FADD, dl, VT,
8163                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8164
8165   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8166   if (Options.UnsafeFPMath && N1CFP &&
8167       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8168     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8169                        DAG.getNode(ISD::FADD, dl, VT,
8170                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8171
8172
8173   return SDValue();
8174 }
8175
8176 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8177   SDValue N0 = N->getOperand(0);
8178   SDValue N1 = N->getOperand(1);
8179   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8180   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8181   EVT VT = N->getValueType(0);
8182   SDLoc DL(N);
8183   const TargetOptions &Options = DAG.getTarget().Options;
8184
8185   // fold vector ops
8186   if (VT.isVector())
8187     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8188       return FoldedVOp;
8189
8190   // fold (fdiv c1, c2) -> c1/c2
8191   if (N0CFP && N1CFP)
8192     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8193
8194   if (Options.UnsafeFPMath) {
8195     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8196     if (N1CFP) {
8197       // Compute the reciprocal 1.0 / c2.
8198       APFloat N1APF = N1CFP->getValueAPF();
8199       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8200       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8201       // Only do the transform if the reciprocal is a legal fp immediate that
8202       // isn't too nasty (eg NaN, denormal, ...).
8203       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8204           (!LegalOperations ||
8205            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8206            // backend)... we should handle this gracefully after Legalize.
8207            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8208            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8209            TLI.isFPImmLegal(Recip, VT)))
8210         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8211                            DAG.getConstantFP(Recip, DL, VT));
8212     }
8213
8214     // If this FDIV is part of a reciprocal square root, it may be folded
8215     // into a target-specific square root estimate instruction.
8216     if (N1.getOpcode() == ISD::FSQRT) {
8217       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8218         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8219       }
8220     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8221                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8222       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8223         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8224         AddToWorklist(RV.getNode());
8225         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8226       }
8227     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8228                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8229       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8230         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8231         AddToWorklist(RV.getNode());
8232         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8233       }
8234     } else if (N1.getOpcode() == ISD::FMUL) {
8235       // Look through an FMUL. Even though this won't remove the FDIV directly,
8236       // it's still worthwhile to get rid of the FSQRT if possible.
8237       SDValue SqrtOp;
8238       SDValue OtherOp;
8239       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8240         SqrtOp = N1.getOperand(0);
8241         OtherOp = N1.getOperand(1);
8242       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8243         SqrtOp = N1.getOperand(1);
8244         OtherOp = N1.getOperand(0);
8245       }
8246       if (SqrtOp.getNode()) {
8247         // We found a FSQRT, so try to make this fold:
8248         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8249         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8250           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8251           AddToWorklist(RV.getNode());
8252           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8253         }
8254       }
8255     }
8256
8257     // Fold into a reciprocal estimate and multiply instead of a real divide.
8258     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8259       AddToWorklist(RV.getNode());
8260       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8261     }
8262   }
8263
8264   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8265   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8266     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8267       // Both can be negated for free, check to see if at least one is cheaper
8268       // negated.
8269       if (LHSNeg == 2 || RHSNeg == 2)
8270         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8271                            GetNegatedExpression(N0, DAG, LegalOperations),
8272                            GetNegatedExpression(N1, DAG, LegalOperations));
8273     }
8274   }
8275
8276   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8277   // reciprocal.
8278   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8279   // Notice that this is not always beneficial. One reason is different target
8280   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8281   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8282   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8283   if (Options.UnsafeFPMath) {
8284     // Skip if current node is a reciprocal.
8285     if (N0CFP && N0CFP->isExactlyValue(1.0))
8286       return SDValue();
8287
8288     SmallVector<SDNode *, 4> Users;
8289     // Find all FDIV users of the same divisor.
8290     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8291                               UE = N1.getNode()->use_end();
8292          UI != UE; ++UI) {
8293       SDNode *User = UI.getUse().getUser();
8294       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8295         Users.push_back(User);
8296     }
8297
8298     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8299       SDLoc DL(N);
8300       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8301       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8302
8303       // Dividend / Divisor -> Dividend * Reciprocal
8304       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8305         if ((*I)->getOperand(0) != FPOne) {
8306           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8307                                         (*I)->getOperand(0), Reciprocal);
8308           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8309         }
8310       }
8311       return SDValue();
8312     }
8313   }
8314
8315   return SDValue();
8316 }
8317
8318 SDValue DAGCombiner::visitFREM(SDNode *N) {
8319   SDValue N0 = N->getOperand(0);
8320   SDValue N1 = N->getOperand(1);
8321   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8322   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8323   EVT VT = N->getValueType(0);
8324
8325   // fold (frem c1, c2) -> fmod(c1,c2)
8326   if (N0CFP && N1CFP)
8327     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8328
8329   return SDValue();
8330 }
8331
8332 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8333   if (DAG.getTarget().Options.UnsafeFPMath &&
8334       !TLI.isFsqrtCheap()) {
8335     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8336     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8337       EVT VT = RV.getValueType();
8338       SDLoc DL(N);
8339       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8340       AddToWorklist(RV.getNode());
8341
8342       // Unfortunately, RV is now NaN if the input was exactly 0.
8343       // Select out this case and force the answer to 0.
8344       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8345       SDValue ZeroCmp =
8346         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8347                      N->getOperand(0), Zero, ISD::SETEQ);
8348       AddToWorklist(ZeroCmp.getNode());
8349       AddToWorklist(RV.getNode());
8350
8351       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8352                        DL, VT, ZeroCmp, Zero, RV);
8353       return RV;
8354     }
8355   }
8356   return SDValue();
8357 }
8358
8359 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8360   SDValue N0 = N->getOperand(0);
8361   SDValue N1 = N->getOperand(1);
8362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8363   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8364   EVT VT = N->getValueType(0);
8365
8366   if (N0CFP && N1CFP)  // Constant fold
8367     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8368
8369   if (N1CFP) {
8370     const APFloat& V = N1CFP->getValueAPF();
8371     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8372     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8373     if (!V.isNegative()) {
8374       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8375         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8376     } else {
8377       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8378         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8379                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8380     }
8381   }
8382
8383   // copysign(fabs(x), y) -> copysign(x, y)
8384   // copysign(fneg(x), y) -> copysign(x, y)
8385   // copysign(copysign(x,z), y) -> copysign(x, y)
8386   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8387       N0.getOpcode() == ISD::FCOPYSIGN)
8388     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8389                        N0.getOperand(0), N1);
8390
8391   // copysign(x, abs(y)) -> abs(x)
8392   if (N1.getOpcode() == ISD::FABS)
8393     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8394
8395   // copysign(x, copysign(y,z)) -> copysign(x, z)
8396   if (N1.getOpcode() == ISD::FCOPYSIGN)
8397     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8398                        N0, N1.getOperand(1));
8399
8400   // copysign(x, fp_extend(y)) -> copysign(x, y)
8401   // copysign(x, fp_round(y)) -> copysign(x, y)
8402   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8403     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8404                        N0, N1.getOperand(0));
8405
8406   return SDValue();
8407 }
8408
8409 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8410   SDValue N0 = N->getOperand(0);
8411   EVT VT = N->getValueType(0);
8412   EVT OpVT = N0.getValueType();
8413
8414   // fold (sint_to_fp c1) -> c1fp
8415   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8416       // ...but only if the target supports immediate floating-point values
8417       (!LegalOperations ||
8418        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8419     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8420
8421   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8422   // but UINT_TO_FP is legal on this target, try to convert.
8423   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8424       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8425     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8426     if (DAG.SignBitIsZero(N0))
8427       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8428   }
8429
8430   // The next optimizations are desirable only if SELECT_CC can be lowered.
8431   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8432     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8433     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8434         !VT.isVector() &&
8435         (!LegalOperations ||
8436          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8437       SDLoc DL(N);
8438       SDValue Ops[] =
8439         { N0.getOperand(0), N0.getOperand(1),
8440           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8441           N0.getOperand(2) };
8442       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8443     }
8444
8445     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8446     //      (select_cc x, y, 1.0, 0.0,, cc)
8447     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8448         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8449         (!LegalOperations ||
8450          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8451       SDLoc DL(N);
8452       SDValue Ops[] =
8453         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8454           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8455           N0.getOperand(0).getOperand(2) };
8456       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8457     }
8458   }
8459
8460   return SDValue();
8461 }
8462
8463 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8464   SDValue N0 = N->getOperand(0);
8465   EVT VT = N->getValueType(0);
8466   EVT OpVT = N0.getValueType();
8467
8468   // fold (uint_to_fp c1) -> c1fp
8469   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8470       // ...but only if the target supports immediate floating-point values
8471       (!LegalOperations ||
8472        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8473     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8474
8475   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8476   // but SINT_TO_FP is legal on this target, try to convert.
8477   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8478       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8479     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8480     if (DAG.SignBitIsZero(N0))
8481       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8482   }
8483
8484   // The next optimizations are desirable only if SELECT_CC can be lowered.
8485   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8486     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8487
8488     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8489         (!LegalOperations ||
8490          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8491       SDLoc DL(N);
8492       SDValue Ops[] =
8493         { N0.getOperand(0), N0.getOperand(1),
8494           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8495           N0.getOperand(2) };
8496       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8497     }
8498   }
8499
8500   return SDValue();
8501 }
8502
8503 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8504 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8505   SDValue N0 = N->getOperand(0);
8506   EVT VT = N->getValueType(0);
8507
8508   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8509     return SDValue();
8510
8511   SDValue Src = N0.getOperand(0);
8512   EVT SrcVT = Src.getValueType();
8513   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8514   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8515
8516   // We can safely assume the conversion won't overflow the output range,
8517   // because (for example) (uint8_t)18293.f is undefined behavior.
8518
8519   // Since we can assume the conversion won't overflow, our decision as to
8520   // whether the input will fit in the float should depend on the minimum
8521   // of the input range and output range.
8522
8523   // This means this is also safe for a signed input and unsigned output, since
8524   // a negative input would lead to undefined behavior.
8525   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8526   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8527   unsigned ActualSize = std::min(InputSize, OutputSize);
8528   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8529
8530   // We can only fold away the float conversion if the input range can be
8531   // represented exactly in the float range.
8532   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8533     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8534       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8535                                                        : ISD::ZERO_EXTEND;
8536       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8537     }
8538     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8539       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8540     if (SrcVT == VT)
8541       return Src;
8542     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8543   }
8544   return SDValue();
8545 }
8546
8547 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8548   SDValue N0 = N->getOperand(0);
8549   EVT VT = N->getValueType(0);
8550
8551   // fold (fp_to_sint c1fp) -> c1
8552   if (isConstantFPBuildVectorOrConstantFP(N0))
8553     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8554
8555   return FoldIntToFPToInt(N, DAG);
8556 }
8557
8558 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8559   SDValue N0 = N->getOperand(0);
8560   EVT VT = N->getValueType(0);
8561
8562   // fold (fp_to_uint c1fp) -> c1
8563   if (isConstantFPBuildVectorOrConstantFP(N0))
8564     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8565
8566   return FoldIntToFPToInt(N, DAG);
8567 }
8568
8569 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8570   SDValue N0 = N->getOperand(0);
8571   SDValue N1 = N->getOperand(1);
8572   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8573   EVT VT = N->getValueType(0);
8574
8575   // fold (fp_round c1fp) -> c1fp
8576   if (N0CFP)
8577     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8578
8579   // fold (fp_round (fp_extend x)) -> x
8580   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8581     return N0.getOperand(0);
8582
8583   // fold (fp_round (fp_round x)) -> (fp_round x)
8584   if (N0.getOpcode() == ISD::FP_ROUND) {
8585     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8586     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8587     // If the first fp_round isn't a value preserving truncation, it might
8588     // introduce a tie in the second fp_round, that wouldn't occur in the
8589     // single-step fp_round we want to fold to.
8590     // In other words, double rounding isn't the same as rounding.
8591     // Also, this is a value preserving truncation iff both fp_round's are.
8592     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8593       SDLoc DL(N);
8594       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8595                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8596     }
8597   }
8598
8599   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8600   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8601     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8602                               N0.getOperand(0), N1);
8603     AddToWorklist(Tmp.getNode());
8604     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8605                        Tmp, N0.getOperand(1));
8606   }
8607
8608   return SDValue();
8609 }
8610
8611 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8612   SDValue N0 = N->getOperand(0);
8613   EVT VT = N->getValueType(0);
8614   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8615   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8616
8617   // fold (fp_round_inreg c1fp) -> c1fp
8618   if (N0CFP && isTypeLegal(EVT)) {
8619     SDLoc DL(N);
8620     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8621     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8622   }
8623
8624   return SDValue();
8625 }
8626
8627 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8628   SDValue N0 = N->getOperand(0);
8629   EVT VT = N->getValueType(0);
8630
8631   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8632   if (N->hasOneUse() &&
8633       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8634     return SDValue();
8635
8636   // fold (fp_extend c1fp) -> c1fp
8637   if (isConstantFPBuildVectorOrConstantFP(N0))
8638     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8639
8640   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8641   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8642       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8643     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8644
8645   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8646   // value of X.
8647   if (N0.getOpcode() == ISD::FP_ROUND
8648       && N0.getNode()->getConstantOperandVal(1) == 1) {
8649     SDValue In = N0.getOperand(0);
8650     if (In.getValueType() == VT) return In;
8651     if (VT.bitsLT(In.getValueType()))
8652       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8653                          In, N0.getOperand(1));
8654     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8655   }
8656
8657   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8658   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8659        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8660     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8661     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8662                                      LN0->getChain(),
8663                                      LN0->getBasePtr(), N0.getValueType(),
8664                                      LN0->getMemOperand());
8665     CombineTo(N, ExtLoad);
8666     CombineTo(N0.getNode(),
8667               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8668                           N0.getValueType(), ExtLoad,
8669                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8670               ExtLoad.getValue(1));
8671     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8672   }
8673
8674   return SDValue();
8675 }
8676
8677 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8678   SDValue N0 = N->getOperand(0);
8679   EVT VT = N->getValueType(0);
8680
8681   // fold (fceil c1) -> fceil(c1)
8682   if (isConstantFPBuildVectorOrConstantFP(N0))
8683     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8684
8685   return SDValue();
8686 }
8687
8688 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8689   SDValue N0 = N->getOperand(0);
8690   EVT VT = N->getValueType(0);
8691
8692   // fold (ftrunc c1) -> ftrunc(c1)
8693   if (isConstantFPBuildVectorOrConstantFP(N0))
8694     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8695
8696   return SDValue();
8697 }
8698
8699 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8700   SDValue N0 = N->getOperand(0);
8701   EVT VT = N->getValueType(0);
8702
8703   // fold (ffloor c1) -> ffloor(c1)
8704   if (isConstantFPBuildVectorOrConstantFP(N0))
8705     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8706
8707   return SDValue();
8708 }
8709
8710 // FIXME: FNEG and FABS have a lot in common; refactor.
8711 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8712   SDValue N0 = N->getOperand(0);
8713   EVT VT = N->getValueType(0);
8714
8715   // Constant fold FNEG.
8716   if (isConstantFPBuildVectorOrConstantFP(N0))
8717     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8718
8719   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8720                          &DAG.getTarget().Options))
8721     return GetNegatedExpression(N0, DAG, LegalOperations);
8722
8723   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8724   // constant pool values.
8725   if (!TLI.isFNegFree(VT) &&
8726       N0.getOpcode() == ISD::BITCAST &&
8727       N0.getNode()->hasOneUse()) {
8728     SDValue Int = N0.getOperand(0);
8729     EVT IntVT = Int.getValueType();
8730     if (IntVT.isInteger() && !IntVT.isVector()) {
8731       APInt SignMask;
8732       if (N0.getValueType().isVector()) {
8733         // For a vector, get a mask such as 0x80... per scalar element
8734         // and splat it.
8735         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8736         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8737       } else {
8738         // For a scalar, just generate 0x80...
8739         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8740       }
8741       SDLoc DL0(N0);
8742       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8743                         DAG.getConstant(SignMask, DL0, IntVT));
8744       AddToWorklist(Int.getNode());
8745       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8746     }
8747   }
8748
8749   // (fneg (fmul c, x)) -> (fmul -c, x)
8750   if (N0.getOpcode() == ISD::FMUL) {
8751     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8752     if (CFP1) {
8753       APFloat CVal = CFP1->getValueAPF();
8754       CVal.changeSign();
8755       if (Level >= AfterLegalizeDAG &&
8756           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8757            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8758         return DAG.getNode(
8759             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8760             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8761     }
8762   }
8763
8764   return SDValue();
8765 }
8766
8767 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8768   SDValue N0 = N->getOperand(0);
8769   SDValue N1 = N->getOperand(1);
8770   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8771   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8772
8773   if (N0CFP && N1CFP) {
8774     const APFloat &C0 = N0CFP->getValueAPF();
8775     const APFloat &C1 = N1CFP->getValueAPF();
8776     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8777   }
8778
8779   if (N0CFP) {
8780     EVT VT = N->getValueType(0);
8781     // Canonicalize to constant on RHS.
8782     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8783   }
8784
8785   return SDValue();
8786 }
8787
8788 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8789   SDValue N0 = N->getOperand(0);
8790   SDValue N1 = N->getOperand(1);
8791   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8792   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8793
8794   if (N0CFP && N1CFP) {
8795     const APFloat &C0 = N0CFP->getValueAPF();
8796     const APFloat &C1 = N1CFP->getValueAPF();
8797     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8798   }
8799
8800   if (N0CFP) {
8801     EVT VT = N->getValueType(0);
8802     // Canonicalize to constant on RHS.
8803     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8804   }
8805
8806   return SDValue();
8807 }
8808
8809 SDValue DAGCombiner::visitFABS(SDNode *N) {
8810   SDValue N0 = N->getOperand(0);
8811   EVT VT = N->getValueType(0);
8812
8813   // fold (fabs c1) -> fabs(c1)
8814   if (isConstantFPBuildVectorOrConstantFP(N0))
8815     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8816
8817   // fold (fabs (fabs x)) -> (fabs x)
8818   if (N0.getOpcode() == ISD::FABS)
8819     return N->getOperand(0);
8820
8821   // fold (fabs (fneg x)) -> (fabs x)
8822   // fold (fabs (fcopysign x, y)) -> (fabs x)
8823   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8824     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8825
8826   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8827   // constant pool values.
8828   if (!TLI.isFAbsFree(VT) &&
8829       N0.getOpcode() == ISD::BITCAST &&
8830       N0.getNode()->hasOneUse()) {
8831     SDValue Int = N0.getOperand(0);
8832     EVT IntVT = Int.getValueType();
8833     if (IntVT.isInteger() && !IntVT.isVector()) {
8834       APInt SignMask;
8835       if (N0.getValueType().isVector()) {
8836         // For a vector, get a mask such as 0x7f... per scalar element
8837         // and splat it.
8838         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8839         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8840       } else {
8841         // For a scalar, just generate 0x7f...
8842         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8843       }
8844       SDLoc DL(N0);
8845       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8846                         DAG.getConstant(SignMask, DL, IntVT));
8847       AddToWorklist(Int.getNode());
8848       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8849     }
8850   }
8851
8852   return SDValue();
8853 }
8854
8855 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8856   SDValue Chain = N->getOperand(0);
8857   SDValue N1 = N->getOperand(1);
8858   SDValue N2 = N->getOperand(2);
8859
8860   // If N is a constant we could fold this into a fallthrough or unconditional
8861   // branch. However that doesn't happen very often in normal code, because
8862   // Instcombine/SimplifyCFG should have handled the available opportunities.
8863   // If we did this folding here, it would be necessary to update the
8864   // MachineBasicBlock CFG, which is awkward.
8865
8866   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8867   // on the target.
8868   if (N1.getOpcode() == ISD::SETCC &&
8869       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8870                                    N1.getOperand(0).getValueType())) {
8871     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8872                        Chain, N1.getOperand(2),
8873                        N1.getOperand(0), N1.getOperand(1), N2);
8874   }
8875
8876   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8877       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8878        (N1.getOperand(0).hasOneUse() &&
8879         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8880     SDNode *Trunc = nullptr;
8881     if (N1.getOpcode() == ISD::TRUNCATE) {
8882       // Look pass the truncate.
8883       Trunc = N1.getNode();
8884       N1 = N1.getOperand(0);
8885     }
8886
8887     // Match this pattern so that we can generate simpler code:
8888     //
8889     //   %a = ...
8890     //   %b = and i32 %a, 2
8891     //   %c = srl i32 %b, 1
8892     //   brcond i32 %c ...
8893     //
8894     // into
8895     //
8896     //   %a = ...
8897     //   %b = and i32 %a, 2
8898     //   %c = setcc eq %b, 0
8899     //   brcond %c ...
8900     //
8901     // This applies only when the AND constant value has one bit set and the
8902     // SRL constant is equal to the log2 of the AND constant. The back-end is
8903     // smart enough to convert the result into a TEST/JMP sequence.
8904     SDValue Op0 = N1.getOperand(0);
8905     SDValue Op1 = N1.getOperand(1);
8906
8907     if (Op0.getOpcode() == ISD::AND &&
8908         Op1.getOpcode() == ISD::Constant) {
8909       SDValue AndOp1 = Op0.getOperand(1);
8910
8911       if (AndOp1.getOpcode() == ISD::Constant) {
8912         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8913
8914         if (AndConst.isPowerOf2() &&
8915             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8916           SDLoc DL(N);
8917           SDValue SetCC =
8918             DAG.getSetCC(DL,
8919                          getSetCCResultType(Op0.getValueType()),
8920                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8921                          ISD::SETNE);
8922
8923           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8924                                           MVT::Other, Chain, SetCC, N2);
8925           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8926           // will convert it back to (X & C1) >> C2.
8927           CombineTo(N, NewBRCond, false);
8928           // Truncate is dead.
8929           if (Trunc)
8930             deleteAndRecombine(Trunc);
8931           // Replace the uses of SRL with SETCC
8932           WorklistRemover DeadNodes(*this);
8933           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8934           deleteAndRecombine(N1.getNode());
8935           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8936         }
8937       }
8938     }
8939
8940     if (Trunc)
8941       // Restore N1 if the above transformation doesn't match.
8942       N1 = N->getOperand(1);
8943   }
8944
8945   // Transform br(xor(x, y)) -> br(x != y)
8946   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8947   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8948     SDNode *TheXor = N1.getNode();
8949     SDValue Op0 = TheXor->getOperand(0);
8950     SDValue Op1 = TheXor->getOperand(1);
8951     if (Op0.getOpcode() == Op1.getOpcode()) {
8952       // Avoid missing important xor optimizations.
8953       SDValue Tmp = visitXOR(TheXor);
8954       if (Tmp.getNode()) {
8955         if (Tmp.getNode() != TheXor) {
8956           DEBUG(dbgs() << "\nReplacing.8 ";
8957                 TheXor->dump(&DAG);
8958                 dbgs() << "\nWith: ";
8959                 Tmp.getNode()->dump(&DAG);
8960                 dbgs() << '\n');
8961           WorklistRemover DeadNodes(*this);
8962           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8963           deleteAndRecombine(TheXor);
8964           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8965                              MVT::Other, Chain, Tmp, N2);
8966         }
8967
8968         // visitXOR has changed XOR's operands or replaced the XOR completely,
8969         // bail out.
8970         return SDValue(N, 0);
8971       }
8972     }
8973
8974     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8975       bool Equal = false;
8976       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8977         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8978             Op0.getOpcode() == ISD::XOR) {
8979           TheXor = Op0.getNode();
8980           Equal = true;
8981         }
8982
8983       EVT SetCCVT = N1.getValueType();
8984       if (LegalTypes)
8985         SetCCVT = getSetCCResultType(SetCCVT);
8986       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8987                                    SetCCVT,
8988                                    Op0, Op1,
8989                                    Equal ? ISD::SETEQ : ISD::SETNE);
8990       // Replace the uses of XOR with SETCC
8991       WorklistRemover DeadNodes(*this);
8992       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8993       deleteAndRecombine(N1.getNode());
8994       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8995                          MVT::Other, Chain, SetCC, N2);
8996     }
8997   }
8998
8999   return SDValue();
9000 }
9001
9002 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9003 //
9004 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9005   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9006   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9007
9008   // If N is a constant we could fold this into a fallthrough or unconditional
9009   // branch. However that doesn't happen very often in normal code, because
9010   // Instcombine/SimplifyCFG should have handled the available opportunities.
9011   // If we did this folding here, it would be necessary to update the
9012   // MachineBasicBlock CFG, which is awkward.
9013
9014   // Use SimplifySetCC to simplify SETCC's.
9015   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9016                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9017                                false);
9018   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9019
9020   // fold to a simpler setcc
9021   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9022     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9023                        N->getOperand(0), Simp.getOperand(2),
9024                        Simp.getOperand(0), Simp.getOperand(1),
9025                        N->getOperand(4));
9026
9027   return SDValue();
9028 }
9029
9030 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9031 /// and that N may be folded in the load / store addressing mode.
9032 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9033                                     SelectionDAG &DAG,
9034                                     const TargetLowering &TLI) {
9035   EVT VT;
9036   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9037     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9038       return false;
9039     VT = LD->getMemoryVT();
9040   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9041     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9042       return false;
9043     VT = ST->getMemoryVT();
9044   } else
9045     return false;
9046
9047   TargetLowering::AddrMode AM;
9048   if (N->getOpcode() == ISD::ADD) {
9049     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9050     if (Offset)
9051       // [reg +/- imm]
9052       AM.BaseOffs = Offset->getSExtValue();
9053     else
9054       // [reg +/- reg]
9055       AM.Scale = 1;
9056   } else if (N->getOpcode() == ISD::SUB) {
9057     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9058     if (Offset)
9059       // [reg +/- imm]
9060       AM.BaseOffs = -Offset->getSExtValue();
9061     else
9062       // [reg +/- reg]
9063       AM.Scale = 1;
9064   } else
9065     return false;
9066
9067   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9068 }
9069
9070 /// Try turning a load/store into a pre-indexed load/store when the base
9071 /// pointer is an add or subtract and it has other uses besides the load/store.
9072 /// After the transformation, the new indexed load/store has effectively folded
9073 /// the add/subtract in and all of its other uses are redirected to the
9074 /// new load/store.
9075 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9076   if (Level < AfterLegalizeDAG)
9077     return false;
9078
9079   bool isLoad = true;
9080   SDValue Ptr;
9081   EVT VT;
9082   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9083     if (LD->isIndexed())
9084       return false;
9085     VT = LD->getMemoryVT();
9086     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9087         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9088       return false;
9089     Ptr = LD->getBasePtr();
9090   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9091     if (ST->isIndexed())
9092       return false;
9093     VT = ST->getMemoryVT();
9094     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9095         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9096       return false;
9097     Ptr = ST->getBasePtr();
9098     isLoad = false;
9099   } else {
9100     return false;
9101   }
9102
9103   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9104   // out.  There is no reason to make this a preinc/predec.
9105   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9106       Ptr.getNode()->hasOneUse())
9107     return false;
9108
9109   // Ask the target to do addressing mode selection.
9110   SDValue BasePtr;
9111   SDValue Offset;
9112   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9113   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9114     return false;
9115
9116   // Backends without true r+i pre-indexed forms may need to pass a
9117   // constant base with a variable offset so that constant coercion
9118   // will work with the patterns in canonical form.
9119   bool Swapped = false;
9120   if (isa<ConstantSDNode>(BasePtr)) {
9121     std::swap(BasePtr, Offset);
9122     Swapped = true;
9123   }
9124
9125   // Don't create a indexed load / store with zero offset.
9126   if (isNullConstant(Offset))
9127     return false;
9128
9129   // Try turning it into a pre-indexed load / store except when:
9130   // 1) The new base ptr is a frame index.
9131   // 2) If N is a store and the new base ptr is either the same as or is a
9132   //    predecessor of the value being stored.
9133   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9134   //    that would create a cycle.
9135   // 4) All uses are load / store ops that use it as old base ptr.
9136
9137   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9138   // (plus the implicit offset) to a register to preinc anyway.
9139   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9140     return false;
9141
9142   // Check #2.
9143   if (!isLoad) {
9144     SDValue Val = cast<StoreSDNode>(N)->getValue();
9145     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9146       return false;
9147   }
9148
9149   // If the offset is a constant, there may be other adds of constants that
9150   // can be folded with this one. We should do this to avoid having to keep
9151   // a copy of the original base pointer.
9152   SmallVector<SDNode *, 16> OtherUses;
9153   if (isa<ConstantSDNode>(Offset))
9154     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9155                               UE = BasePtr.getNode()->use_end();
9156          UI != UE; ++UI) {
9157       SDUse &Use = UI.getUse();
9158       // Skip the use that is Ptr and uses of other results from BasePtr's
9159       // node (important for nodes that return multiple results).
9160       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9161         continue;
9162
9163       if (Use.getUser()->isPredecessorOf(N))
9164         continue;
9165
9166       if (Use.getUser()->getOpcode() != ISD::ADD &&
9167           Use.getUser()->getOpcode() != ISD::SUB) {
9168         OtherUses.clear();
9169         break;
9170       }
9171
9172       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9173       if (!isa<ConstantSDNode>(Op1)) {
9174         OtherUses.clear();
9175         break;
9176       }
9177
9178       // FIXME: In some cases, we can be smarter about this.
9179       if (Op1.getValueType() != Offset.getValueType()) {
9180         OtherUses.clear();
9181         break;
9182       }
9183
9184       OtherUses.push_back(Use.getUser());
9185     }
9186
9187   if (Swapped)
9188     std::swap(BasePtr, Offset);
9189
9190   // Now check for #3 and #4.
9191   bool RealUse = false;
9192
9193   // Caches for hasPredecessorHelper
9194   SmallPtrSet<const SDNode *, 32> Visited;
9195   SmallVector<const SDNode *, 16> Worklist;
9196
9197   for (SDNode *Use : Ptr.getNode()->uses()) {
9198     if (Use == N)
9199       continue;
9200     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9201       return false;
9202
9203     // If Ptr may be folded in addressing mode of other use, then it's
9204     // not profitable to do this transformation.
9205     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9206       RealUse = true;
9207   }
9208
9209   if (!RealUse)
9210     return false;
9211
9212   SDValue Result;
9213   if (isLoad)
9214     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9215                                 BasePtr, Offset, AM);
9216   else
9217     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9218                                  BasePtr, Offset, AM);
9219   ++PreIndexedNodes;
9220   ++NodesCombined;
9221   DEBUG(dbgs() << "\nReplacing.4 ";
9222         N->dump(&DAG);
9223         dbgs() << "\nWith: ";
9224         Result.getNode()->dump(&DAG);
9225         dbgs() << '\n');
9226   WorklistRemover DeadNodes(*this);
9227   if (isLoad) {
9228     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9229     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9230   } else {
9231     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9232   }
9233
9234   // Finally, since the node is now dead, remove it from the graph.
9235   deleteAndRecombine(N);
9236
9237   if (Swapped)
9238     std::swap(BasePtr, Offset);
9239
9240   // Replace other uses of BasePtr that can be updated to use Ptr
9241   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9242     unsigned OffsetIdx = 1;
9243     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9244       OffsetIdx = 0;
9245     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9246            BasePtr.getNode() && "Expected BasePtr operand");
9247
9248     // We need to replace ptr0 in the following expression:
9249     //   x0 * offset0 + y0 * ptr0 = t0
9250     // knowing that
9251     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9252     //
9253     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9254     // indexed load/store and the expresion that needs to be re-written.
9255     //
9256     // Therefore, we have:
9257     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9258
9259     ConstantSDNode *CN =
9260       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9261     int X0, X1, Y0, Y1;
9262     APInt Offset0 = CN->getAPIntValue();
9263     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9264
9265     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9266     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9267     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9268     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9269
9270     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9271
9272     APInt CNV = Offset0;
9273     if (X0 < 0) CNV = -CNV;
9274     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9275     else CNV = CNV - Offset1;
9276
9277     SDLoc DL(OtherUses[i]);
9278
9279     // We can now generate the new expression.
9280     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9281     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9282
9283     SDValue NewUse = DAG.getNode(Opcode,
9284                                  DL,
9285                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9286     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9287     deleteAndRecombine(OtherUses[i]);
9288   }
9289
9290   // Replace the uses of Ptr with uses of the updated base value.
9291   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9292   deleteAndRecombine(Ptr.getNode());
9293
9294   return true;
9295 }
9296
9297 /// Try to combine a load/store with a add/sub of the base pointer node into a
9298 /// post-indexed load/store. The transformation folded the add/subtract into the
9299 /// new indexed load/store effectively and all of its uses are redirected to the
9300 /// new load/store.
9301 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9302   if (Level < AfterLegalizeDAG)
9303     return false;
9304
9305   bool isLoad = true;
9306   SDValue Ptr;
9307   EVT VT;
9308   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9309     if (LD->isIndexed())
9310       return false;
9311     VT = LD->getMemoryVT();
9312     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9313         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9314       return false;
9315     Ptr = LD->getBasePtr();
9316   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9317     if (ST->isIndexed())
9318       return false;
9319     VT = ST->getMemoryVT();
9320     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9321         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9322       return false;
9323     Ptr = ST->getBasePtr();
9324     isLoad = false;
9325   } else {
9326     return false;
9327   }
9328
9329   if (Ptr.getNode()->hasOneUse())
9330     return false;
9331
9332   for (SDNode *Op : Ptr.getNode()->uses()) {
9333     if (Op == N ||
9334         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9335       continue;
9336
9337     SDValue BasePtr;
9338     SDValue Offset;
9339     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9340     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9341       // Don't create a indexed load / store with zero offset.
9342       if (isNullConstant(Offset))
9343         continue;
9344
9345       // Try turning it into a post-indexed load / store except when
9346       // 1) All uses are load / store ops that use it as base ptr (and
9347       //    it may be folded as addressing mmode).
9348       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9349       //    nor a successor of N. Otherwise, if Op is folded that would
9350       //    create a cycle.
9351
9352       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9353         continue;
9354
9355       // Check for #1.
9356       bool TryNext = false;
9357       for (SDNode *Use : BasePtr.getNode()->uses()) {
9358         if (Use == Ptr.getNode())
9359           continue;
9360
9361         // If all the uses are load / store addresses, then don't do the
9362         // transformation.
9363         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9364           bool RealUse = false;
9365           for (SDNode *UseUse : Use->uses()) {
9366             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9367               RealUse = true;
9368           }
9369
9370           if (!RealUse) {
9371             TryNext = true;
9372             break;
9373           }
9374         }
9375       }
9376
9377       if (TryNext)
9378         continue;
9379
9380       // Check for #2
9381       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9382         SDValue Result = isLoad
9383           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9384                                BasePtr, Offset, AM)
9385           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9386                                 BasePtr, Offset, AM);
9387         ++PostIndexedNodes;
9388         ++NodesCombined;
9389         DEBUG(dbgs() << "\nReplacing.5 ";
9390               N->dump(&DAG);
9391               dbgs() << "\nWith: ";
9392               Result.getNode()->dump(&DAG);
9393               dbgs() << '\n');
9394         WorklistRemover DeadNodes(*this);
9395         if (isLoad) {
9396           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9397           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9398         } else {
9399           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9400         }
9401
9402         // Finally, since the node is now dead, remove it from the graph.
9403         deleteAndRecombine(N);
9404
9405         // Replace the uses of Use with uses of the updated base value.
9406         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9407                                       Result.getValue(isLoad ? 1 : 0));
9408         deleteAndRecombine(Op);
9409         return true;
9410       }
9411     }
9412   }
9413
9414   return false;
9415 }
9416
9417 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9418 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9419   ISD::MemIndexedMode AM = LD->getAddressingMode();
9420   assert(AM != ISD::UNINDEXED);
9421   SDValue BP = LD->getOperand(1);
9422   SDValue Inc = LD->getOperand(2);
9423
9424   // Some backends use TargetConstants for load offsets, but don't expect
9425   // TargetConstants in general ADD nodes. We can convert these constants into
9426   // regular Constants (if the constant is not opaque).
9427   assert((Inc.getOpcode() != ISD::TargetConstant ||
9428           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9429          "Cannot split out indexing using opaque target constants");
9430   if (Inc.getOpcode() == ISD::TargetConstant) {
9431     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9432     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9433                           ConstInc->getValueType(0));
9434   }
9435
9436   unsigned Opc =
9437       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9438   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9439 }
9440
9441 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9442   LoadSDNode *LD  = cast<LoadSDNode>(N);
9443   SDValue Chain = LD->getChain();
9444   SDValue Ptr   = LD->getBasePtr();
9445
9446   // If load is not volatile and there are no uses of the loaded value (and
9447   // the updated indexed value in case of indexed loads), change uses of the
9448   // chain value into uses of the chain input (i.e. delete the dead load).
9449   if (!LD->isVolatile()) {
9450     if (N->getValueType(1) == MVT::Other) {
9451       // Unindexed loads.
9452       if (!N->hasAnyUseOfValue(0)) {
9453         // It's not safe to use the two value CombineTo variant here. e.g.
9454         // v1, chain2 = load chain1, loc
9455         // v2, chain3 = load chain2, loc
9456         // v3         = add v2, c
9457         // Now we replace use of chain2 with chain1.  This makes the second load
9458         // isomorphic to the one we are deleting, and thus makes this load live.
9459         DEBUG(dbgs() << "\nReplacing.6 ";
9460               N->dump(&DAG);
9461               dbgs() << "\nWith chain: ";
9462               Chain.getNode()->dump(&DAG);
9463               dbgs() << "\n");
9464         WorklistRemover DeadNodes(*this);
9465         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9466
9467         if (N->use_empty())
9468           deleteAndRecombine(N);
9469
9470         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9471       }
9472     } else {
9473       // Indexed loads.
9474       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9475
9476       // If this load has an opaque TargetConstant offset, then we cannot split
9477       // the indexing into an add/sub directly (that TargetConstant may not be
9478       // valid for a different type of node, and we cannot convert an opaque
9479       // target constant into a regular constant).
9480       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9481                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9482
9483       if (!N->hasAnyUseOfValue(0) &&
9484           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9485         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9486         SDValue Index;
9487         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9488           Index = SplitIndexingFromLoad(LD);
9489           // Try to fold the base pointer arithmetic into subsequent loads and
9490           // stores.
9491           AddUsersToWorklist(N);
9492         } else
9493           Index = DAG.getUNDEF(N->getValueType(1));
9494         DEBUG(dbgs() << "\nReplacing.7 ";
9495               N->dump(&DAG);
9496               dbgs() << "\nWith: ";
9497               Undef.getNode()->dump(&DAG);
9498               dbgs() << " and 2 other values\n");
9499         WorklistRemover DeadNodes(*this);
9500         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9501         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9502         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9503         deleteAndRecombine(N);
9504         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9505       }
9506     }
9507   }
9508
9509   // If this load is directly stored, replace the load value with the stored
9510   // value.
9511   // TODO: Handle store large -> read small portion.
9512   // TODO: Handle TRUNCSTORE/LOADEXT
9513   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9514     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9515       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9516       if (PrevST->getBasePtr() == Ptr &&
9517           PrevST->getValue().getValueType() == N->getValueType(0))
9518       return CombineTo(N, Chain.getOperand(1), Chain);
9519     }
9520   }
9521
9522   // Try to infer better alignment information than the load already has.
9523   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9524     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9525       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9526         SDValue NewLoad =
9527                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9528                               LD->getValueType(0),
9529                               Chain, Ptr, LD->getPointerInfo(),
9530                               LD->getMemoryVT(),
9531                               LD->isVolatile(), LD->isNonTemporal(),
9532                               LD->isInvariant(), Align, LD->getAAInfo());
9533         if (NewLoad.getNode() != N)
9534           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9535       }
9536     }
9537   }
9538
9539   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9540                                                   : DAG.getSubtarget().useAA();
9541 #ifndef NDEBUG
9542   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9543       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9544     UseAA = false;
9545 #endif
9546   if (UseAA && LD->isUnindexed()) {
9547     // Walk up chain skipping non-aliasing memory nodes.
9548     SDValue BetterChain = FindBetterChain(N, Chain);
9549
9550     // If there is a better chain.
9551     if (Chain != BetterChain) {
9552       SDValue ReplLoad;
9553
9554       // Replace the chain to void dependency.
9555       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9556         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9557                                BetterChain, Ptr, LD->getMemOperand());
9558       } else {
9559         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9560                                   LD->getValueType(0),
9561                                   BetterChain, Ptr, LD->getMemoryVT(),
9562                                   LD->getMemOperand());
9563       }
9564
9565       // Create token factor to keep old chain connected.
9566       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9567                                   MVT::Other, Chain, ReplLoad.getValue(1));
9568
9569       // Make sure the new and old chains are cleaned up.
9570       AddToWorklist(Token.getNode());
9571
9572       // Replace uses with load result and token factor. Don't add users
9573       // to work list.
9574       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9575     }
9576   }
9577
9578   // Try transforming N to an indexed load.
9579   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9580     return SDValue(N, 0);
9581
9582   // Try to slice up N to more direct loads if the slices are mapped to
9583   // different register banks or pairing can take place.
9584   if (SliceUpLoad(N))
9585     return SDValue(N, 0);
9586
9587   return SDValue();
9588 }
9589
9590 namespace {
9591 /// \brief Helper structure used to slice a load in smaller loads.
9592 /// Basically a slice is obtained from the following sequence:
9593 /// Origin = load Ty1, Base
9594 /// Shift = srl Ty1 Origin, CstTy Amount
9595 /// Inst = trunc Shift to Ty2
9596 ///
9597 /// Then, it will be rewriten into:
9598 /// Slice = load SliceTy, Base + SliceOffset
9599 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9600 ///
9601 /// SliceTy is deduced from the number of bits that are actually used to
9602 /// build Inst.
9603 struct LoadedSlice {
9604   /// \brief Helper structure used to compute the cost of a slice.
9605   struct Cost {
9606     /// Are we optimizing for code size.
9607     bool ForCodeSize;
9608     /// Various cost.
9609     unsigned Loads;
9610     unsigned Truncates;
9611     unsigned CrossRegisterBanksCopies;
9612     unsigned ZExts;
9613     unsigned Shift;
9614
9615     Cost(bool ForCodeSize = false)
9616         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9617           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9618
9619     /// \brief Get the cost of one isolated slice.
9620     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9621         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9622           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9623       EVT TruncType = LS.Inst->getValueType(0);
9624       EVT LoadedType = LS.getLoadedType();
9625       if (TruncType != LoadedType &&
9626           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9627         ZExts = 1;
9628     }
9629
9630     /// \brief Account for slicing gain in the current cost.
9631     /// Slicing provide a few gains like removing a shift or a
9632     /// truncate. This method allows to grow the cost of the original
9633     /// load with the gain from this slice.
9634     void addSliceGain(const LoadedSlice &LS) {
9635       // Each slice saves a truncate.
9636       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9637       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9638                               LS.Inst->getOperand(0).getValueType()))
9639         ++Truncates;
9640       // If there is a shift amount, this slice gets rid of it.
9641       if (LS.Shift)
9642         ++Shift;
9643       // If this slice can merge a cross register bank copy, account for it.
9644       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9645         ++CrossRegisterBanksCopies;
9646     }
9647
9648     Cost &operator+=(const Cost &RHS) {
9649       Loads += RHS.Loads;
9650       Truncates += RHS.Truncates;
9651       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9652       ZExts += RHS.ZExts;
9653       Shift += RHS.Shift;
9654       return *this;
9655     }
9656
9657     bool operator==(const Cost &RHS) const {
9658       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9659              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9660              ZExts == RHS.ZExts && Shift == RHS.Shift;
9661     }
9662
9663     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9664
9665     bool operator<(const Cost &RHS) const {
9666       // Assume cross register banks copies are as expensive as loads.
9667       // FIXME: Do we want some more target hooks?
9668       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9669       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9670       // Unless we are optimizing for code size, consider the
9671       // expensive operation first.
9672       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9673         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9674       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9675              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9676     }
9677
9678     bool operator>(const Cost &RHS) const { return RHS < *this; }
9679
9680     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9681
9682     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9683   };
9684   // The last instruction that represent the slice. This should be a
9685   // truncate instruction.
9686   SDNode *Inst;
9687   // The original load instruction.
9688   LoadSDNode *Origin;
9689   // The right shift amount in bits from the original load.
9690   unsigned Shift;
9691   // The DAG from which Origin came from.
9692   // This is used to get some contextual information about legal types, etc.
9693   SelectionDAG *DAG;
9694
9695   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9696               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9697       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9698
9699   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9700   /// \return Result is \p BitWidth and has used bits set to 1 and
9701   ///         not used bits set to 0.
9702   APInt getUsedBits() const {
9703     // Reproduce the trunc(lshr) sequence:
9704     // - Start from the truncated value.
9705     // - Zero extend to the desired bit width.
9706     // - Shift left.
9707     assert(Origin && "No original load to compare against.");
9708     unsigned BitWidth = Origin->getValueSizeInBits(0);
9709     assert(Inst && "This slice is not bound to an instruction");
9710     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9711            "Extracted slice is bigger than the whole type!");
9712     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9713     UsedBits.setAllBits();
9714     UsedBits = UsedBits.zext(BitWidth);
9715     UsedBits <<= Shift;
9716     return UsedBits;
9717   }
9718
9719   /// \brief Get the size of the slice to be loaded in bytes.
9720   unsigned getLoadedSize() const {
9721     unsigned SliceSize = getUsedBits().countPopulation();
9722     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9723     return SliceSize / 8;
9724   }
9725
9726   /// \brief Get the type that will be loaded for this slice.
9727   /// Note: This may not be the final type for the slice.
9728   EVT getLoadedType() const {
9729     assert(DAG && "Missing context");
9730     LLVMContext &Ctxt = *DAG->getContext();
9731     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9732   }
9733
9734   /// \brief Get the alignment of the load used for this slice.
9735   unsigned getAlignment() const {
9736     unsigned Alignment = Origin->getAlignment();
9737     unsigned Offset = getOffsetFromBase();
9738     if (Offset != 0)
9739       Alignment = MinAlign(Alignment, Alignment + Offset);
9740     return Alignment;
9741   }
9742
9743   /// \brief Check if this slice can be rewritten with legal operations.
9744   bool isLegal() const {
9745     // An invalid slice is not legal.
9746     if (!Origin || !Inst || !DAG)
9747       return false;
9748
9749     // Offsets are for indexed load only, we do not handle that.
9750     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9751       return false;
9752
9753     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9754
9755     // Check that the type is legal.
9756     EVT SliceType = getLoadedType();
9757     if (!TLI.isTypeLegal(SliceType))
9758       return false;
9759
9760     // Check that the load is legal for this type.
9761     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9762       return false;
9763
9764     // Check that the offset can be computed.
9765     // 1. Check its type.
9766     EVT PtrType = Origin->getBasePtr().getValueType();
9767     if (PtrType == MVT::Untyped || PtrType.isExtended())
9768       return false;
9769
9770     // 2. Check that it fits in the immediate.
9771     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9772       return false;
9773
9774     // 3. Check that the computation is legal.
9775     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9776       return false;
9777
9778     // Check that the zext is legal if it needs one.
9779     EVT TruncateType = Inst->getValueType(0);
9780     if (TruncateType != SliceType &&
9781         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9782       return false;
9783
9784     return true;
9785   }
9786
9787   /// \brief Get the offset in bytes of this slice in the original chunk of
9788   /// bits.
9789   /// \pre DAG != nullptr.
9790   uint64_t getOffsetFromBase() const {
9791     assert(DAG && "Missing context.");
9792     bool IsBigEndian =
9793         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9794     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9795     uint64_t Offset = Shift / 8;
9796     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9797     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9798            "The size of the original loaded type is not a multiple of a"
9799            " byte.");
9800     // If Offset is bigger than TySizeInBytes, it means we are loading all
9801     // zeros. This should have been optimized before in the process.
9802     assert(TySizeInBytes > Offset &&
9803            "Invalid shift amount for given loaded size");
9804     if (IsBigEndian)
9805       Offset = TySizeInBytes - Offset - getLoadedSize();
9806     return Offset;
9807   }
9808
9809   /// \brief Generate the sequence of instructions to load the slice
9810   /// represented by this object and redirect the uses of this slice to
9811   /// this new sequence of instructions.
9812   /// \pre this->Inst && this->Origin are valid Instructions and this
9813   /// object passed the legal check: LoadedSlice::isLegal returned true.
9814   /// \return The last instruction of the sequence used to load the slice.
9815   SDValue loadSlice() const {
9816     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9817     const SDValue &OldBaseAddr = Origin->getBasePtr();
9818     SDValue BaseAddr = OldBaseAddr;
9819     // Get the offset in that chunk of bytes w.r.t. the endianess.
9820     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9821     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9822     if (Offset) {
9823       // BaseAddr = BaseAddr + Offset.
9824       EVT ArithType = BaseAddr.getValueType();
9825       SDLoc DL(Origin);
9826       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9827                               DAG->getConstant(Offset, DL, ArithType));
9828     }
9829
9830     // Create the type of the loaded slice according to its size.
9831     EVT SliceType = getLoadedType();
9832
9833     // Create the load for the slice.
9834     SDValue LastInst = DAG->getLoad(
9835         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9836         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9837         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9838     // If the final type is not the same as the loaded type, this means that
9839     // we have to pad with zero. Create a zero extend for that.
9840     EVT FinalType = Inst->getValueType(0);
9841     if (SliceType != FinalType)
9842       LastInst =
9843           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9844     return LastInst;
9845   }
9846
9847   /// \brief Check if this slice can be merged with an expensive cross register
9848   /// bank copy. E.g.,
9849   /// i = load i32
9850   /// f = bitcast i32 i to float
9851   bool canMergeExpensiveCrossRegisterBankCopy() const {
9852     if (!Inst || !Inst->hasOneUse())
9853       return false;
9854     SDNode *Use = *Inst->use_begin();
9855     if (Use->getOpcode() != ISD::BITCAST)
9856       return false;
9857     assert(DAG && "Missing context");
9858     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9859     EVT ResVT = Use->getValueType(0);
9860     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9861     const TargetRegisterClass *ArgRC =
9862         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9863     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9864       return false;
9865
9866     // At this point, we know that we perform a cross-register-bank copy.
9867     // Check if it is expensive.
9868     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9869     // Assume bitcasts are cheap, unless both register classes do not
9870     // explicitly share a common sub class.
9871     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9872       return false;
9873
9874     // Check if it will be merged with the load.
9875     // 1. Check the alignment constraint.
9876     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9877         ResVT.getTypeForEVT(*DAG->getContext()));
9878
9879     if (RequiredAlignment > getAlignment())
9880       return false;
9881
9882     // 2. Check that the load is a legal operation for that type.
9883     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9884       return false;
9885
9886     // 3. Check that we do not have a zext in the way.
9887     if (Inst->getValueType(0) != getLoadedType())
9888       return false;
9889
9890     return true;
9891   }
9892 };
9893 }
9894
9895 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9896 /// \p UsedBits looks like 0..0 1..1 0..0.
9897 static bool areUsedBitsDense(const APInt &UsedBits) {
9898   // If all the bits are one, this is dense!
9899   if (UsedBits.isAllOnesValue())
9900     return true;
9901
9902   // Get rid of the unused bits on the right.
9903   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9904   // Get rid of the unused bits on the left.
9905   if (NarrowedUsedBits.countLeadingZeros())
9906     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9907   // Check that the chunk of bits is completely used.
9908   return NarrowedUsedBits.isAllOnesValue();
9909 }
9910
9911 /// \brief Check whether or not \p First and \p Second are next to each other
9912 /// in memory. This means that there is no hole between the bits loaded
9913 /// by \p First and the bits loaded by \p Second.
9914 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9915                                      const LoadedSlice &Second) {
9916   assert(First.Origin == Second.Origin && First.Origin &&
9917          "Unable to match different memory origins.");
9918   APInt UsedBits = First.getUsedBits();
9919   assert((UsedBits & Second.getUsedBits()) == 0 &&
9920          "Slices are not supposed to overlap.");
9921   UsedBits |= Second.getUsedBits();
9922   return areUsedBitsDense(UsedBits);
9923 }
9924
9925 /// \brief Adjust the \p GlobalLSCost according to the target
9926 /// paring capabilities and the layout of the slices.
9927 /// \pre \p GlobalLSCost should account for at least as many loads as
9928 /// there is in the slices in \p LoadedSlices.
9929 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9930                                  LoadedSlice::Cost &GlobalLSCost) {
9931   unsigned NumberOfSlices = LoadedSlices.size();
9932   // If there is less than 2 elements, no pairing is possible.
9933   if (NumberOfSlices < 2)
9934     return;
9935
9936   // Sort the slices so that elements that are likely to be next to each
9937   // other in memory are next to each other in the list.
9938   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9939             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9940     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9941     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9942   });
9943   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9944   // First (resp. Second) is the first (resp. Second) potentially candidate
9945   // to be placed in a paired load.
9946   const LoadedSlice *First = nullptr;
9947   const LoadedSlice *Second = nullptr;
9948   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9949                 // Set the beginning of the pair.
9950                                                            First = Second) {
9951
9952     Second = &LoadedSlices[CurrSlice];
9953
9954     // If First is NULL, it means we start a new pair.
9955     // Get to the next slice.
9956     if (!First)
9957       continue;
9958
9959     EVT LoadedType = First->getLoadedType();
9960
9961     // If the types of the slices are different, we cannot pair them.
9962     if (LoadedType != Second->getLoadedType())
9963       continue;
9964
9965     // Check if the target supplies paired loads for this type.
9966     unsigned RequiredAlignment = 0;
9967     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9968       // move to the next pair, this type is hopeless.
9969       Second = nullptr;
9970       continue;
9971     }
9972     // Check if we meet the alignment requirement.
9973     if (RequiredAlignment > First->getAlignment())
9974       continue;
9975
9976     // Check that both loads are next to each other in memory.
9977     if (!areSlicesNextToEachOther(*First, *Second))
9978       continue;
9979
9980     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9981     --GlobalLSCost.Loads;
9982     // Move to the next pair.
9983     Second = nullptr;
9984   }
9985 }
9986
9987 /// \brief Check the profitability of all involved LoadedSlice.
9988 /// Currently, it is considered profitable if there is exactly two
9989 /// involved slices (1) which are (2) next to each other in memory, and
9990 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9991 ///
9992 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9993 /// the elements themselves.
9994 ///
9995 /// FIXME: When the cost model will be mature enough, we can relax
9996 /// constraints (1) and (2).
9997 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9998                                 const APInt &UsedBits, bool ForCodeSize) {
9999   unsigned NumberOfSlices = LoadedSlices.size();
10000   if (StressLoadSlicing)
10001     return NumberOfSlices > 1;
10002
10003   // Check (1).
10004   if (NumberOfSlices != 2)
10005     return false;
10006
10007   // Check (2).
10008   if (!areUsedBitsDense(UsedBits))
10009     return false;
10010
10011   // Check (3).
10012   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10013   // The original code has one big load.
10014   OrigCost.Loads = 1;
10015   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10016     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10017     // Accumulate the cost of all the slices.
10018     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10019     GlobalSlicingCost += SliceCost;
10020
10021     // Account as cost in the original configuration the gain obtained
10022     // with the current slices.
10023     OrigCost.addSliceGain(LS);
10024   }
10025
10026   // If the target supports paired load, adjust the cost accordingly.
10027   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10028   return OrigCost > GlobalSlicingCost;
10029 }
10030
10031 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10032 /// operations, split it in the various pieces being extracted.
10033 ///
10034 /// This sort of thing is introduced by SROA.
10035 /// This slicing takes care not to insert overlapping loads.
10036 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10037 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10038   if (Level < AfterLegalizeDAG)
10039     return false;
10040
10041   LoadSDNode *LD = cast<LoadSDNode>(N);
10042   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10043       !LD->getValueType(0).isInteger())
10044     return false;
10045
10046   // Keep track of already used bits to detect overlapping values.
10047   // In that case, we will just abort the transformation.
10048   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10049
10050   SmallVector<LoadedSlice, 4> LoadedSlices;
10051
10052   // Check if this load is used as several smaller chunks of bits.
10053   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10054   // of computation for each trunc.
10055   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10056        UI != UIEnd; ++UI) {
10057     // Skip the uses of the chain.
10058     if (UI.getUse().getResNo() != 0)
10059       continue;
10060
10061     SDNode *User = *UI;
10062     unsigned Shift = 0;
10063
10064     // Check if this is a trunc(lshr).
10065     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10066         isa<ConstantSDNode>(User->getOperand(1))) {
10067       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10068       User = *User->use_begin();
10069     }
10070
10071     // At this point, User is a Truncate, iff we encountered, trunc or
10072     // trunc(lshr).
10073     if (User->getOpcode() != ISD::TRUNCATE)
10074       return false;
10075
10076     // The width of the type must be a power of 2 and greater than 8-bits.
10077     // Otherwise the load cannot be represented in LLVM IR.
10078     // Moreover, if we shifted with a non-8-bits multiple, the slice
10079     // will be across several bytes. We do not support that.
10080     unsigned Width = User->getValueSizeInBits(0);
10081     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10082       return 0;
10083
10084     // Build the slice for this chain of computations.
10085     LoadedSlice LS(User, LD, Shift, &DAG);
10086     APInt CurrentUsedBits = LS.getUsedBits();
10087
10088     // Check if this slice overlaps with another.
10089     if ((CurrentUsedBits & UsedBits) != 0)
10090       return false;
10091     // Update the bits used globally.
10092     UsedBits |= CurrentUsedBits;
10093
10094     // Check if the new slice would be legal.
10095     if (!LS.isLegal())
10096       return false;
10097
10098     // Record the slice.
10099     LoadedSlices.push_back(LS);
10100   }
10101
10102   // Abort slicing if it does not seem to be profitable.
10103   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10104     return false;
10105
10106   ++SlicedLoads;
10107
10108   // Rewrite each chain to use an independent load.
10109   // By construction, each chain can be represented by a unique load.
10110
10111   // Prepare the argument for the new token factor for all the slices.
10112   SmallVector<SDValue, 8> ArgChains;
10113   for (SmallVectorImpl<LoadedSlice>::const_iterator
10114            LSIt = LoadedSlices.begin(),
10115            LSItEnd = LoadedSlices.end();
10116        LSIt != LSItEnd; ++LSIt) {
10117     SDValue SliceInst = LSIt->loadSlice();
10118     CombineTo(LSIt->Inst, SliceInst, true);
10119     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10120       SliceInst = SliceInst.getOperand(0);
10121     assert(SliceInst->getOpcode() == ISD::LOAD &&
10122            "It takes more than a zext to get to the loaded slice!!");
10123     ArgChains.push_back(SliceInst.getValue(1));
10124   }
10125
10126   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10127                               ArgChains);
10128   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10129   return true;
10130 }
10131
10132 /// Check to see if V is (and load (ptr), imm), where the load is having
10133 /// specific bytes cleared out.  If so, return the byte size being masked out
10134 /// and the shift amount.
10135 static std::pair<unsigned, unsigned>
10136 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10137   std::pair<unsigned, unsigned> Result(0, 0);
10138
10139   // Check for the structure we're looking for.
10140   if (V->getOpcode() != ISD::AND ||
10141       !isa<ConstantSDNode>(V->getOperand(1)) ||
10142       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10143     return Result;
10144
10145   // Check the chain and pointer.
10146   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10147   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10148
10149   // The store should be chained directly to the load or be an operand of a
10150   // tokenfactor.
10151   if (LD == Chain.getNode())
10152     ; // ok.
10153   else if (Chain->getOpcode() != ISD::TokenFactor)
10154     return Result; // Fail.
10155   else {
10156     bool isOk = false;
10157     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10158       if (Chain->getOperand(i).getNode() == LD) {
10159         isOk = true;
10160         break;
10161       }
10162     if (!isOk) return Result;
10163   }
10164
10165   // This only handles simple types.
10166   if (V.getValueType() != MVT::i16 &&
10167       V.getValueType() != MVT::i32 &&
10168       V.getValueType() != MVT::i64)
10169     return Result;
10170
10171   // Check the constant mask.  Invert it so that the bits being masked out are
10172   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10173   // follow the sign bit for uniformity.
10174   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10175   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10176   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10177   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10178   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10179   if (NotMaskLZ == 64) return Result;  // All zero mask.
10180
10181   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10182   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10183     return Result;
10184
10185   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10186   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10187     NotMaskLZ -= 64-V.getValueSizeInBits();
10188
10189   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10190   switch (MaskedBytes) {
10191   case 1:
10192   case 2:
10193   case 4: break;
10194   default: return Result; // All one mask, or 5-byte mask.
10195   }
10196
10197   // Verify that the first bit starts at a multiple of mask so that the access
10198   // is aligned the same as the access width.
10199   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10200
10201   Result.first = MaskedBytes;
10202   Result.second = NotMaskTZ/8;
10203   return Result;
10204 }
10205
10206
10207 /// Check to see if IVal is something that provides a value as specified by
10208 /// MaskInfo. If so, replace the specified store with a narrower store of
10209 /// truncated IVal.
10210 static SDNode *
10211 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10212                                 SDValue IVal, StoreSDNode *St,
10213                                 DAGCombiner *DC) {
10214   unsigned NumBytes = MaskInfo.first;
10215   unsigned ByteShift = MaskInfo.second;
10216   SelectionDAG &DAG = DC->getDAG();
10217
10218   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10219   // that uses this.  If not, this is not a replacement.
10220   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10221                                   ByteShift*8, (ByteShift+NumBytes)*8);
10222   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10223
10224   // Check that it is legal on the target to do this.  It is legal if the new
10225   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10226   // legalization.
10227   MVT VT = MVT::getIntegerVT(NumBytes*8);
10228   if (!DC->isTypeLegal(VT))
10229     return nullptr;
10230
10231   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10232   // shifted by ByteShift and truncated down to NumBytes.
10233   if (ByteShift) {
10234     SDLoc DL(IVal);
10235     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10236                        DAG.getConstant(ByteShift*8, DL,
10237                                     DC->getShiftAmountTy(IVal.getValueType())));
10238   }
10239
10240   // Figure out the offset for the store and the alignment of the access.
10241   unsigned StOffset;
10242   unsigned NewAlign = St->getAlignment();
10243
10244   if (DAG.getTargetLoweringInfo().isLittleEndian())
10245     StOffset = ByteShift;
10246   else
10247     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10248
10249   SDValue Ptr = St->getBasePtr();
10250   if (StOffset) {
10251     SDLoc DL(IVal);
10252     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10253                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10254     NewAlign = MinAlign(NewAlign, StOffset);
10255   }
10256
10257   // Truncate down to the new size.
10258   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10259
10260   ++OpsNarrowed;
10261   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10262                       St->getPointerInfo().getWithOffset(StOffset),
10263                       false, false, NewAlign).getNode();
10264 }
10265
10266
10267 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10268 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10269 /// narrowing the load and store if it would end up being a win for performance
10270 /// or code size.
10271 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10272   StoreSDNode *ST  = cast<StoreSDNode>(N);
10273   if (ST->isVolatile())
10274     return SDValue();
10275
10276   SDValue Chain = ST->getChain();
10277   SDValue Value = ST->getValue();
10278   SDValue Ptr   = ST->getBasePtr();
10279   EVT VT = Value.getValueType();
10280
10281   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10282     return SDValue();
10283
10284   unsigned Opc = Value.getOpcode();
10285
10286   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10287   // is a byte mask indicating a consecutive number of bytes, check to see if
10288   // Y is known to provide just those bytes.  If so, we try to replace the
10289   // load + replace + store sequence with a single (narrower) store, which makes
10290   // the load dead.
10291   if (Opc == ISD::OR) {
10292     std::pair<unsigned, unsigned> MaskedLoad;
10293     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10294     if (MaskedLoad.first)
10295       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10296                                                   Value.getOperand(1), ST,this))
10297         return SDValue(NewST, 0);
10298
10299     // Or is commutative, so try swapping X and Y.
10300     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10301     if (MaskedLoad.first)
10302       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10303                                                   Value.getOperand(0), ST,this))
10304         return SDValue(NewST, 0);
10305   }
10306
10307   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10308       Value.getOperand(1).getOpcode() != ISD::Constant)
10309     return SDValue();
10310
10311   SDValue N0 = Value.getOperand(0);
10312   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10313       Chain == SDValue(N0.getNode(), 1)) {
10314     LoadSDNode *LD = cast<LoadSDNode>(N0);
10315     if (LD->getBasePtr() != Ptr ||
10316         LD->getPointerInfo().getAddrSpace() !=
10317         ST->getPointerInfo().getAddrSpace())
10318       return SDValue();
10319
10320     // Find the type to narrow it the load / op / store to.
10321     SDValue N1 = Value.getOperand(1);
10322     unsigned BitWidth = N1.getValueSizeInBits();
10323     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10324     if (Opc == ISD::AND)
10325       Imm ^= APInt::getAllOnesValue(BitWidth);
10326     if (Imm == 0 || Imm.isAllOnesValue())
10327       return SDValue();
10328     unsigned ShAmt = Imm.countTrailingZeros();
10329     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10330     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10331     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10332     // The narrowing should be profitable, the load/store operation should be
10333     // legal (or custom) and the store size should be equal to the NewVT width.
10334     while (NewBW < BitWidth &&
10335            (NewVT.getStoreSizeInBits() != NewBW ||
10336             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10337             !TLI.isNarrowingProfitable(VT, NewVT))) {
10338       NewBW = NextPowerOf2(NewBW);
10339       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10340     }
10341     if (NewBW >= BitWidth)
10342       return SDValue();
10343
10344     // If the lsb changed does not start at the type bitwidth boundary,
10345     // start at the previous one.
10346     if (ShAmt % NewBW)
10347       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10348     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10349                                    std::min(BitWidth, ShAmt + NewBW));
10350     if ((Imm & Mask) == Imm) {
10351       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10352       if (Opc == ISD::AND)
10353         NewImm ^= APInt::getAllOnesValue(NewBW);
10354       uint64_t PtrOff = ShAmt / 8;
10355       // For big endian targets, we need to adjust the offset to the pointer to
10356       // load the correct bytes.
10357       if (TLI.isBigEndian())
10358         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10359
10360       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10361       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10362       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10363         return SDValue();
10364
10365       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10366                                    Ptr.getValueType(), Ptr,
10367                                    DAG.getConstant(PtrOff, SDLoc(LD),
10368                                                    Ptr.getValueType()));
10369       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10370                                   LD->getChain(), NewPtr,
10371                                   LD->getPointerInfo().getWithOffset(PtrOff),
10372                                   LD->isVolatile(), LD->isNonTemporal(),
10373                                   LD->isInvariant(), NewAlign,
10374                                   LD->getAAInfo());
10375       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10376                                    DAG.getConstant(NewImm, SDLoc(Value),
10377                                                    NewVT));
10378       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10379                                    NewVal, NewPtr,
10380                                    ST->getPointerInfo().getWithOffset(PtrOff),
10381                                    false, false, NewAlign);
10382
10383       AddToWorklist(NewPtr.getNode());
10384       AddToWorklist(NewLD.getNode());
10385       AddToWorklist(NewVal.getNode());
10386       WorklistRemover DeadNodes(*this);
10387       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10388       ++OpsNarrowed;
10389       return NewST;
10390     }
10391   }
10392
10393   return SDValue();
10394 }
10395
10396 /// For a given floating point load / store pair, if the load value isn't used
10397 /// by any other operations, then consider transforming the pair to integer
10398 /// load / store operations if the target deems the transformation profitable.
10399 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10400   StoreSDNode *ST  = cast<StoreSDNode>(N);
10401   SDValue Chain = ST->getChain();
10402   SDValue Value = ST->getValue();
10403   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10404       Value.hasOneUse() &&
10405       Chain == SDValue(Value.getNode(), 1)) {
10406     LoadSDNode *LD = cast<LoadSDNode>(Value);
10407     EVT VT = LD->getMemoryVT();
10408     if (!VT.isFloatingPoint() ||
10409         VT != ST->getMemoryVT() ||
10410         LD->isNonTemporal() ||
10411         ST->isNonTemporal() ||
10412         LD->getPointerInfo().getAddrSpace() != 0 ||
10413         ST->getPointerInfo().getAddrSpace() != 0)
10414       return SDValue();
10415
10416     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10417     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10418         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10419         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10420         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10421       return SDValue();
10422
10423     unsigned LDAlign = LD->getAlignment();
10424     unsigned STAlign = ST->getAlignment();
10425     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10426     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10427     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10428       return SDValue();
10429
10430     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10431                                 LD->getChain(), LD->getBasePtr(),
10432                                 LD->getPointerInfo(),
10433                                 false, false, false, LDAlign);
10434
10435     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10436                                  NewLD, ST->getBasePtr(),
10437                                  ST->getPointerInfo(),
10438                                  false, false, STAlign);
10439
10440     AddToWorklist(NewLD.getNode());
10441     AddToWorklist(NewST.getNode());
10442     WorklistRemover DeadNodes(*this);
10443     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10444     ++LdStFP2Int;
10445     return NewST;
10446   }
10447
10448   return SDValue();
10449 }
10450
10451 namespace {
10452 /// Helper struct to parse and store a memory address as base + index + offset.
10453 /// We ignore sign extensions when it is safe to do so.
10454 /// The following two expressions are not equivalent. To differentiate we need
10455 /// to store whether there was a sign extension involved in the index
10456 /// computation.
10457 ///  (load (i64 add (i64 copyfromreg %c)
10458 ///                 (i64 signextend (add (i8 load %index)
10459 ///                                      (i8 1))))
10460 /// vs
10461 ///
10462 /// (load (i64 add (i64 copyfromreg %c)
10463 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10464 ///                                         (i32 1)))))
10465 struct BaseIndexOffset {
10466   SDValue Base;
10467   SDValue Index;
10468   int64_t Offset;
10469   bool IsIndexSignExt;
10470
10471   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10472
10473   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10474                   bool IsIndexSignExt) :
10475     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10476
10477   bool equalBaseIndex(const BaseIndexOffset &Other) {
10478     return Other.Base == Base && Other.Index == Index &&
10479       Other.IsIndexSignExt == IsIndexSignExt;
10480   }
10481
10482   /// Parses tree in Ptr for base, index, offset addresses.
10483   static BaseIndexOffset match(SDValue Ptr) {
10484     bool IsIndexSignExt = false;
10485
10486     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10487     // instruction, then it could be just the BASE or everything else we don't
10488     // know how to handle. Just use Ptr as BASE and give up.
10489     if (Ptr->getOpcode() != ISD::ADD)
10490       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10491
10492     // We know that we have at least an ADD instruction. Try to pattern match
10493     // the simple case of BASE + OFFSET.
10494     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10495       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10496       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10497                               IsIndexSignExt);
10498     }
10499
10500     // Inside a loop the current BASE pointer is calculated using an ADD and a
10501     // MUL instruction. In this case Ptr is the actual BASE pointer.
10502     // (i64 add (i64 %array_ptr)
10503     //          (i64 mul (i64 %induction_var)
10504     //                   (i64 %element_size)))
10505     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10506       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10507
10508     // Look at Base + Index + Offset cases.
10509     SDValue Base = Ptr->getOperand(0);
10510     SDValue IndexOffset = Ptr->getOperand(1);
10511
10512     // Skip signextends.
10513     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10514       IndexOffset = IndexOffset->getOperand(0);
10515       IsIndexSignExt = true;
10516     }
10517
10518     // Either the case of Base + Index (no offset) or something else.
10519     if (IndexOffset->getOpcode() != ISD::ADD)
10520       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10521
10522     // Now we have the case of Base + Index + offset.
10523     SDValue Index = IndexOffset->getOperand(0);
10524     SDValue Offset = IndexOffset->getOperand(1);
10525
10526     if (!isa<ConstantSDNode>(Offset))
10527       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10528
10529     // Ignore signextends.
10530     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10531       Index = Index->getOperand(0);
10532       IsIndexSignExt = true;
10533     } else IsIndexSignExt = false;
10534
10535     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10536     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10537   }
10538 };
10539 } // namespace
10540
10541 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10542                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10543                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10544   // Make sure we have something to merge.
10545   if (NumElem < 2)
10546     return false;
10547
10548   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10549   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10550   unsigned LatestNodeUsed = 0;
10551
10552   for (unsigned i=0; i < NumElem; ++i) {
10553     // Find a chain for the new wide-store operand. Notice that some
10554     // of the store nodes that we found may not be selected for inclusion
10555     // in the wide store. The chain we use needs to be the chain of the
10556     // latest store node which is *used* and replaced by the wide store.
10557     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10558       LatestNodeUsed = i;
10559   }
10560
10561   // The latest Node in the DAG.
10562   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10563   SDLoc DL(StoreNodes[0].MemNode);
10564
10565   SDValue StoredVal;
10566   if (UseVector) {
10567     // Find a legal type for the vector store.
10568     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10569     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10570     if (IsConstantSrc) {
10571       // A vector store with a constant source implies that the constant is
10572       // zero; we only handle merging stores of constant zeros because the zero
10573       // can be materialized without a load.
10574       // It may be beneficial to loosen this restriction to allow non-zero
10575       // store merging.
10576       StoredVal = DAG.getConstant(0, DL, Ty);
10577     } else {
10578       SmallVector<SDValue, 8> Ops;
10579       for (unsigned i = 0; i < NumElem ; ++i) {
10580         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10581         SDValue Val = St->getValue();
10582         // All of the operands of a BUILD_VECTOR must have the same type.
10583         if (Val.getValueType() != MemVT)
10584           return false;
10585         Ops.push_back(Val);
10586       }
10587
10588       // Build the extracted vector elements back into a vector.
10589       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10590     }
10591   } else {
10592     // We should always use a vector store when merging extracted vector
10593     // elements, so this path implies a store of constants.
10594     assert(IsConstantSrc && "Merged vector elements should use vector store");
10595
10596     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10597     APInt StoreInt(StoreBW, 0);
10598
10599     // Construct a single integer constant which is made of the smaller
10600     // constant inputs.
10601     bool IsLE = TLI.isLittleEndian();
10602     for (unsigned i = 0; i < NumElem ; ++i) {
10603       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10604       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10605       SDValue Val = St->getValue();
10606       StoreInt <<= ElementSizeBytes*8;
10607       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10608         StoreInt |= C->getAPIntValue().zext(StoreBW);
10609       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10610         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10611       } else {
10612         llvm_unreachable("Invalid constant element type");
10613       }
10614     }
10615
10616     // Create the new Load and Store operations.
10617     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10618     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10619   }
10620
10621   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10622                                   FirstInChain->getBasePtr(),
10623                                   FirstInChain->getPointerInfo(),
10624                                   false, false,
10625                                   FirstInChain->getAlignment());
10626
10627   // Replace the last store with the new store
10628   CombineTo(LatestOp, NewStore);
10629   // Erase all other stores.
10630   for (unsigned i = 0; i < NumElem ; ++i) {
10631     if (StoreNodes[i].MemNode == LatestOp)
10632       continue;
10633     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10634     // ReplaceAllUsesWith will replace all uses that existed when it was
10635     // called, but graph optimizations may cause new ones to appear. For
10636     // example, the case in pr14333 looks like
10637     //
10638     //  St's chain -> St -> another store -> X
10639     //
10640     // And the only difference from St to the other store is the chain.
10641     // When we change it's chain to be St's chain they become identical,
10642     // get CSEed and the net result is that X is now a use of St.
10643     // Since we know that St is redundant, just iterate.
10644     while (!St->use_empty())
10645       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10646     deleteAndRecombine(St);
10647   }
10648
10649   return true;
10650 }
10651
10652 static bool allowableAlignment(const SelectionDAG &DAG,
10653                                const TargetLowering &TLI, EVT EVTTy,
10654                                unsigned AS, unsigned Align) {
10655   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10656     return true;
10657
10658   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10659   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10660   return (Align >= ABIAlignment);
10661 }
10662
10663 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10664   if (OptLevel == CodeGenOpt::None)
10665     return false;
10666
10667   EVT MemVT = St->getMemoryVT();
10668   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10669   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10670       Attribute::NoImplicitFloat);
10671
10672   // This function cannot currently deal with non-byte-sized memory sizes.
10673   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10674     return false;
10675
10676   // Don't merge vectors into wider inputs.
10677   if (MemVT.isVector() || !MemVT.isSimple())
10678     return false;
10679
10680   // Perform an early exit check. Do not bother looking at stored values that
10681   // are not constants, loads, or extracted vector elements.
10682   SDValue StoredVal = St->getValue();
10683   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10684   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10685                        isa<ConstantFPSDNode>(StoredVal);
10686   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10687
10688   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10689     return false;
10690
10691   // Only look at ends of store sequences.
10692   SDValue Chain = SDValue(St, 0);
10693   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10694     return false;
10695
10696   // This holds the base pointer, index, and the offset in bytes from the base
10697   // pointer.
10698   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10699
10700   // We must have a base and an offset.
10701   if (!BasePtr.Base.getNode())
10702     return false;
10703
10704   // Do not handle stores to undef base pointers.
10705   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10706     return false;
10707
10708   // Save the LoadSDNodes that we find in the chain.
10709   // We need to make sure that these nodes do not interfere with
10710   // any of the store nodes.
10711   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10712
10713   // Save the StoreSDNodes that we find in the chain.
10714   SmallVector<MemOpLink, 8> StoreNodes;
10715
10716   // Walk up the chain and look for nodes with offsets from the same
10717   // base pointer. Stop when reaching an instruction with a different kind
10718   // or instruction which has a different base pointer.
10719   unsigned Seq = 0;
10720   StoreSDNode *Index = St;
10721   while (Index) {
10722     // If the chain has more than one use, then we can't reorder the mem ops.
10723     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10724       break;
10725
10726     // Find the base pointer and offset for this memory node.
10727     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10728
10729     // Check that the base pointer is the same as the original one.
10730     if (!Ptr.equalBaseIndex(BasePtr))
10731       break;
10732
10733     // The memory operands must not be volatile.
10734     if (Index->isVolatile() || Index->isIndexed())
10735       break;
10736
10737     // No truncation.
10738     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10739       if (St->isTruncatingStore())
10740         break;
10741
10742     // The stored memory type must be the same.
10743     if (Index->getMemoryVT() != MemVT)
10744       break;
10745
10746     // We found a potential memory operand to merge.
10747     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10748
10749     // Find the next memory operand in the chain. If the next operand in the
10750     // chain is a store then move up and continue the scan with the next
10751     // memory operand. If the next operand is a load save it and use alias
10752     // information to check if it interferes with anything.
10753     SDNode *NextInChain = Index->getChain().getNode();
10754     while (1) {
10755       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10756         // We found a store node. Use it for the next iteration.
10757         Index = STn;
10758         break;
10759       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10760         if (Ldn->isVolatile()) {
10761           Index = nullptr;
10762           break;
10763         }
10764
10765         // Save the load node for later. Continue the scan.
10766         AliasLoadNodes.push_back(Ldn);
10767         NextInChain = Ldn->getChain().getNode();
10768         continue;
10769       } else {
10770         Index = nullptr;
10771         break;
10772       }
10773     }
10774   }
10775
10776   // Check if there is anything to merge.
10777   if (StoreNodes.size() < 2)
10778     return false;
10779
10780   // Sort the memory operands according to their distance from the base pointer.
10781   std::sort(StoreNodes.begin(), StoreNodes.end(),
10782             [](MemOpLink LHS, MemOpLink RHS) {
10783     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10784            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10785             LHS.SequenceNum > RHS.SequenceNum);
10786   });
10787
10788   // Scan the memory operations on the chain and find the first non-consecutive
10789   // store memory address.
10790   unsigned LastConsecutiveStore = 0;
10791   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10792   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10793
10794     // Check that the addresses are consecutive starting from the second
10795     // element in the list of stores.
10796     if (i > 0) {
10797       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10798       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10799         break;
10800     }
10801
10802     bool Alias = false;
10803     // Check if this store interferes with any of the loads that we found.
10804     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10805       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10806         Alias = true;
10807         break;
10808       }
10809     // We found a load that alias with this store. Stop the sequence.
10810     if (Alias)
10811       break;
10812
10813     // Mark this node as useful.
10814     LastConsecutiveStore = i;
10815   }
10816
10817   // The node with the lowest store address.
10818   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10819   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10820   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10821
10822   // Store the constants into memory as one consecutive store.
10823   if (IsConstantSrc) {
10824     unsigned LastLegalType = 0;
10825     unsigned LastLegalVectorType = 0;
10826     bool NonZero = false;
10827     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10828       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10829       SDValue StoredVal = St->getValue();
10830
10831       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10832         NonZero |= !C->isNullValue();
10833       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10834         NonZero |= !C->getConstantFPValue()->isNullValue();
10835       } else {
10836         // Non-constant.
10837         break;
10838       }
10839
10840       // Find a legal type for the constant store.
10841       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10842       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10843       if (TLI.isTypeLegal(StoreTy) &&
10844           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10845                              FirstStoreAlign)) {
10846         LastLegalType = i+1;
10847       // Or check whether a truncstore is legal.
10848       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10849                  TargetLowering::TypePromoteInteger) {
10850         EVT LegalizedStoredValueTy =
10851           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10852         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10853             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10854                                FirstStoreAlign)) {
10855           LastLegalType = i + 1;
10856         }
10857       }
10858
10859       // Find a legal type for the vector store.
10860       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10861       if (TLI.isTypeLegal(Ty) &&
10862           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10863         LastLegalVectorType = i + 1;
10864       }
10865     }
10866
10867     // We only use vectors if the constant is known to be zero and the
10868     // function is not marked with the noimplicitfloat attribute.
10869     if (NonZero || NoVectors)
10870       LastLegalVectorType = 0;
10871
10872     // Check if we found a legal integer type to store.
10873     if (LastLegalType == 0 && LastLegalVectorType == 0)
10874       return false;
10875
10876     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10877     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10878
10879     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10880                                            true, UseVector);
10881   }
10882
10883   // When extracting multiple vector elements, try to store them
10884   // in one vector store rather than a sequence of scalar stores.
10885   if (IsExtractVecEltSrc) {
10886     unsigned NumElem = 0;
10887     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10888       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10889       SDValue StoredVal = St->getValue();
10890       // This restriction could be loosened.
10891       // Bail out if any stored values are not elements extracted from a vector.
10892       // It should be possible to handle mixed sources, but load sources need
10893       // more careful handling (see the block of code below that handles
10894       // consecutive loads).
10895       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10896         return false;
10897
10898       // Find a legal type for the vector store.
10899       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10900       if (TLI.isTypeLegal(Ty) &&
10901           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10902         NumElem = i + 1;
10903     }
10904
10905     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10906                                            false, true);
10907   }
10908
10909   // Below we handle the case of multiple consecutive stores that
10910   // come from multiple consecutive loads. We merge them into a single
10911   // wide load and a single wide store.
10912
10913   // Look for load nodes which are used by the stored values.
10914   SmallVector<MemOpLink, 8> LoadNodes;
10915
10916   // Find acceptable loads. Loads need to have the same chain (token factor),
10917   // must not be zext, volatile, indexed, and they must be consecutive.
10918   BaseIndexOffset LdBasePtr;
10919   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10920     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10921     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10922     if (!Ld) break;
10923
10924     // Loads must only have one use.
10925     if (!Ld->hasNUsesOfValue(1, 0))
10926       break;
10927
10928     // The memory operands must not be volatile.
10929     if (Ld->isVolatile() || Ld->isIndexed())
10930       break;
10931
10932     // We do not accept ext loads.
10933     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10934       break;
10935
10936     // The stored memory type must be the same.
10937     if (Ld->getMemoryVT() != MemVT)
10938       break;
10939
10940     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10941     // If this is not the first ptr that we check.
10942     if (LdBasePtr.Base.getNode()) {
10943       // The base ptr must be the same.
10944       if (!LdPtr.equalBaseIndex(LdBasePtr))
10945         break;
10946     } else {
10947       // Check that all other base pointers are the same as this one.
10948       LdBasePtr = LdPtr;
10949     }
10950
10951     // We found a potential memory operand to merge.
10952     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10953   }
10954
10955   if (LoadNodes.size() < 2)
10956     return false;
10957
10958   // If we have load/store pair instructions and we only have two values,
10959   // don't bother.
10960   unsigned RequiredAlignment;
10961   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10962       St->getAlignment() >= RequiredAlignment)
10963     return false;
10964
10965   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10966   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10967   unsigned FirstLoadAlign = FirstLoad->getAlignment();
10968
10969   // Scan the memory operations on the chain and find the first non-consecutive
10970   // load memory address. These variables hold the index in the store node
10971   // array.
10972   unsigned LastConsecutiveLoad = 0;
10973   // This variable refers to the size and not index in the array.
10974   unsigned LastLegalVectorType = 0;
10975   unsigned LastLegalIntegerType = 0;
10976   StartAddress = LoadNodes[0].OffsetFromBase;
10977   SDValue FirstChain = FirstLoad->getChain();
10978   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10979     // All loads much share the same chain.
10980     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10981       break;
10982
10983     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10984     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10985       break;
10986     LastConsecutiveLoad = i;
10987
10988     // Find a legal type for the vector store.
10989     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10990     if (TLI.isTypeLegal(StoreTy) &&
10991         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10992         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10993       LastLegalVectorType = i + 1;
10994     }
10995
10996     // Find a legal type for the integer store.
10997     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10998     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10999     if (TLI.isTypeLegal(StoreTy) &&
11000         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11001         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11002       LastLegalIntegerType = i + 1;
11003     // Or check whether a truncstore and extload is legal.
11004     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11005              TargetLowering::TypePromoteInteger) {
11006       EVT LegalizedStoredValueTy =
11007         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11008       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11009           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11010           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11011           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11012           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11013                              FirstStoreAlign) &&
11014           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11015                              FirstLoadAlign))
11016         LastLegalIntegerType = i+1;
11017     }
11018   }
11019
11020   // Only use vector types if the vector type is larger than the integer type.
11021   // If they are the same, use integers.
11022   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11023   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11024
11025   // We add +1 here because the LastXXX variables refer to location while
11026   // the NumElem refers to array/index size.
11027   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11028   NumElem = std::min(LastLegalType, NumElem);
11029
11030   if (NumElem < 2)
11031     return false;
11032
11033   // The latest Node in the DAG.
11034   unsigned LatestNodeUsed = 0;
11035   for (unsigned i=1; i<NumElem; ++i) {
11036     // Find a chain for the new wide-store operand. Notice that some
11037     // of the store nodes that we found may not be selected for inclusion
11038     // in the wide store. The chain we use needs to be the chain of the
11039     // latest store node which is *used* and replaced by the wide store.
11040     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11041       LatestNodeUsed = i;
11042   }
11043
11044   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11045
11046   // Find if it is better to use vectors or integers to load and store
11047   // to memory.
11048   EVT JointMemOpVT;
11049   if (UseVectorTy) {
11050     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11051   } else {
11052     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11053     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11054   }
11055
11056   SDLoc LoadDL(LoadNodes[0].MemNode);
11057   SDLoc StoreDL(StoreNodes[0].MemNode);
11058
11059   SDValue NewLoad = DAG.getLoad(
11060       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11061       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11062
11063   SDValue NewStore = DAG.getStore(
11064       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11065       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11066
11067   // Replace one of the loads with the new load.
11068   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11069   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11070                                 SDValue(NewLoad.getNode(), 1));
11071
11072   // Remove the rest of the load chains.
11073   for (unsigned i = 1; i < NumElem ; ++i) {
11074     // Replace all chain users of the old load nodes with the chain of the new
11075     // load node.
11076     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11077     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11078   }
11079
11080   // Replace the last store with the new store.
11081   CombineTo(LatestOp, NewStore);
11082   // Erase all other stores.
11083   for (unsigned i = 0; i < NumElem ; ++i) {
11084     // Remove all Store nodes.
11085     if (StoreNodes[i].MemNode == LatestOp)
11086       continue;
11087     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11088     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11089     deleteAndRecombine(St);
11090   }
11091
11092   return true;
11093 }
11094
11095 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11096   StoreSDNode *ST  = cast<StoreSDNode>(N);
11097   SDValue Chain = ST->getChain();
11098   SDValue Value = ST->getValue();
11099   SDValue Ptr   = ST->getBasePtr();
11100
11101   // If this is a store of a bit convert, store the input value if the
11102   // resultant store does not need a higher alignment than the original.
11103   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11104       ST->isUnindexed()) {
11105     unsigned OrigAlign = ST->getAlignment();
11106     EVT SVT = Value.getOperand(0).getValueType();
11107     unsigned Align = TLI.getDataLayout()->
11108       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11109     if (Align <= OrigAlign &&
11110         ((!LegalOperations && !ST->isVolatile()) ||
11111          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11112       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11113                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11114                           ST->isNonTemporal(), OrigAlign,
11115                           ST->getAAInfo());
11116   }
11117
11118   // Turn 'store undef, Ptr' -> nothing.
11119   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11120     return Chain;
11121
11122   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11123   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11124     // NOTE: If the original store is volatile, this transform must not increase
11125     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11126     // processor operation but an i64 (which is not legal) requires two.  So the
11127     // transform should not be done in this case.
11128     if (Value.getOpcode() != ISD::TargetConstantFP) {
11129       SDValue Tmp;
11130       switch (CFP->getSimpleValueType(0).SimpleTy) {
11131       default: llvm_unreachable("Unknown FP type");
11132       case MVT::f16:    // We don't do this for these yet.
11133       case MVT::f80:
11134       case MVT::f128:
11135       case MVT::ppcf128:
11136         break;
11137       case MVT::f32:
11138         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11139             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11140           ;
11141           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11142                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11143                               MVT::i32);
11144           return DAG.getStore(Chain, SDLoc(N), Tmp,
11145                               Ptr, ST->getMemOperand());
11146         }
11147         break;
11148       case MVT::f64:
11149         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11150              !ST->isVolatile()) ||
11151             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11152           ;
11153           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11154                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11155           return DAG.getStore(Chain, SDLoc(N), Tmp,
11156                               Ptr, ST->getMemOperand());
11157         }
11158
11159         if (!ST->isVolatile() &&
11160             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11161           // Many FP stores are not made apparent until after legalize, e.g. for
11162           // argument passing.  Since this is so common, custom legalize the
11163           // 64-bit integer store into two 32-bit stores.
11164           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11165           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11166           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11167           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11168
11169           unsigned Alignment = ST->getAlignment();
11170           bool isVolatile = ST->isVolatile();
11171           bool isNonTemporal = ST->isNonTemporal();
11172           AAMDNodes AAInfo = ST->getAAInfo();
11173
11174           SDLoc DL(N);
11175
11176           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11177                                      Ptr, ST->getPointerInfo(),
11178                                      isVolatile, isNonTemporal,
11179                                      ST->getAlignment(), AAInfo);
11180           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11181                             DAG.getConstant(4, DL, Ptr.getValueType()));
11182           Alignment = MinAlign(Alignment, 4U);
11183           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11184                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11185                                      isVolatile, isNonTemporal,
11186                                      Alignment, AAInfo);
11187           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11188                              St0, St1);
11189         }
11190
11191         break;
11192       }
11193     }
11194   }
11195
11196   // Try to infer better alignment information than the store already has.
11197   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11198     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11199       if (Align > ST->getAlignment()) {
11200         SDValue NewStore =
11201                DAG.getTruncStore(Chain, SDLoc(N), Value,
11202                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11203                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11204                                  ST->getAAInfo());
11205         if (NewStore.getNode() != N)
11206           return CombineTo(ST, NewStore, true);
11207       }
11208     }
11209   }
11210
11211   // Try transforming a pair floating point load / store ops to integer
11212   // load / store ops.
11213   SDValue NewST = TransformFPLoadStorePair(N);
11214   if (NewST.getNode())
11215     return NewST;
11216
11217   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11218                                                   : DAG.getSubtarget().useAA();
11219 #ifndef NDEBUG
11220   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11221       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11222     UseAA = false;
11223 #endif
11224   if (UseAA && ST->isUnindexed()) {
11225     // Walk up chain skipping non-aliasing memory nodes.
11226     SDValue BetterChain = FindBetterChain(N, Chain);
11227
11228     // If there is a better chain.
11229     if (Chain != BetterChain) {
11230       SDValue ReplStore;
11231
11232       // Replace the chain to avoid dependency.
11233       if (ST->isTruncatingStore()) {
11234         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11235                                       ST->getMemoryVT(), ST->getMemOperand());
11236       } else {
11237         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11238                                  ST->getMemOperand());
11239       }
11240
11241       // Create token to keep both nodes around.
11242       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11243                                   MVT::Other, Chain, ReplStore);
11244
11245       // Make sure the new and old chains are cleaned up.
11246       AddToWorklist(Token.getNode());
11247
11248       // Don't add users to work list.
11249       return CombineTo(N, Token, false);
11250     }
11251   }
11252
11253   // Try transforming N to an indexed store.
11254   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11255     return SDValue(N, 0);
11256
11257   // FIXME: is there such a thing as a truncating indexed store?
11258   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11259       Value.getValueType().isInteger()) {
11260     // See if we can simplify the input to this truncstore with knowledge that
11261     // only the low bits are being used.  For example:
11262     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11263     SDValue Shorter =
11264       GetDemandedBits(Value,
11265                       APInt::getLowBitsSet(
11266                         Value.getValueType().getScalarType().getSizeInBits(),
11267                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11268     AddToWorklist(Value.getNode());
11269     if (Shorter.getNode())
11270       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11271                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11272
11273     // Otherwise, see if we can simplify the operation with
11274     // SimplifyDemandedBits, which only works if the value has a single use.
11275     if (SimplifyDemandedBits(Value,
11276                         APInt::getLowBitsSet(
11277                           Value.getValueType().getScalarType().getSizeInBits(),
11278                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11279       return SDValue(N, 0);
11280   }
11281
11282   // If this is a load followed by a store to the same location, then the store
11283   // is dead/noop.
11284   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11285     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11286         ST->isUnindexed() && !ST->isVolatile() &&
11287         // There can't be any side effects between the load and store, such as
11288         // a call or store.
11289         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11290       // The store is dead, remove it.
11291       return Chain;
11292     }
11293   }
11294
11295   // If this is a store followed by a store with the same value to the same
11296   // location, then the store is dead/noop.
11297   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11298     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11299         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11300         ST1->isUnindexed() && !ST1->isVolatile()) {
11301       // The store is dead, remove it.
11302       return Chain;
11303     }
11304   }
11305
11306   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11307   // truncating store.  We can do this even if this is already a truncstore.
11308   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11309       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11310       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11311                             ST->getMemoryVT())) {
11312     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11313                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11314   }
11315
11316   // Only perform this optimization before the types are legal, because we
11317   // don't want to perform this optimization on every DAGCombine invocation.
11318   if (!LegalTypes) {
11319     bool EverChanged = false;
11320
11321     do {
11322       // There can be multiple store sequences on the same chain.
11323       // Keep trying to merge store sequences until we are unable to do so
11324       // or until we merge the last store on the chain.
11325       bool Changed = MergeConsecutiveStores(ST);
11326       EverChanged |= Changed;
11327       if (!Changed) break;
11328     } while (ST->getOpcode() != ISD::DELETED_NODE);
11329
11330     if (EverChanged)
11331       return SDValue(N, 0);
11332   }
11333
11334   return ReduceLoadOpStoreWidth(N);
11335 }
11336
11337 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11338   SDValue InVec = N->getOperand(0);
11339   SDValue InVal = N->getOperand(1);
11340   SDValue EltNo = N->getOperand(2);
11341   SDLoc dl(N);
11342
11343   // If the inserted element is an UNDEF, just use the input vector.
11344   if (InVal.getOpcode() == ISD::UNDEF)
11345     return InVec;
11346
11347   EVT VT = InVec.getValueType();
11348
11349   // If we can't generate a legal BUILD_VECTOR, exit
11350   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11351     return SDValue();
11352
11353   // Check that we know which element is being inserted
11354   if (!isa<ConstantSDNode>(EltNo))
11355     return SDValue();
11356   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11357
11358   // Canonicalize insert_vector_elt dag nodes.
11359   // Example:
11360   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11361   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11362   //
11363   // Do this only if the child insert_vector node has one use; also
11364   // do this only if indices are both constants and Idx1 < Idx0.
11365   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11366       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11367     unsigned OtherElt =
11368       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11369     if (Elt < OtherElt) {
11370       // Swap nodes.
11371       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11372                                   InVec.getOperand(0), InVal, EltNo);
11373       AddToWorklist(NewOp.getNode());
11374       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11375                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11376     }
11377   }
11378
11379   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11380   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11381   // vector elements.
11382   SmallVector<SDValue, 8> Ops;
11383   // Do not combine these two vectors if the output vector will not replace
11384   // the input vector.
11385   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11386     Ops.append(InVec.getNode()->op_begin(),
11387                InVec.getNode()->op_end());
11388   } else if (InVec.getOpcode() == ISD::UNDEF) {
11389     unsigned NElts = VT.getVectorNumElements();
11390     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11391   } else {
11392     return SDValue();
11393   }
11394
11395   // Insert the element
11396   if (Elt < Ops.size()) {
11397     // All the operands of BUILD_VECTOR must have the same type;
11398     // we enforce that here.
11399     EVT OpVT = Ops[0].getValueType();
11400     if (InVal.getValueType() != OpVT)
11401       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11402                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11403                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11404     Ops[Elt] = InVal;
11405   }
11406
11407   // Return the new vector
11408   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11409 }
11410
11411 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11412     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11413   EVT ResultVT = EVE->getValueType(0);
11414   EVT VecEltVT = InVecVT.getVectorElementType();
11415   unsigned Align = OriginalLoad->getAlignment();
11416   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11417       VecEltVT.getTypeForEVT(*DAG.getContext()));
11418
11419   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11420     return SDValue();
11421
11422   Align = NewAlign;
11423
11424   SDValue NewPtr = OriginalLoad->getBasePtr();
11425   SDValue Offset;
11426   EVT PtrType = NewPtr.getValueType();
11427   MachinePointerInfo MPI;
11428   SDLoc DL(EVE);
11429   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11430     int Elt = ConstEltNo->getZExtValue();
11431     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11432     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11433     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11434   } else {
11435     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11436     Offset = DAG.getNode(
11437         ISD::MUL, DL, PtrType, Offset,
11438         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11439     MPI = OriginalLoad->getPointerInfo();
11440   }
11441   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11442
11443   // The replacement we need to do here is a little tricky: we need to
11444   // replace an extractelement of a load with a load.
11445   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11446   // Note that this replacement assumes that the extractvalue is the only
11447   // use of the load; that's okay because we don't want to perform this
11448   // transformation in other cases anyway.
11449   SDValue Load;
11450   SDValue Chain;
11451   if (ResultVT.bitsGT(VecEltVT)) {
11452     // If the result type of vextract is wider than the load, then issue an
11453     // extending load instead.
11454     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11455                                                   VecEltVT)
11456                                    ? ISD::ZEXTLOAD
11457                                    : ISD::EXTLOAD;
11458     Load = DAG.getExtLoad(
11459         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11460         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11461         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11462     Chain = Load.getValue(1);
11463   } else {
11464     Load = DAG.getLoad(
11465         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11466         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11467         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11468     Chain = Load.getValue(1);
11469     if (ResultVT.bitsLT(VecEltVT))
11470       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11471     else
11472       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11473   }
11474   WorklistRemover DeadNodes(*this);
11475   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11476   SDValue To[] = { Load, Chain };
11477   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11478   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11479   // worklist explicitly as well.
11480   AddToWorklist(Load.getNode());
11481   AddUsersToWorklist(Load.getNode()); // Add users too
11482   // Make sure to revisit this node to clean it up; it will usually be dead.
11483   AddToWorklist(EVE);
11484   ++OpsNarrowed;
11485   return SDValue(EVE, 0);
11486 }
11487
11488 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11489   // (vextract (scalar_to_vector val, 0) -> val
11490   SDValue InVec = N->getOperand(0);
11491   EVT VT = InVec.getValueType();
11492   EVT NVT = N->getValueType(0);
11493
11494   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11495     // Check if the result type doesn't match the inserted element type. A
11496     // SCALAR_TO_VECTOR may truncate the inserted element and the
11497     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11498     SDValue InOp = InVec.getOperand(0);
11499     if (InOp.getValueType() != NVT) {
11500       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11501       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11502     }
11503     return InOp;
11504   }
11505
11506   SDValue EltNo = N->getOperand(1);
11507   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11508
11509   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11510   // We only perform this optimization before the op legalization phase because
11511   // we may introduce new vector instructions which are not backed by TD
11512   // patterns. For example on AVX, extracting elements from a wide vector
11513   // without using extract_subvector. However, if we can find an underlying
11514   // scalar value, then we can always use that.
11515   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11516       && ConstEltNo) {
11517     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11518     int NumElem = VT.getVectorNumElements();
11519     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11520     // Find the new index to extract from.
11521     int OrigElt = SVOp->getMaskElt(Elt);
11522
11523     // Extracting an undef index is undef.
11524     if (OrigElt == -1)
11525       return DAG.getUNDEF(NVT);
11526
11527     // Select the right vector half to extract from.
11528     SDValue SVInVec;
11529     if (OrigElt < NumElem) {
11530       SVInVec = InVec->getOperand(0);
11531     } else {
11532       SVInVec = InVec->getOperand(1);
11533       OrigElt -= NumElem;
11534     }
11535
11536     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11537       SDValue InOp = SVInVec.getOperand(OrigElt);
11538       if (InOp.getValueType() != NVT) {
11539         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11540         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11541       }
11542
11543       return InOp;
11544     }
11545
11546     // FIXME: We should handle recursing on other vector shuffles and
11547     // scalar_to_vector here as well.
11548
11549     if (!LegalOperations) {
11550       EVT IndexTy = TLI.getVectorIdxTy();
11551       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11552                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11553     }
11554   }
11555
11556   bool BCNumEltsChanged = false;
11557   EVT ExtVT = VT.getVectorElementType();
11558   EVT LVT = ExtVT;
11559
11560   // If the result of load has to be truncated, then it's not necessarily
11561   // profitable.
11562   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11563     return SDValue();
11564
11565   if (InVec.getOpcode() == ISD::BITCAST) {
11566     // Don't duplicate a load with other uses.
11567     if (!InVec.hasOneUse())
11568       return SDValue();
11569
11570     EVT BCVT = InVec.getOperand(0).getValueType();
11571     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11572       return SDValue();
11573     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11574       BCNumEltsChanged = true;
11575     InVec = InVec.getOperand(0);
11576     ExtVT = BCVT.getVectorElementType();
11577   }
11578
11579   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11580   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11581       ISD::isNormalLoad(InVec.getNode()) &&
11582       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11583     SDValue Index = N->getOperand(1);
11584     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11585       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11586                                                            OrigLoad);
11587   }
11588
11589   // Perform only after legalization to ensure build_vector / vector_shuffle
11590   // optimizations have already been done.
11591   if (!LegalOperations) return SDValue();
11592
11593   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11594   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11595   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11596
11597   if (ConstEltNo) {
11598     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11599
11600     LoadSDNode *LN0 = nullptr;
11601     const ShuffleVectorSDNode *SVN = nullptr;
11602     if (ISD::isNormalLoad(InVec.getNode())) {
11603       LN0 = cast<LoadSDNode>(InVec);
11604     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11605                InVec.getOperand(0).getValueType() == ExtVT &&
11606                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11607       // Don't duplicate a load with other uses.
11608       if (!InVec.hasOneUse())
11609         return SDValue();
11610
11611       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11612     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11613       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11614       // =>
11615       // (load $addr+1*size)
11616
11617       // Don't duplicate a load with other uses.
11618       if (!InVec.hasOneUse())
11619         return SDValue();
11620
11621       // If the bit convert changed the number of elements, it is unsafe
11622       // to examine the mask.
11623       if (BCNumEltsChanged)
11624         return SDValue();
11625
11626       // Select the input vector, guarding against out of range extract vector.
11627       unsigned NumElems = VT.getVectorNumElements();
11628       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11629       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11630
11631       if (InVec.getOpcode() == ISD::BITCAST) {
11632         // Don't duplicate a load with other uses.
11633         if (!InVec.hasOneUse())
11634           return SDValue();
11635
11636         InVec = InVec.getOperand(0);
11637       }
11638       if (ISD::isNormalLoad(InVec.getNode())) {
11639         LN0 = cast<LoadSDNode>(InVec);
11640         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11641         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11642       }
11643     }
11644
11645     // Make sure we found a non-volatile load and the extractelement is
11646     // the only use.
11647     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11648       return SDValue();
11649
11650     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11651     if (Elt == -1)
11652       return DAG.getUNDEF(LVT);
11653
11654     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11655   }
11656
11657   return SDValue();
11658 }
11659
11660 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11661 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11662   // We perform this optimization post type-legalization because
11663   // the type-legalizer often scalarizes integer-promoted vectors.
11664   // Performing this optimization before may create bit-casts which
11665   // will be type-legalized to complex code sequences.
11666   // We perform this optimization only before the operation legalizer because we
11667   // may introduce illegal operations.
11668   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11669     return SDValue();
11670
11671   unsigned NumInScalars = N->getNumOperands();
11672   SDLoc dl(N);
11673   EVT VT = N->getValueType(0);
11674
11675   // Check to see if this is a BUILD_VECTOR of a bunch of values
11676   // which come from any_extend or zero_extend nodes. If so, we can create
11677   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11678   // optimizations. We do not handle sign-extend because we can't fill the sign
11679   // using shuffles.
11680   EVT SourceType = MVT::Other;
11681   bool AllAnyExt = true;
11682
11683   for (unsigned i = 0; i != NumInScalars; ++i) {
11684     SDValue In = N->getOperand(i);
11685     // Ignore undef inputs.
11686     if (In.getOpcode() == ISD::UNDEF) continue;
11687
11688     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11689     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11690
11691     // Abort if the element is not an extension.
11692     if (!ZeroExt && !AnyExt) {
11693       SourceType = MVT::Other;
11694       break;
11695     }
11696
11697     // The input is a ZeroExt or AnyExt. Check the original type.
11698     EVT InTy = In.getOperand(0).getValueType();
11699
11700     // Check that all of the widened source types are the same.
11701     if (SourceType == MVT::Other)
11702       // First time.
11703       SourceType = InTy;
11704     else if (InTy != SourceType) {
11705       // Multiple income types. Abort.
11706       SourceType = MVT::Other;
11707       break;
11708     }
11709
11710     // Check if all of the extends are ANY_EXTENDs.
11711     AllAnyExt &= AnyExt;
11712   }
11713
11714   // In order to have valid types, all of the inputs must be extended from the
11715   // same source type and all of the inputs must be any or zero extend.
11716   // Scalar sizes must be a power of two.
11717   EVT OutScalarTy = VT.getScalarType();
11718   bool ValidTypes = SourceType != MVT::Other &&
11719                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11720                  isPowerOf2_32(SourceType.getSizeInBits());
11721
11722   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11723   // turn into a single shuffle instruction.
11724   if (!ValidTypes)
11725     return SDValue();
11726
11727   bool isLE = TLI.isLittleEndian();
11728   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11729   assert(ElemRatio > 1 && "Invalid element size ratio");
11730   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11731                                DAG.getConstant(0, SDLoc(N), SourceType);
11732
11733   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11734   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11735
11736   // Populate the new build_vector
11737   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11738     SDValue Cast = N->getOperand(i);
11739     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11740             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11741             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11742     SDValue In;
11743     if (Cast.getOpcode() == ISD::UNDEF)
11744       In = DAG.getUNDEF(SourceType);
11745     else
11746       In = Cast->getOperand(0);
11747     unsigned Index = isLE ? (i * ElemRatio) :
11748                             (i * ElemRatio + (ElemRatio - 1));
11749
11750     assert(Index < Ops.size() && "Invalid index");
11751     Ops[Index] = In;
11752   }
11753
11754   // The type of the new BUILD_VECTOR node.
11755   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11756   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11757          "Invalid vector size");
11758   // Check if the new vector type is legal.
11759   if (!isTypeLegal(VecVT)) return SDValue();
11760
11761   // Make the new BUILD_VECTOR.
11762   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11763
11764   // The new BUILD_VECTOR node has the potential to be further optimized.
11765   AddToWorklist(BV.getNode());
11766   // Bitcast to the desired type.
11767   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11768 }
11769
11770 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11771   EVT VT = N->getValueType(0);
11772
11773   unsigned NumInScalars = N->getNumOperands();
11774   SDLoc dl(N);
11775
11776   EVT SrcVT = MVT::Other;
11777   unsigned Opcode = ISD::DELETED_NODE;
11778   unsigned NumDefs = 0;
11779
11780   for (unsigned i = 0; i != NumInScalars; ++i) {
11781     SDValue In = N->getOperand(i);
11782     unsigned Opc = In.getOpcode();
11783
11784     if (Opc == ISD::UNDEF)
11785       continue;
11786
11787     // If all scalar values are floats and converted from integers.
11788     if (Opcode == ISD::DELETED_NODE &&
11789         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11790       Opcode = Opc;
11791     }
11792
11793     if (Opc != Opcode)
11794       return SDValue();
11795
11796     EVT InVT = In.getOperand(0).getValueType();
11797
11798     // If all scalar values are typed differently, bail out. It's chosen to
11799     // simplify BUILD_VECTOR of integer types.
11800     if (SrcVT == MVT::Other)
11801       SrcVT = InVT;
11802     if (SrcVT != InVT)
11803       return SDValue();
11804     NumDefs++;
11805   }
11806
11807   // If the vector has just one element defined, it's not worth to fold it into
11808   // a vectorized one.
11809   if (NumDefs < 2)
11810     return SDValue();
11811
11812   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11813          && "Should only handle conversion from integer to float.");
11814   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11815
11816   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11817
11818   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11819     return SDValue();
11820
11821   // Just because the floating-point vector type is legal does not necessarily
11822   // mean that the corresponding integer vector type is.
11823   if (!isTypeLegal(NVT))
11824     return SDValue();
11825
11826   SmallVector<SDValue, 8> Opnds;
11827   for (unsigned i = 0; i != NumInScalars; ++i) {
11828     SDValue In = N->getOperand(i);
11829
11830     if (In.getOpcode() == ISD::UNDEF)
11831       Opnds.push_back(DAG.getUNDEF(SrcVT));
11832     else
11833       Opnds.push_back(In.getOperand(0));
11834   }
11835   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11836   AddToWorklist(BV.getNode());
11837
11838   return DAG.getNode(Opcode, dl, VT, BV);
11839 }
11840
11841 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11842   unsigned NumInScalars = N->getNumOperands();
11843   SDLoc dl(N);
11844   EVT VT = N->getValueType(0);
11845
11846   // A vector built entirely of undefs is undef.
11847   if (ISD::allOperandsUndef(N))
11848     return DAG.getUNDEF(VT);
11849
11850   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11851     return V;
11852
11853   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11854     return V;
11855
11856   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11857   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11858   // at most two distinct vectors, turn this into a shuffle node.
11859
11860   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11861   if (!isTypeLegal(VT))
11862     return SDValue();
11863
11864   // May only combine to shuffle after legalize if shuffle is legal.
11865   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11866     return SDValue();
11867
11868   SDValue VecIn1, VecIn2;
11869   bool UsesZeroVector = false;
11870   for (unsigned i = 0; i != NumInScalars; ++i) {
11871     SDValue Op = N->getOperand(i);
11872     // Ignore undef inputs.
11873     if (Op.getOpcode() == ISD::UNDEF) continue;
11874
11875     // See if we can combine this build_vector into a blend with a zero vector.
11876     if (!VecIn2.getNode() && (isNullConstant(Op) ||
11877         (Op.getOpcode() == ISD::ConstantFP &&
11878         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11879       UsesZeroVector = true;
11880       continue;
11881     }
11882
11883     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11884     // constant index, bail out.
11885     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11886         !isa<ConstantSDNode>(Op.getOperand(1))) {
11887       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11888       break;
11889     }
11890
11891     // We allow up to two distinct input vectors.
11892     SDValue ExtractedFromVec = Op.getOperand(0);
11893     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11894       continue;
11895
11896     if (!VecIn1.getNode()) {
11897       VecIn1 = ExtractedFromVec;
11898     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11899       VecIn2 = ExtractedFromVec;
11900     } else {
11901       // Too many inputs.
11902       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11903       break;
11904     }
11905   }
11906
11907   // If everything is good, we can make a shuffle operation.
11908   if (VecIn1.getNode()) {
11909     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11910     SmallVector<int, 8> Mask;
11911     for (unsigned i = 0; i != NumInScalars; ++i) {
11912       unsigned Opcode = N->getOperand(i).getOpcode();
11913       if (Opcode == ISD::UNDEF) {
11914         Mask.push_back(-1);
11915         continue;
11916       }
11917
11918       // Operands can also be zero.
11919       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11920         assert(UsesZeroVector &&
11921                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11922                "Unexpected node found!");
11923         Mask.push_back(NumInScalars+i);
11924         continue;
11925       }
11926
11927       // If extracting from the first vector, just use the index directly.
11928       SDValue Extract = N->getOperand(i);
11929       SDValue ExtVal = Extract.getOperand(1);
11930       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11931       if (Extract.getOperand(0) == VecIn1) {
11932         Mask.push_back(ExtIndex);
11933         continue;
11934       }
11935
11936       // Otherwise, use InIdx + InputVecSize
11937       Mask.push_back(InNumElements + ExtIndex);
11938     }
11939
11940     // Avoid introducing illegal shuffles with zero.
11941     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11942       return SDValue();
11943
11944     // We can't generate a shuffle node with mismatched input and output types.
11945     // Attempt to transform a single input vector to the correct type.
11946     if ((VT != VecIn1.getValueType())) {
11947       // If the input vector type has a different base type to the output
11948       // vector type, bail out.
11949       EVT VTElemType = VT.getVectorElementType();
11950       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11951           (VecIn2.getNode() &&
11952            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11953         return SDValue();
11954
11955       // If the input vector is too small, widen it.
11956       // We only support widening of vectors which are half the size of the
11957       // output registers. For example XMM->YMM widening on X86 with AVX.
11958       EVT VecInT = VecIn1.getValueType();
11959       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11960         // If we only have one small input, widen it by adding undef values.
11961         if (!VecIn2.getNode())
11962           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11963                                DAG.getUNDEF(VecIn1.getValueType()));
11964         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11965           // If we have two small inputs of the same type, try to concat them.
11966           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11967           VecIn2 = SDValue(nullptr, 0);
11968         } else
11969           return SDValue();
11970       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11971         // If the input vector is too large, try to split it.
11972         // We don't support having two input vectors that are too large.
11973         // If the zero vector was used, we can not split the vector,
11974         // since we'd need 3 inputs.
11975         if (UsesZeroVector || VecIn2.getNode())
11976           return SDValue();
11977
11978         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11979           return SDValue();
11980
11981         // Try to replace VecIn1 with two extract_subvectors
11982         // No need to update the masks, they should still be correct.
11983         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11984           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11985         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11986           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11987       } else
11988         return SDValue();
11989     }
11990
11991     if (UsesZeroVector)
11992       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11993                                 DAG.getConstantFP(0.0, dl, VT);
11994     else
11995       // If VecIn2 is unused then change it to undef.
11996       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11997
11998     // Check that we were able to transform all incoming values to the same
11999     // type.
12000     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12001         VecIn1.getValueType() != VT)
12002           return SDValue();
12003
12004     // Return the new VECTOR_SHUFFLE node.
12005     SDValue Ops[2];
12006     Ops[0] = VecIn1;
12007     Ops[1] = VecIn2;
12008     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12009   }
12010
12011   return SDValue();
12012 }
12013
12014 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12016   EVT OpVT = N->getOperand(0).getValueType();
12017
12018   // If the operands are legal vectors, leave them alone.
12019   if (TLI.isTypeLegal(OpVT))
12020     return SDValue();
12021
12022   SDLoc DL(N);
12023   EVT VT = N->getValueType(0);
12024   SmallVector<SDValue, 8> Ops;
12025
12026   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12027   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12028
12029   // Keep track of what we encounter.
12030   bool AnyInteger = false;
12031   bool AnyFP = false;
12032   for (const SDValue &Op : N->ops()) {
12033     if (ISD::BITCAST == Op.getOpcode() &&
12034         !Op.getOperand(0).getValueType().isVector())
12035       Ops.push_back(Op.getOperand(0));
12036     else if (ISD::UNDEF == Op.getOpcode())
12037       Ops.push_back(ScalarUndef);
12038     else
12039       return SDValue();
12040
12041     // Note whether we encounter an integer or floating point scalar.
12042     // If it's neither, bail out, it could be something weird like x86mmx.
12043     EVT LastOpVT = Ops.back().getValueType();
12044     if (LastOpVT.isFloatingPoint())
12045       AnyFP = true;
12046     else if (LastOpVT.isInteger())
12047       AnyInteger = true;
12048     else
12049       return SDValue();
12050   }
12051
12052   // If any of the operands is a floating point scalar bitcast to a vector,
12053   // use floating point types throughout, and bitcast everything.  
12054   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12055   if (AnyFP) {
12056     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12057     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12058     if (AnyInteger) {
12059       for (SDValue &Op : Ops) {
12060         if (Op.getValueType() == SVT)
12061           continue;
12062         if (Op.getOpcode() == ISD::UNDEF)
12063           Op = ScalarUndef;
12064         else
12065           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12066       }
12067     }
12068   }
12069
12070   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12071                                VT.getSizeInBits() / SVT.getSizeInBits());
12072   return DAG.getNode(ISD::BITCAST, DL, VT,
12073                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12074 }
12075
12076 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12077   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12078   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12079   // inputs come from at most two distinct vectors, turn this into a shuffle
12080   // node.
12081
12082   // If we only have one input vector, we don't need to do any concatenation.
12083   if (N->getNumOperands() == 1)
12084     return N->getOperand(0);
12085
12086   // Check if all of the operands are undefs.
12087   EVT VT = N->getValueType(0);
12088   if (ISD::allOperandsUndef(N))
12089     return DAG.getUNDEF(VT);
12090
12091   // Optimize concat_vectors where all but the first of the vectors are undef.
12092   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12093         return Op.getOpcode() == ISD::UNDEF;
12094       })) {
12095     SDValue In = N->getOperand(0);
12096     assert(In.getValueType().isVector() && "Must concat vectors");
12097
12098     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12099     if (In->getOpcode() == ISD::BITCAST &&
12100         !In->getOperand(0)->getValueType(0).isVector()) {
12101       SDValue Scalar = In->getOperand(0);
12102
12103       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12104       // look through the trunc so we can still do the transform:
12105       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12106       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12107           !TLI.isTypeLegal(Scalar.getValueType()) &&
12108           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12109         Scalar = Scalar->getOperand(0);
12110
12111       EVT SclTy = Scalar->getValueType(0);
12112
12113       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12114         return SDValue();
12115
12116       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12117                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12118       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12119         return SDValue();
12120
12121       SDLoc dl = SDLoc(N);
12122       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12123       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12124     }
12125   }
12126
12127   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12128   // We have already tested above for an UNDEF only concatenation.
12129   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12130   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12131   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12132     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12133   };
12134   bool AllBuildVectorsOrUndefs =
12135       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12136   if (AllBuildVectorsOrUndefs) {
12137     SmallVector<SDValue, 8> Opnds;
12138     EVT SVT = VT.getScalarType();
12139
12140     EVT MinVT = SVT;
12141     if (!SVT.isFloatingPoint()) {
12142       // If BUILD_VECTOR are from built from integer, they may have different
12143       // operand types. Get the smallest type and truncate all operands to it.
12144       bool FoundMinVT = false;
12145       for (const SDValue &Op : N->ops())
12146         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12147           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12148           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12149           FoundMinVT = true;
12150         }
12151       assert(FoundMinVT && "Concat vector type mismatch");
12152     }
12153
12154     for (const SDValue &Op : N->ops()) {
12155       EVT OpVT = Op.getValueType();
12156       unsigned NumElts = OpVT.getVectorNumElements();
12157
12158       if (ISD::UNDEF == Op.getOpcode())
12159         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12160
12161       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12162         if (SVT.isFloatingPoint()) {
12163           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12164           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12165         } else {
12166           for (unsigned i = 0; i != NumElts; ++i)
12167             Opnds.push_back(
12168                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12169         }
12170       }
12171     }
12172
12173     assert(VT.getVectorNumElements() == Opnds.size() &&
12174            "Concat vector type mismatch");
12175     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12176   }
12177
12178   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12179   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12180     return V;
12181
12182   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12183   // nodes often generate nop CONCAT_VECTOR nodes.
12184   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12185   // place the incoming vectors at the exact same location.
12186   SDValue SingleSource = SDValue();
12187   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12188
12189   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12190     SDValue Op = N->getOperand(i);
12191
12192     if (Op.getOpcode() == ISD::UNDEF)
12193       continue;
12194
12195     // Check if this is the identity extract:
12196     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12197       return SDValue();
12198
12199     // Find the single incoming vector for the extract_subvector.
12200     if (SingleSource.getNode()) {
12201       if (Op.getOperand(0) != SingleSource)
12202         return SDValue();
12203     } else {
12204       SingleSource = Op.getOperand(0);
12205
12206       // Check the source type is the same as the type of the result.
12207       // If not, this concat may extend the vector, so we can not
12208       // optimize it away.
12209       if (SingleSource.getValueType() != N->getValueType(0))
12210         return SDValue();
12211     }
12212
12213     unsigned IdentityIndex = i * PartNumElem;
12214     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12215     // The extract index must be constant.
12216     if (!CS)
12217       return SDValue();
12218
12219     // Check that we are reading from the identity index.
12220     if (CS->getZExtValue() != IdentityIndex)
12221       return SDValue();
12222   }
12223
12224   if (SingleSource.getNode())
12225     return SingleSource;
12226
12227   return SDValue();
12228 }
12229
12230 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12231   EVT NVT = N->getValueType(0);
12232   SDValue V = N->getOperand(0);
12233
12234   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12235     // Combine:
12236     //    (extract_subvec (concat V1, V2, ...), i)
12237     // Into:
12238     //    Vi if possible
12239     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12240     // type.
12241     if (V->getOperand(0).getValueType() != NVT)
12242       return SDValue();
12243     unsigned Idx = N->getConstantOperandVal(1);
12244     unsigned NumElems = NVT.getVectorNumElements();
12245     assert((Idx % NumElems) == 0 &&
12246            "IDX in concat is not a multiple of the result vector length.");
12247     return V->getOperand(Idx / NumElems);
12248   }
12249
12250   // Skip bitcasting
12251   if (V->getOpcode() == ISD::BITCAST)
12252     V = V.getOperand(0);
12253
12254   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12255     SDLoc dl(N);
12256     // Handle only simple case where vector being inserted and vector
12257     // being extracted are of same type, and are half size of larger vectors.
12258     EVT BigVT = V->getOperand(0).getValueType();
12259     EVT SmallVT = V->getOperand(1).getValueType();
12260     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12261       return SDValue();
12262
12263     // Only handle cases where both indexes are constants with the same type.
12264     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12265     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12266
12267     if (InsIdx && ExtIdx &&
12268         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12269         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12270       // Combine:
12271       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12272       // Into:
12273       //    indices are equal or bit offsets are equal => V1
12274       //    otherwise => (extract_subvec V1, ExtIdx)
12275       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12276           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12277         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12278       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12279                          DAG.getNode(ISD::BITCAST, dl,
12280                                      N->getOperand(0).getValueType(),
12281                                      V->getOperand(0)), N->getOperand(1));
12282     }
12283   }
12284
12285   return SDValue();
12286 }
12287
12288 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12289                                                  SDValue V, SelectionDAG &DAG) {
12290   SDLoc DL(V);
12291   EVT VT = V.getValueType();
12292
12293   switch (V.getOpcode()) {
12294   default:
12295     return V;
12296
12297   case ISD::CONCAT_VECTORS: {
12298     EVT OpVT = V->getOperand(0).getValueType();
12299     int OpSize = OpVT.getVectorNumElements();
12300     SmallBitVector OpUsedElements(OpSize, false);
12301     bool FoundSimplification = false;
12302     SmallVector<SDValue, 4> NewOps;
12303     NewOps.reserve(V->getNumOperands());
12304     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12305       SDValue Op = V->getOperand(i);
12306       bool OpUsed = false;
12307       for (int j = 0; j < OpSize; ++j)
12308         if (UsedElements[i * OpSize + j]) {
12309           OpUsedElements[j] = true;
12310           OpUsed = true;
12311         }
12312       NewOps.push_back(
12313           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12314                  : DAG.getUNDEF(OpVT));
12315       FoundSimplification |= Op == NewOps.back();
12316       OpUsedElements.reset();
12317     }
12318     if (FoundSimplification)
12319       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12320     return V;
12321   }
12322
12323   case ISD::INSERT_SUBVECTOR: {
12324     SDValue BaseV = V->getOperand(0);
12325     SDValue SubV = V->getOperand(1);
12326     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12327     if (!IdxN)
12328       return V;
12329
12330     int SubSize = SubV.getValueType().getVectorNumElements();
12331     int Idx = IdxN->getZExtValue();
12332     bool SubVectorUsed = false;
12333     SmallBitVector SubUsedElements(SubSize, false);
12334     for (int i = 0; i < SubSize; ++i)
12335       if (UsedElements[i + Idx]) {
12336         SubVectorUsed = true;
12337         SubUsedElements[i] = true;
12338         UsedElements[i + Idx] = false;
12339       }
12340
12341     // Now recurse on both the base and sub vectors.
12342     SDValue SimplifiedSubV =
12343         SubVectorUsed
12344             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12345             : DAG.getUNDEF(SubV.getValueType());
12346     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12347     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12348       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12349                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12350     return V;
12351   }
12352   }
12353 }
12354
12355 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12356                                        SDValue N1, SelectionDAG &DAG) {
12357   EVT VT = SVN->getValueType(0);
12358   int NumElts = VT.getVectorNumElements();
12359   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12360   for (int M : SVN->getMask())
12361     if (M >= 0 && M < NumElts)
12362       N0UsedElements[M] = true;
12363     else if (M >= NumElts)
12364       N1UsedElements[M - NumElts] = true;
12365
12366   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12367   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12368   if (S0 == N0 && S1 == N1)
12369     return SDValue();
12370
12371   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12372 }
12373
12374 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12375 // or turn a shuffle of a single concat into simpler shuffle then concat.
12376 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12377   EVT VT = N->getValueType(0);
12378   unsigned NumElts = VT.getVectorNumElements();
12379
12380   SDValue N0 = N->getOperand(0);
12381   SDValue N1 = N->getOperand(1);
12382   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12383
12384   SmallVector<SDValue, 4> Ops;
12385   EVT ConcatVT = N0.getOperand(0).getValueType();
12386   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12387   unsigned NumConcats = NumElts / NumElemsPerConcat;
12388
12389   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12390   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12391   // half vector elements.
12392   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12393       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12394                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12395     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12396                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12397     N1 = DAG.getUNDEF(ConcatVT);
12398     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12399   }
12400
12401   // Look at every vector that's inserted. We're looking for exact
12402   // subvector-sized copies from a concatenated vector
12403   for (unsigned I = 0; I != NumConcats; ++I) {
12404     // Make sure we're dealing with a copy.
12405     unsigned Begin = I * NumElemsPerConcat;
12406     bool AllUndef = true, NoUndef = true;
12407     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12408       if (SVN->getMaskElt(J) >= 0)
12409         AllUndef = false;
12410       else
12411         NoUndef = false;
12412     }
12413
12414     if (NoUndef) {
12415       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12416         return SDValue();
12417
12418       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12419         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12420           return SDValue();
12421
12422       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12423       if (FirstElt < N0.getNumOperands())
12424         Ops.push_back(N0.getOperand(FirstElt));
12425       else
12426         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12427
12428     } else if (AllUndef) {
12429       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12430     } else { // Mixed with general masks and undefs, can't do optimization.
12431       return SDValue();
12432     }
12433   }
12434
12435   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12436 }
12437
12438 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12439   EVT VT = N->getValueType(0);
12440   unsigned NumElts = VT.getVectorNumElements();
12441
12442   SDValue N0 = N->getOperand(0);
12443   SDValue N1 = N->getOperand(1);
12444
12445   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12446
12447   // Canonicalize shuffle undef, undef -> undef
12448   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12449     return DAG.getUNDEF(VT);
12450
12451   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12452
12453   // Canonicalize shuffle v, v -> v, undef
12454   if (N0 == N1) {
12455     SmallVector<int, 8> NewMask;
12456     for (unsigned i = 0; i != NumElts; ++i) {
12457       int Idx = SVN->getMaskElt(i);
12458       if (Idx >= (int)NumElts) Idx -= NumElts;
12459       NewMask.push_back(Idx);
12460     }
12461     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12462                                 &NewMask[0]);
12463   }
12464
12465   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12466   if (N0.getOpcode() == ISD::UNDEF) {
12467     SmallVector<int, 8> NewMask;
12468     for (unsigned i = 0; i != NumElts; ++i) {
12469       int Idx = SVN->getMaskElt(i);
12470       if (Idx >= 0) {
12471         if (Idx >= (int)NumElts)
12472           Idx -= NumElts;
12473         else
12474           Idx = -1; // remove reference to lhs
12475       }
12476       NewMask.push_back(Idx);
12477     }
12478     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12479                                 &NewMask[0]);
12480   }
12481
12482   // Remove references to rhs if it is undef
12483   if (N1.getOpcode() == ISD::UNDEF) {
12484     bool Changed = false;
12485     SmallVector<int, 8> NewMask;
12486     for (unsigned i = 0; i != NumElts; ++i) {
12487       int Idx = SVN->getMaskElt(i);
12488       if (Idx >= (int)NumElts) {
12489         Idx = -1;
12490         Changed = true;
12491       }
12492       NewMask.push_back(Idx);
12493     }
12494     if (Changed)
12495       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12496   }
12497
12498   // If it is a splat, check if the argument vector is another splat or a
12499   // build_vector.
12500   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12501     SDNode *V = N0.getNode();
12502
12503     // If this is a bit convert that changes the element type of the vector but
12504     // not the number of vector elements, look through it.  Be careful not to
12505     // look though conversions that change things like v4f32 to v2f64.
12506     if (V->getOpcode() == ISD::BITCAST) {
12507       SDValue ConvInput = V->getOperand(0);
12508       if (ConvInput.getValueType().isVector() &&
12509           ConvInput.getValueType().getVectorNumElements() == NumElts)
12510         V = ConvInput.getNode();
12511     }
12512
12513     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12514       assert(V->getNumOperands() == NumElts &&
12515              "BUILD_VECTOR has wrong number of operands");
12516       SDValue Base;
12517       bool AllSame = true;
12518       for (unsigned i = 0; i != NumElts; ++i) {
12519         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12520           Base = V->getOperand(i);
12521           break;
12522         }
12523       }
12524       // Splat of <u, u, u, u>, return <u, u, u, u>
12525       if (!Base.getNode())
12526         return N0;
12527       for (unsigned i = 0; i != NumElts; ++i) {
12528         if (V->getOperand(i) != Base) {
12529           AllSame = false;
12530           break;
12531         }
12532       }
12533       // Splat of <x, x, x, x>, return <x, x, x, x>
12534       if (AllSame)
12535         return N0;
12536
12537       // Canonicalize any other splat as a build_vector.
12538       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12539       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12540       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12541                                   V->getValueType(0), Ops);
12542
12543       // We may have jumped through bitcasts, so the type of the
12544       // BUILD_VECTOR may not match the type of the shuffle.
12545       if (V->getValueType(0) != VT)
12546         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12547       return NewBV;
12548     }
12549   }
12550
12551   // There are various patterns used to build up a vector from smaller vectors,
12552   // subvectors, or elements. Scan chains of these and replace unused insertions
12553   // or components with undef.
12554   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12555     return S;
12556
12557   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12558       Level < AfterLegalizeVectorOps &&
12559       (N1.getOpcode() == ISD::UNDEF ||
12560       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12561        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12562     SDValue V = partitionShuffleOfConcats(N, DAG);
12563
12564     if (V.getNode())
12565       return V;
12566   }
12567
12568   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12569   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12570   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12571     SmallVector<SDValue, 8> Ops;
12572     for (int M : SVN->getMask()) {
12573       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12574       if (M >= 0) {
12575         int Idx = M % NumElts;
12576         SDValue &S = (M < (int)NumElts ? N0 : N1);
12577         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12578           Op = S.getOperand(Idx);
12579         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12580           if (Idx == 0)
12581             Op = S.getOperand(0);
12582         } else {
12583           // Operand can't be combined - bail out.
12584           break;
12585         }
12586       }
12587       Ops.push_back(Op);
12588     }
12589     if (Ops.size() == VT.getVectorNumElements()) {
12590       // BUILD_VECTOR requires all inputs to be of the same type, find the
12591       // maximum type and extend them all.
12592       EVT SVT = VT.getScalarType();
12593       if (SVT.isInteger())
12594         for (SDValue &Op : Ops)
12595           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12596       if (SVT != VT.getScalarType())
12597         for (SDValue &Op : Ops)
12598           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12599                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12600                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12601       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12602     }
12603   }
12604
12605   // If this shuffle only has a single input that is a bitcasted shuffle,
12606   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12607   // back to their original types.
12608   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12609       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12610       TLI.isTypeLegal(VT)) {
12611
12612     // Peek through the bitcast only if there is one user.
12613     SDValue BC0 = N0;
12614     while (BC0.getOpcode() == ISD::BITCAST) {
12615       if (!BC0.hasOneUse())
12616         break;
12617       BC0 = BC0.getOperand(0);
12618     }
12619
12620     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12621       if (Scale == 1)
12622         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12623
12624       SmallVector<int, 8> NewMask;
12625       for (int M : Mask)
12626         for (int s = 0; s != Scale; ++s)
12627           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12628       return NewMask;
12629     };
12630
12631     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12632       EVT SVT = VT.getScalarType();
12633       EVT InnerVT = BC0->getValueType(0);
12634       EVT InnerSVT = InnerVT.getScalarType();
12635
12636       // Determine which shuffle works with the smaller scalar type.
12637       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12638       EVT ScaleSVT = ScaleVT.getScalarType();
12639
12640       if (TLI.isTypeLegal(ScaleVT) &&
12641           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12642           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12643
12644         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12645         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12646
12647         // Scale the shuffle masks to the smaller scalar type.
12648         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12649         SmallVector<int, 8> InnerMask =
12650             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12651         SmallVector<int, 8> OuterMask =
12652             ScaleShuffleMask(SVN->getMask(), OuterScale);
12653
12654         // Merge the shuffle masks.
12655         SmallVector<int, 8> NewMask;
12656         for (int M : OuterMask)
12657           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12658
12659         // Test for shuffle mask legality over both commutations.
12660         SDValue SV0 = BC0->getOperand(0);
12661         SDValue SV1 = BC0->getOperand(1);
12662         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12663         if (!LegalMask) {
12664           std::swap(SV0, SV1);
12665           ShuffleVectorSDNode::commuteMask(NewMask);
12666           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12667         }
12668
12669         if (LegalMask) {
12670           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12671           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12672           return DAG.getNode(
12673               ISD::BITCAST, SDLoc(N), VT,
12674               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12675         }
12676       }
12677     }
12678   }
12679
12680   // Canonicalize shuffles according to rules:
12681   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12682   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12683   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12684   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12685       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12686       TLI.isTypeLegal(VT)) {
12687     // The incoming shuffle must be of the same type as the result of the
12688     // current shuffle.
12689     assert(N1->getOperand(0).getValueType() == VT &&
12690            "Shuffle types don't match");
12691
12692     SDValue SV0 = N1->getOperand(0);
12693     SDValue SV1 = N1->getOperand(1);
12694     bool HasSameOp0 = N0 == SV0;
12695     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12696     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12697       // Commute the operands of this shuffle so that next rule
12698       // will trigger.
12699       return DAG.getCommutedVectorShuffle(*SVN);
12700   }
12701
12702   // Try to fold according to rules:
12703   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12704   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12705   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12706   // Don't try to fold shuffles with illegal type.
12707   // Only fold if this shuffle is the only user of the other shuffle.
12708   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12709       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12710     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12711
12712     // The incoming shuffle must be of the same type as the result of the
12713     // current shuffle.
12714     assert(OtherSV->getOperand(0).getValueType() == VT &&
12715            "Shuffle types don't match");
12716
12717     SDValue SV0, SV1;
12718     SmallVector<int, 4> Mask;
12719     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12720     // operand, and SV1 as the second operand.
12721     for (unsigned i = 0; i != NumElts; ++i) {
12722       int Idx = SVN->getMaskElt(i);
12723       if (Idx < 0) {
12724         // Propagate Undef.
12725         Mask.push_back(Idx);
12726         continue;
12727       }
12728
12729       SDValue CurrentVec;
12730       if (Idx < (int)NumElts) {
12731         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12732         // shuffle mask to identify which vector is actually referenced.
12733         Idx = OtherSV->getMaskElt(Idx);
12734         if (Idx < 0) {
12735           // Propagate Undef.
12736           Mask.push_back(Idx);
12737           continue;
12738         }
12739
12740         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12741                                            : OtherSV->getOperand(1);
12742       } else {
12743         // This shuffle index references an element within N1.
12744         CurrentVec = N1;
12745       }
12746
12747       // Simple case where 'CurrentVec' is UNDEF.
12748       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12749         Mask.push_back(-1);
12750         continue;
12751       }
12752
12753       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12754       // will be the first or second operand of the combined shuffle.
12755       Idx = Idx % NumElts;
12756       if (!SV0.getNode() || SV0 == CurrentVec) {
12757         // Ok. CurrentVec is the left hand side.
12758         // Update the mask accordingly.
12759         SV0 = CurrentVec;
12760         Mask.push_back(Idx);
12761         continue;
12762       }
12763
12764       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12765       if (SV1.getNode() && SV1 != CurrentVec)
12766         return SDValue();
12767
12768       // Ok. CurrentVec is the right hand side.
12769       // Update the mask accordingly.
12770       SV1 = CurrentVec;
12771       Mask.push_back(Idx + NumElts);
12772     }
12773
12774     // Check if all indices in Mask are Undef. In case, propagate Undef.
12775     bool isUndefMask = true;
12776     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12777       isUndefMask &= Mask[i] < 0;
12778
12779     if (isUndefMask)
12780       return DAG.getUNDEF(VT);
12781
12782     if (!SV0.getNode())
12783       SV0 = DAG.getUNDEF(VT);
12784     if (!SV1.getNode())
12785       SV1 = DAG.getUNDEF(VT);
12786
12787     // Avoid introducing shuffles with illegal mask.
12788     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12789       ShuffleVectorSDNode::commuteMask(Mask);
12790
12791       if (!TLI.isShuffleMaskLegal(Mask, VT))
12792         return SDValue();
12793
12794       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12795       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12796       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12797       std::swap(SV0, SV1);
12798     }
12799
12800     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12801     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12802     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12803     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12804   }
12805
12806   return SDValue();
12807 }
12808
12809 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12810   SDValue InVal = N->getOperand(0);
12811   EVT VT = N->getValueType(0);
12812
12813   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12814   // with a VECTOR_SHUFFLE.
12815   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12816     SDValue InVec = InVal->getOperand(0);
12817     SDValue EltNo = InVal->getOperand(1);
12818
12819     // FIXME: We could support implicit truncation if the shuffle can be
12820     // scaled to a smaller vector scalar type.
12821     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12822     if (C0 && VT == InVec.getValueType() &&
12823         VT.getScalarType() == InVal.getValueType()) {
12824       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12825       int Elt = C0->getZExtValue();
12826       NewMask[0] = Elt;
12827
12828       if (TLI.isShuffleMaskLegal(NewMask, VT))
12829         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12830                                     NewMask);
12831     }
12832   }
12833
12834   return SDValue();
12835 }
12836
12837 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12838   SDValue N0 = N->getOperand(0);
12839   SDValue N2 = N->getOperand(2);
12840
12841   // If the input vector is a concatenation, and the insert replaces
12842   // one of the halves, we can optimize into a single concat_vectors.
12843   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12844       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12845     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12846     EVT VT = N->getValueType(0);
12847
12848     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12849     // (concat_vectors Z, Y)
12850     if (InsIdx == 0)
12851       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12852                          N->getOperand(1), N0.getOperand(1));
12853
12854     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12855     // (concat_vectors X, Z)
12856     if (InsIdx == VT.getVectorNumElements()/2)
12857       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12858                          N0.getOperand(0), N->getOperand(1));
12859   }
12860
12861   return SDValue();
12862 }
12863
12864 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12865   SDValue N0 = N->getOperand(0);
12866
12867   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12868   if (N0->getOpcode() == ISD::FP16_TO_FP)
12869     return N0->getOperand(0);
12870
12871   return SDValue();
12872 }
12873
12874 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12875 /// with the destination vector and a zero vector.
12876 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12877 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12878 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12879   EVT VT = N->getValueType(0);
12880   SDValue LHS = N->getOperand(0);
12881   SDValue RHS = N->getOperand(1);
12882   SDLoc dl(N);
12883
12884   // Make sure we're not running after operation legalization where it 
12885   // may have custom lowered the vector shuffles.
12886   if (LegalOperations)
12887     return SDValue();
12888
12889   if (N->getOpcode() != ISD::AND)
12890     return SDValue();
12891
12892   if (RHS.getOpcode() == ISD::BITCAST)
12893     RHS = RHS.getOperand(0);
12894
12895   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12896     SmallVector<int, 8> Indices;
12897     unsigned NumElts = RHS.getNumOperands();
12898
12899     for (unsigned i = 0; i != NumElts; ++i) {
12900       SDValue Elt = RHS.getOperand(i);
12901       if (const ConstantSDNode *EltC = dyn_cast<const ConstantSDNode>(Elt)) {
12902         if (EltC->isAllOnesValue())
12903           Indices.push_back(i);
12904         else if (EltC->isNullValue())
12905           Indices.push_back(NumElts+i);
12906         else
12907           return SDValue();
12908       } else {
12909         return SDValue();
12910       }
12911     }
12912
12913     // Let's see if the target supports this vector_shuffle.
12914     EVT RVT = RHS.getValueType();
12915     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12916       return SDValue();
12917
12918     // Return the new VECTOR_SHUFFLE node.
12919     EVT EltVT = RVT.getVectorElementType();
12920     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12921                                    DAG.getConstant(0, dl, EltVT));
12922     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12923     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12924     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12925     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12926   }
12927
12928   return SDValue();
12929 }
12930
12931 /// Visit a binary vector operation, like ADD.
12932 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12933   assert(N->getValueType(0).isVector() &&
12934          "SimplifyVBinOp only works on vectors!");
12935
12936   SDValue LHS = N->getOperand(0);
12937   SDValue RHS = N->getOperand(1);
12938
12939   if (SDValue Shuffle = XformToShuffleWithZero(N))
12940     return Shuffle;
12941
12942   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12943   // this operation.
12944   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12945       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12946     // Check if both vectors are constants. If not bail out.
12947     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12948           cast<BuildVectorSDNode>(RHS)->isConstant()))
12949       return SDValue();
12950
12951     SmallVector<SDValue, 8> Ops;
12952     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12953       SDValue LHSOp = LHS.getOperand(i);
12954       SDValue RHSOp = RHS.getOperand(i);
12955
12956       // Can't fold divide by zero.
12957       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12958           N->getOpcode() == ISD::FDIV) {
12959         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12960              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12961           break;
12962       }
12963
12964       EVT VT = LHSOp.getValueType();
12965       EVT RVT = RHSOp.getValueType();
12966       if (RVT != VT) {
12967         // Integer BUILD_VECTOR operands may have types larger than the element
12968         // size (e.g., when the element type is not legal).  Prior to type
12969         // legalization, the types may not match between the two BUILD_VECTORS.
12970         // Truncate one of the operands to make them match.
12971         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12972           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12973         } else {
12974           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12975           VT = RVT;
12976         }
12977       }
12978       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12979                                    LHSOp, RHSOp);
12980       if (FoldOp.getOpcode() != ISD::UNDEF &&
12981           FoldOp.getOpcode() != ISD::Constant &&
12982           FoldOp.getOpcode() != ISD::ConstantFP)
12983         break;
12984       Ops.push_back(FoldOp);
12985       AddToWorklist(FoldOp.getNode());
12986     }
12987
12988     if (Ops.size() == LHS.getNumOperands())
12989       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12990   }
12991
12992   // Type legalization might introduce new shuffles in the DAG.
12993   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12994   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12995   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12996       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12997       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12998       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12999     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13000     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13001
13002     if (SVN0->getMask().equals(SVN1->getMask())) {
13003       EVT VT = N->getValueType(0);
13004       SDValue UndefVector = LHS.getOperand(1);
13005       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13006                                      LHS.getOperand(0), RHS.getOperand(0));
13007       AddUsersToWorklist(N);
13008       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13009                                   &SVN0->getMask()[0]);
13010     }
13011   }
13012
13013   return SDValue();
13014 }
13015
13016 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13017                                     SDValue N1, SDValue N2){
13018   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13019
13020   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13021                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13022
13023   // If we got a simplified select_cc node back from SimplifySelectCC, then
13024   // break it down into a new SETCC node, and a new SELECT node, and then return
13025   // the SELECT node, since we were called with a SELECT node.
13026   if (SCC.getNode()) {
13027     // Check to see if we got a select_cc back (to turn into setcc/select).
13028     // Otherwise, just return whatever node we got back, like fabs.
13029     if (SCC.getOpcode() == ISD::SELECT_CC) {
13030       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13031                                   N0.getValueType(),
13032                                   SCC.getOperand(0), SCC.getOperand(1),
13033                                   SCC.getOperand(4));
13034       AddToWorklist(SETCC.getNode());
13035       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13036                            SCC.getOperand(2), SCC.getOperand(3));
13037     }
13038
13039     return SCC;
13040   }
13041   return SDValue();
13042 }
13043
13044 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13045 /// being selected between, see if we can simplify the select.  Callers of this
13046 /// should assume that TheSelect is deleted if this returns true.  As such, they
13047 /// should return the appropriate thing (e.g. the node) back to the top-level of
13048 /// the DAG combiner loop to avoid it being looked at.
13049 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13050                                     SDValue RHS) {
13051
13052   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13053   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13054   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13055     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13056       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13057       SDValue Sqrt = RHS;
13058       ISD::CondCode CC;
13059       SDValue CmpLHS;
13060       const ConstantFPSDNode *NegZero = nullptr;
13061
13062       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13063         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13064         CmpLHS = TheSelect->getOperand(0);
13065         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13066       } else {
13067         // SELECT or VSELECT
13068         SDValue Cmp = TheSelect->getOperand(0);
13069         if (Cmp.getOpcode() == ISD::SETCC) {
13070           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13071           CmpLHS = Cmp.getOperand(0);
13072           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13073         }
13074       }
13075       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13076           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13077           CC == ISD::SETULT || CC == ISD::SETLT)) {
13078         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13079         CombineTo(TheSelect, Sqrt);
13080         return true;
13081       }
13082     }
13083   }
13084   // Cannot simplify select with vector condition
13085   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13086
13087   // If this is a select from two identical things, try to pull the operation
13088   // through the select.
13089   if (LHS.getOpcode() != RHS.getOpcode() ||
13090       !LHS.hasOneUse() || !RHS.hasOneUse())
13091     return false;
13092
13093   // If this is a load and the token chain is identical, replace the select
13094   // of two loads with a load through a select of the address to load from.
13095   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13096   // constants have been dropped into the constant pool.
13097   if (LHS.getOpcode() == ISD::LOAD) {
13098     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13099     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13100
13101     // Token chains must be identical.
13102     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13103         // Do not let this transformation reduce the number of volatile loads.
13104         LLD->isVolatile() || RLD->isVolatile() ||
13105         // FIXME: If either is a pre/post inc/dec load,
13106         // we'd need to split out the address adjustment.
13107         LLD->isIndexed() || RLD->isIndexed() ||
13108         // If this is an EXTLOAD, the VT's must match.
13109         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13110         // If this is an EXTLOAD, the kind of extension must match.
13111         (LLD->getExtensionType() != RLD->getExtensionType() &&
13112          // The only exception is if one of the extensions is anyext.
13113          LLD->getExtensionType() != ISD::EXTLOAD &&
13114          RLD->getExtensionType() != ISD::EXTLOAD) ||
13115         // FIXME: this discards src value information.  This is
13116         // over-conservative. It would be beneficial to be able to remember
13117         // both potential memory locations.  Since we are discarding
13118         // src value info, don't do the transformation if the memory
13119         // locations are not in the default address space.
13120         LLD->getPointerInfo().getAddrSpace() != 0 ||
13121         RLD->getPointerInfo().getAddrSpace() != 0 ||
13122         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13123                                       LLD->getBasePtr().getValueType()))
13124       return false;
13125
13126     // Check that the select condition doesn't reach either load.  If so,
13127     // folding this will induce a cycle into the DAG.  If not, this is safe to
13128     // xform, so create a select of the addresses.
13129     SDValue Addr;
13130     if (TheSelect->getOpcode() == ISD::SELECT) {
13131       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13132       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13133           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13134         return false;
13135       // The loads must not depend on one another.
13136       if (LLD->isPredecessorOf(RLD) ||
13137           RLD->isPredecessorOf(LLD))
13138         return false;
13139       Addr = DAG.getSelect(SDLoc(TheSelect),
13140                            LLD->getBasePtr().getValueType(),
13141                            TheSelect->getOperand(0), LLD->getBasePtr(),
13142                            RLD->getBasePtr());
13143     } else {  // Otherwise SELECT_CC
13144       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13145       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13146
13147       if ((LLD->hasAnyUseOfValue(1) &&
13148            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13149           (RLD->hasAnyUseOfValue(1) &&
13150            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13151         return false;
13152
13153       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13154                          LLD->getBasePtr().getValueType(),
13155                          TheSelect->getOperand(0),
13156                          TheSelect->getOperand(1),
13157                          LLD->getBasePtr(), RLD->getBasePtr(),
13158                          TheSelect->getOperand(4));
13159     }
13160
13161     SDValue Load;
13162     // It is safe to replace the two loads if they have different alignments,
13163     // but the new load must be the minimum (most restrictive) alignment of the
13164     // inputs.
13165     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13166     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13167     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13168       Load = DAG.getLoad(TheSelect->getValueType(0),
13169                          SDLoc(TheSelect),
13170                          // FIXME: Discards pointer and AA info.
13171                          LLD->getChain(), Addr, MachinePointerInfo(),
13172                          LLD->isVolatile(), LLD->isNonTemporal(),
13173                          isInvariant, Alignment);
13174     } else {
13175       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13176                             RLD->getExtensionType() : LLD->getExtensionType(),
13177                             SDLoc(TheSelect),
13178                             TheSelect->getValueType(0),
13179                             // FIXME: Discards pointer and AA info.
13180                             LLD->getChain(), Addr, MachinePointerInfo(),
13181                             LLD->getMemoryVT(), LLD->isVolatile(),
13182                             LLD->isNonTemporal(), isInvariant, Alignment);
13183     }
13184
13185     // Users of the select now use the result of the load.
13186     CombineTo(TheSelect, Load);
13187
13188     // Users of the old loads now use the new load's chain.  We know the
13189     // old-load value is dead now.
13190     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13191     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13192     return true;
13193   }
13194
13195   return false;
13196 }
13197
13198 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13199 /// where 'cond' is the comparison specified by CC.
13200 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13201                                       SDValue N2, SDValue N3,
13202                                       ISD::CondCode CC, bool NotExtCompare) {
13203   // (x ? y : y) -> y.
13204   if (N2 == N3) return N2;
13205
13206   EVT VT = N2.getValueType();
13207   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13208   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13209
13210   // Determine if the condition we're dealing with is constant
13211   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13212                               N0, N1, CC, DL, false);
13213   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13214
13215   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13216     // fold select_cc true, x, y -> x
13217     // fold select_cc false, x, y -> y
13218     return !SCCC->isNullValue() ? N2 : N3;
13219   }
13220
13221   // Check to see if we can simplify the select into an fabs node
13222   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13223     // Allow either -0.0 or 0.0
13224     if (CFP->getValueAPF().isZero()) {
13225       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13226       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13227           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13228           N2 == N3.getOperand(0))
13229         return DAG.getNode(ISD::FABS, DL, VT, N0);
13230
13231       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13232       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13233           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13234           N2.getOperand(0) == N3)
13235         return DAG.getNode(ISD::FABS, DL, VT, N3);
13236     }
13237   }
13238
13239   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13240   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13241   // in it.  This is a win when the constant is not otherwise available because
13242   // it replaces two constant pool loads with one.  We only do this if the FP
13243   // type is known to be legal, because if it isn't, then we are before legalize
13244   // types an we want the other legalization to happen first (e.g. to avoid
13245   // messing with soft float) and if the ConstantFP is not legal, because if
13246   // it is legal, we may not need to store the FP constant in a constant pool.
13247   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13248     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13249       if (TLI.isTypeLegal(N2.getValueType()) &&
13250           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13251                TargetLowering::Legal &&
13252            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13253            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13254           // If both constants have multiple uses, then we won't need to do an
13255           // extra load, they are likely around in registers for other users.
13256           (TV->hasOneUse() || FV->hasOneUse())) {
13257         Constant *Elts[] = {
13258           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13259           const_cast<ConstantFP*>(TV->getConstantFPValue())
13260         };
13261         Type *FPTy = Elts[0]->getType();
13262         const DataLayout &TD = *TLI.getDataLayout();
13263
13264         // Create a ConstantArray of the two constants.
13265         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13266         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13267                                             TD.getPrefTypeAlignment(FPTy));
13268         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13269
13270         // Get the offsets to the 0 and 1 element of the array so that we can
13271         // select between them.
13272         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13273         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13274         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13275
13276         SDValue Cond = DAG.getSetCC(DL,
13277                                     getSetCCResultType(N0.getValueType()),
13278                                     N0, N1, CC);
13279         AddToWorklist(Cond.getNode());
13280         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13281                                           Cond, One, Zero);
13282         AddToWorklist(CstOffset.getNode());
13283         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13284                             CstOffset);
13285         AddToWorklist(CPIdx.getNode());
13286         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13287                            MachinePointerInfo::getConstantPool(), false,
13288                            false, false, Alignment);
13289       }
13290     }
13291
13292   // Check to see if we can perform the "gzip trick", transforming
13293   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13294   if (N1C && isNullConstant(N3) && CC == ISD::SETLT &&
13295       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13296        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13297     EVT XType = N0.getValueType();
13298     EVT AType = N2.getValueType();
13299     if (XType.bitsGE(AType)) {
13300       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13301       // single-bit constant.
13302       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13303         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13304         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13305         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13306                                        getShiftAmountTy(N0.getValueType()));
13307         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13308                                     XType, N0, ShCt);
13309         AddToWorklist(Shift.getNode());
13310
13311         if (XType.bitsGT(AType)) {
13312           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13313           AddToWorklist(Shift.getNode());
13314         }
13315
13316         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13317       }
13318
13319       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13320                                   XType, N0,
13321                                   DAG.getConstant(XType.getSizeInBits() - 1,
13322                                                   SDLoc(N0),
13323                                          getShiftAmountTy(N0.getValueType())));
13324       AddToWorklist(Shift.getNode());
13325
13326       if (XType.bitsGT(AType)) {
13327         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13328         AddToWorklist(Shift.getNode());
13329       }
13330
13331       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13332     }
13333   }
13334
13335   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13336   // where y is has a single bit set.
13337   // A plaintext description would be, we can turn the SELECT_CC into an AND
13338   // when the condition can be materialized as an all-ones register.  Any
13339   // single bit-test can be materialized as an all-ones register with
13340   // shift-left and shift-right-arith.
13341   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13342       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13343     SDValue AndLHS = N0->getOperand(0);
13344     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13345     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13346       // Shift the tested bit over the sign bit.
13347       APInt AndMask = ConstAndRHS->getAPIntValue();
13348       SDValue ShlAmt =
13349         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13350                         getShiftAmountTy(AndLHS.getValueType()));
13351       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13352
13353       // Now arithmetic right shift it all the way over, so the result is either
13354       // all-ones, or zero.
13355       SDValue ShrAmt =
13356         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13357                         getShiftAmountTy(Shl.getValueType()));
13358       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13359
13360       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13361     }
13362   }
13363
13364   // fold select C, 16, 0 -> shl C, 4
13365   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13366       TLI.getBooleanContents(N0.getValueType()) ==
13367           TargetLowering::ZeroOrOneBooleanContent) {
13368
13369     // If the caller doesn't want us to simplify this into a zext of a compare,
13370     // don't do it.
13371     if (NotExtCompare && N2C->getAPIntValue() == 1)
13372       return SDValue();
13373
13374     // Get a SetCC of the condition
13375     // NOTE: Don't create a SETCC if it's not legal on this target.
13376     if (!LegalOperations ||
13377         TLI.isOperationLegal(ISD::SETCC,
13378           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13379       SDValue Temp, SCC;
13380       // cast from setcc result type to select result type
13381       if (LegalTypes) {
13382         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13383                             N0, N1, CC);
13384         if (N2.getValueType().bitsLT(SCC.getValueType()))
13385           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13386                                         N2.getValueType());
13387         else
13388           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13389                              N2.getValueType(), SCC);
13390       } else {
13391         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13392         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13393                            N2.getValueType(), SCC);
13394       }
13395
13396       AddToWorklist(SCC.getNode());
13397       AddToWorklist(Temp.getNode());
13398
13399       if (N2C->getAPIntValue() == 1)
13400         return Temp;
13401
13402       // shl setcc result by log2 n2c
13403       return DAG.getNode(
13404           ISD::SHL, DL, N2.getValueType(), Temp,
13405           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13406                           getShiftAmountTy(Temp.getValueType())));
13407     }
13408   }
13409
13410   // Check to see if this is the equivalent of setcc
13411   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13412   // otherwise, go ahead with the folds.
13413   if (0 && isNullConstant(N3) && N2C && (N2C->getAPIntValue() == 1ULL)) {
13414     EVT XType = N0.getValueType();
13415     if (!LegalOperations ||
13416         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13417       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13418       if (Res.getValueType() != VT)
13419         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13420       return Res;
13421     }
13422
13423     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13424     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13425         (!LegalOperations ||
13426          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13427       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13428       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13429                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13430                                          SDLoc(Ctlz),
13431                                        getShiftAmountTy(Ctlz.getValueType())));
13432     }
13433     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13434     if (isNullConstant(N1) && CC == ISD::SETGT) {
13435       SDLoc DL(N0);
13436       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13437                                   XType, DAG.getConstant(0, DL, XType), N0);
13438       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13439       return DAG.getNode(ISD::SRL, DL, XType,
13440                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13441                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13442                                          getShiftAmountTy(XType)));
13443     }
13444     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13445     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13446       SDLoc DL(N0);
13447       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13448                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13449                                          getShiftAmountTy(N0.getValueType())));
13450       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13451                                                                     XType));
13452     }
13453   }
13454
13455   // Check to see if this is an integer abs.
13456   // select_cc setg[te] X,  0,  X, -X ->
13457   // select_cc setgt    X, -1,  X, -X ->
13458   // select_cc setl[te] X,  0, -X,  X ->
13459   // select_cc setlt    X,  1, -X,  X ->
13460   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13461   if (N1C) {
13462     ConstantSDNode *SubC = nullptr;
13463     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13464          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13465         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13466       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13467     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13468               (N1C->isOne() && CC == ISD::SETLT)) &&
13469              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13470       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13471
13472     EVT XType = N0.getValueType();
13473     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13474       SDLoc DL(N0);
13475       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13476                                   N0,
13477                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13478                                          getShiftAmountTy(N0.getValueType())));
13479       SDValue Add = DAG.getNode(ISD::ADD, DL,
13480                                 XType, N0, Shift);
13481       AddToWorklist(Shift.getNode());
13482       AddToWorklist(Add.getNode());
13483       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13484     }
13485   }
13486
13487   return SDValue();
13488 }
13489
13490 /// This is a stub for TargetLowering::SimplifySetCC.
13491 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13492                                    SDValue N1, ISD::CondCode Cond,
13493                                    SDLoc DL, bool foldBooleans) {
13494   TargetLowering::DAGCombinerInfo
13495     DagCombineInfo(DAG, Level, false, this);
13496   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13497 }
13498
13499 /// Given an ISD::SDIV node expressing a divide by constant, return
13500 /// a DAG expression to select that will generate the same value by multiplying
13501 /// by a magic number.
13502 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13503 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13504   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13505   if (!C)
13506     return SDValue();
13507
13508   // Avoid division by zero.
13509   if (C->isNullValue())
13510     return SDValue();
13511
13512   std::vector<SDNode*> Built;
13513   SDValue S =
13514       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13515
13516   for (SDNode *N : Built)
13517     AddToWorklist(N);
13518   return S;
13519 }
13520
13521 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13522 /// DAG expression that will generate the same value by right shifting.
13523 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13524   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13525   if (!C)
13526     return SDValue();
13527
13528   // Avoid division by zero.
13529   if (C->isNullValue())
13530     return SDValue();
13531
13532   std::vector<SDNode *> Built;
13533   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13534
13535   for (SDNode *N : Built)
13536     AddToWorklist(N);
13537   return S;
13538 }
13539
13540 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13541 /// expression that will generate the same value by multiplying by a magic
13542 /// number.
13543 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13544 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13545   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13546   if (!C)
13547     return SDValue();
13548
13549   // Avoid division by zero.
13550   if (C->isNullValue())
13551     return SDValue();
13552
13553   std::vector<SDNode*> Built;
13554   SDValue S =
13555       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13556
13557   for (SDNode *N : Built)
13558     AddToWorklist(N);
13559   return S;
13560 }
13561
13562 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13563   if (Level >= AfterLegalizeDAG)
13564     return SDValue();
13565
13566   // Expose the DAG combiner to the target combiner implementations.
13567   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13568
13569   unsigned Iterations = 0;
13570   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13571     if (Iterations) {
13572       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13573       // For the reciprocal, we need to find the zero of the function:
13574       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13575       //     =>
13576       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13577       //     does not require additional intermediate precision]
13578       EVT VT = Op.getValueType();
13579       SDLoc DL(Op);
13580       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13581
13582       AddToWorklist(Est.getNode());
13583
13584       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13585       for (unsigned i = 0; i < Iterations; ++i) {
13586         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13587         AddToWorklist(NewEst.getNode());
13588
13589         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13590         AddToWorklist(NewEst.getNode());
13591
13592         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13593         AddToWorklist(NewEst.getNode());
13594
13595         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13596         AddToWorklist(Est.getNode());
13597       }
13598     }
13599     return Est;
13600   }
13601
13602   return SDValue();
13603 }
13604
13605 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13606 /// For the reciprocal sqrt, we need to find the zero of the function:
13607 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13608 ///     =>
13609 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13610 /// As a result, we precompute A/2 prior to the iteration loop.
13611 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13612                                           unsigned Iterations) {
13613   EVT VT = Arg.getValueType();
13614   SDLoc DL(Arg);
13615   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13616
13617   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13618   // this entire sequence requires only one FP constant.
13619   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13620   AddToWorklist(HalfArg.getNode());
13621
13622   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13623   AddToWorklist(HalfArg.getNode());
13624
13625   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13626   for (unsigned i = 0; i < Iterations; ++i) {
13627     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13628     AddToWorklist(NewEst.getNode());
13629
13630     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13631     AddToWorklist(NewEst.getNode());
13632
13633     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13634     AddToWorklist(NewEst.getNode());
13635
13636     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13637     AddToWorklist(Est.getNode());
13638   }
13639   return Est;
13640 }
13641
13642 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13643 /// For the reciprocal sqrt, we need to find the zero of the function:
13644 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13645 ///     =>
13646 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13647 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13648                                           unsigned Iterations) {
13649   EVT VT = Arg.getValueType();
13650   SDLoc DL(Arg);
13651   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13652   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13653
13654   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13655   for (unsigned i = 0; i < Iterations; ++i) {
13656     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13657     AddToWorklist(HalfEst.getNode());
13658
13659     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13660     AddToWorklist(Est.getNode());
13661
13662     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13663     AddToWorklist(Est.getNode());
13664
13665     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13666     AddToWorklist(Est.getNode());
13667
13668     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13669     AddToWorklist(Est.getNode());
13670   }
13671   return Est;
13672 }
13673
13674 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13675   if (Level >= AfterLegalizeDAG)
13676     return SDValue();
13677
13678   // Expose the DAG combiner to the target combiner implementations.
13679   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13680   unsigned Iterations = 0;
13681   bool UseOneConstNR = false;
13682   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13683     AddToWorklist(Est.getNode());
13684     if (Iterations) {
13685       Est = UseOneConstNR ?
13686         BuildRsqrtNROneConst(Op, Est, Iterations) :
13687         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13688     }
13689     return Est;
13690   }
13691
13692   return SDValue();
13693 }
13694
13695 /// Return true if base is a frame index, which is known not to alias with
13696 /// anything but itself.  Provides base object and offset as results.
13697 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13698                            const GlobalValue *&GV, const void *&CV) {
13699   // Assume it is a primitive operation.
13700   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13701
13702   // If it's an adding a simple constant then integrate the offset.
13703   if (Base.getOpcode() == ISD::ADD) {
13704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13705       Base = Base.getOperand(0);
13706       Offset += C->getZExtValue();
13707     }
13708   }
13709
13710   // Return the underlying GlobalValue, and update the Offset.  Return false
13711   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13712   // by multiple nodes with different offsets.
13713   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13714     GV = G->getGlobal();
13715     Offset += G->getOffset();
13716     return false;
13717   }
13718
13719   // Return the underlying Constant value, and update the Offset.  Return false
13720   // for ConstantSDNodes since the same constant pool entry may be represented
13721   // by multiple nodes with different offsets.
13722   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13723     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13724                                          : (const void *)C->getConstVal();
13725     Offset += C->getOffset();
13726     return false;
13727   }
13728   // If it's any of the following then it can't alias with anything but itself.
13729   return isa<FrameIndexSDNode>(Base);
13730 }
13731
13732 /// Return true if there is any possibility that the two addresses overlap.
13733 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13734   // If they are the same then they must be aliases.
13735   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13736
13737   // If they are both volatile then they cannot be reordered.
13738   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13739
13740   // Gather base node and offset information.
13741   SDValue Base1, Base2;
13742   int64_t Offset1, Offset2;
13743   const GlobalValue *GV1, *GV2;
13744   const void *CV1, *CV2;
13745   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13746                                       Base1, Offset1, GV1, CV1);
13747   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13748                                       Base2, Offset2, GV2, CV2);
13749
13750   // If they have a same base address then check to see if they overlap.
13751   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13752     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13753              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13754
13755   // It is possible for different frame indices to alias each other, mostly
13756   // when tail call optimization reuses return address slots for arguments.
13757   // To catch this case, look up the actual index of frame indices to compute
13758   // the real alias relationship.
13759   if (isFrameIndex1 && isFrameIndex2) {
13760     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13761     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13762     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13763     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13764              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13765   }
13766
13767   // Otherwise, if we know what the bases are, and they aren't identical, then
13768   // we know they cannot alias.
13769   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13770     return false;
13771
13772   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13773   // compared to the size and offset of the access, we may be able to prove they
13774   // do not alias.  This check is conservative for now to catch cases created by
13775   // splitting vector types.
13776   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13777       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13778       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13779        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13780       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13781     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13782     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13783
13784     // There is no overlap between these relatively aligned accesses of similar
13785     // size, return no alias.
13786     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13787         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13788       return false;
13789   }
13790
13791   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13792                    ? CombinerGlobalAA
13793                    : DAG.getSubtarget().useAA();
13794 #ifndef NDEBUG
13795   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13796       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13797     UseAA = false;
13798 #endif
13799   if (UseAA &&
13800       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13801     // Use alias analysis information.
13802     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13803                                  Op1->getSrcValueOffset());
13804     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13805         Op0->getSrcValueOffset() - MinOffset;
13806     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13807         Op1->getSrcValueOffset() - MinOffset;
13808     AliasAnalysis::AliasResult AAResult =
13809         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13810                                          Overlap1,
13811                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13812                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13813                                          Overlap2,
13814                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13815     if (AAResult == AliasAnalysis::NoAlias)
13816       return false;
13817   }
13818
13819   // Otherwise we have to assume they alias.
13820   return true;
13821 }
13822
13823 /// Walk up chain skipping non-aliasing memory nodes,
13824 /// looking for aliasing nodes and adding them to the Aliases vector.
13825 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13826                                    SmallVectorImpl<SDValue> &Aliases) {
13827   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13828   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13829
13830   // Get alias information for node.
13831   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13832
13833   // Starting off.
13834   Chains.push_back(OriginalChain);
13835   unsigned Depth = 0;
13836
13837   // Look at each chain and determine if it is an alias.  If so, add it to the
13838   // aliases list.  If not, then continue up the chain looking for the next
13839   // candidate.
13840   while (!Chains.empty()) {
13841     SDValue Chain = Chains.back();
13842     Chains.pop_back();
13843
13844     // For TokenFactor nodes, look at each operand and only continue up the
13845     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13846     // find more and revert to original chain since the xform is unlikely to be
13847     // profitable.
13848     //
13849     // FIXME: The depth check could be made to return the last non-aliasing
13850     // chain we found before we hit a tokenfactor rather than the original
13851     // chain.
13852     if (Depth > 6 || Aliases.size() == 2) {
13853       Aliases.clear();
13854       Aliases.push_back(OriginalChain);
13855       return;
13856     }
13857
13858     // Don't bother if we've been before.
13859     if (!Visited.insert(Chain.getNode()).second)
13860       continue;
13861
13862     switch (Chain.getOpcode()) {
13863     case ISD::EntryToken:
13864       // Entry token is ideal chain operand, but handled in FindBetterChain.
13865       break;
13866
13867     case ISD::LOAD:
13868     case ISD::STORE: {
13869       // Get alias information for Chain.
13870       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13871           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13872
13873       // If chain is alias then stop here.
13874       if (!(IsLoad && IsOpLoad) &&
13875           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13876         Aliases.push_back(Chain);
13877       } else {
13878         // Look further up the chain.
13879         Chains.push_back(Chain.getOperand(0));
13880         ++Depth;
13881       }
13882       break;
13883     }
13884
13885     case ISD::TokenFactor:
13886       // We have to check each of the operands of the token factor for "small"
13887       // token factors, so we queue them up.  Adding the operands to the queue
13888       // (stack) in reverse order maintains the original order and increases the
13889       // likelihood that getNode will find a matching token factor (CSE.)
13890       if (Chain.getNumOperands() > 16) {
13891         Aliases.push_back(Chain);
13892         break;
13893       }
13894       for (unsigned n = Chain.getNumOperands(); n;)
13895         Chains.push_back(Chain.getOperand(--n));
13896       ++Depth;
13897       break;
13898
13899     default:
13900       // For all other instructions we will just have to take what we can get.
13901       Aliases.push_back(Chain);
13902       break;
13903     }
13904   }
13905
13906   // We need to be careful here to also search for aliases through the
13907   // value operand of a store, etc. Consider the following situation:
13908   //   Token1 = ...
13909   //   L1 = load Token1, %52
13910   //   S1 = store Token1, L1, %51
13911   //   L2 = load Token1, %52+8
13912   //   S2 = store Token1, L2, %51+8
13913   //   Token2 = Token(S1, S2)
13914   //   L3 = load Token2, %53
13915   //   S3 = store Token2, L3, %52
13916   //   L4 = load Token2, %53+8
13917   //   S4 = store Token2, L4, %52+8
13918   // If we search for aliases of S3 (which loads address %52), and we look
13919   // only through the chain, then we'll miss the trivial dependence on L1
13920   // (which also loads from %52). We then might change all loads and
13921   // stores to use Token1 as their chain operand, which could result in
13922   // copying %53 into %52 before copying %52 into %51 (which should
13923   // happen first).
13924   //
13925   // The problem is, however, that searching for such data dependencies
13926   // can become expensive, and the cost is not directly related to the
13927   // chain depth. Instead, we'll rule out such configurations here by
13928   // insisting that we've visited all chain users (except for users
13929   // of the original chain, which is not necessary). When doing this,
13930   // we need to look through nodes we don't care about (otherwise, things
13931   // like register copies will interfere with trivial cases).
13932
13933   SmallVector<const SDNode *, 16> Worklist;
13934   for (const SDNode *N : Visited)
13935     if (N != OriginalChain.getNode())
13936       Worklist.push_back(N);
13937
13938   while (!Worklist.empty()) {
13939     const SDNode *M = Worklist.pop_back_val();
13940
13941     // We have already visited M, and want to make sure we've visited any uses
13942     // of M that we care about. For uses that we've not visisted, and don't
13943     // care about, queue them to the worklist.
13944
13945     for (SDNode::use_iterator UI = M->use_begin(),
13946          UIE = M->use_end(); UI != UIE; ++UI)
13947       if (UI.getUse().getValueType() == MVT::Other &&
13948           Visited.insert(*UI).second) {
13949         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13950           // We've not visited this use, and we care about it (it could have an
13951           // ordering dependency with the original node).
13952           Aliases.clear();
13953           Aliases.push_back(OriginalChain);
13954           return;
13955         }
13956
13957         // We've not visited this use, but we don't care about it. Mark it as
13958         // visited and enqueue it to the worklist.
13959         Worklist.push_back(*UI);
13960       }
13961   }
13962 }
13963
13964 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13965 /// (aliasing node.)
13966 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13967   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13968
13969   // Accumulate all the aliases to this node.
13970   GatherAllAliases(N, OldChain, Aliases);
13971
13972   // If no operands then chain to entry token.
13973   if (Aliases.size() == 0)
13974     return DAG.getEntryNode();
13975
13976   // If a single operand then chain to it.  We don't need to revisit it.
13977   if (Aliases.size() == 1)
13978     return Aliases[0];
13979
13980   // Construct a custom tailored token factor.
13981   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13982 }
13983
13984 /// This is the entry point for the file.
13985 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13986                            CodeGenOpt::Level OptLevel) {
13987   /// This is the main entry point to this class.
13988   DAGCombiner(*this, AA, OptLevel).Run(Level);
13989 }