[DAGCombine] Be more pedantic about use iteration in CombineToPreIndexedLoadStore
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitMGATHER(SDNode *N);
311     SDValue visitMSCATTER(SDNode *N);
312     SDValue visitFP_TO_FP16(SDNode *N);
313
314     SDValue visitFADDForFMACombine(SDNode *N);
315     SDValue visitFSUBForFMACombine(SDNode *N);
316
317     SDValue XformToShuffleWithZero(SDNode *N);
318     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
319
320     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
321
322     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326                              SDValue N3, ISD::CondCode CC,
327                              bool NotExtCompare = false);
328     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329                           SDLoc DL, bool foldBooleans = true);
330
331     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332                            SDValue &CC) const;
333     bool isOneUseSetCC(SDValue N) const;
334
335     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
336                                          unsigned HiOp);
337     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338     SDValue CombineExtLoad(SDNode *N);
339     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340     SDValue BuildSDIV(SDNode *N);
341     SDValue BuildSDIVPow2(SDNode *N);
342     SDValue BuildUDIV(SDNode *N);
343     SDValue BuildReciprocalEstimate(SDValue Op);
344     SDValue BuildRsqrtEstimate(SDValue Op);
345     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348                                bool DemandHighBits = true);
349     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351                               SDValue InnerPos, SDValue InnerNeg,
352                               unsigned PosOpcode, unsigned NegOpcode,
353                               SDLoc DL);
354     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355     SDValue ReduceLoadWidth(SDNode *N);
356     SDValue ReduceLoadOpStoreWidth(SDNode *N);
357     SDValue TransformFPLoadStorePair(SDNode *N);
358     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
360
361     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
362
363     /// Walk up chain skipping non-aliasing memory nodes,
364     /// looking for aliasing nodes and adding them to the Aliases vector.
365     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366                           SmallVectorImpl<SDValue> &Aliases);
367
368     /// Return true if there is any possibility that the two addresses overlap.
369     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
370
371     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372     /// chain (aliasing node.)
373     SDValue FindBetterChain(SDNode *N, SDValue Chain);
374
375     /// Holds a pointer to an LSBaseSDNode as well as information on where it
376     /// is located in a sequence of memory operations connected by a chain.
377     struct MemOpLink {
378       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380       // Ptr to the mem node.
381       LSBaseSDNode *MemNode;
382       // Offset from the base ptr.
383       int64_t OffsetFromBase;
384       // What is the sequence number of this mem node.
385       // Lowest mem operand in the DAG starts at zero.
386       unsigned SequenceNum;
387     };
388
389     /// This is a helper function for MergeConsecutiveStores. When the source
390     /// elements of the consecutive stores are all constants or all extracted
391     /// vector elements, try to merge them into one larger store.
392     /// \return True if a merged store was created.
393     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394                                          EVT MemVT, unsigned NumElem,
395                                          bool IsConstantSrc, bool UseVector);
396
397     /// Merge consecutive store operations into a wide store.
398     /// This optimization uses wide integers or vectors when possible.
399     /// \return True if some memory operations were changed.
400     bool MergeConsecutiveStores(StoreSDNode *N);
401
402     /// \brief Try to transform a truncation where C is a constant:
403     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
404     ///
405     /// \p N needs to be a truncation and its first operand an AND. Other
406     /// requirements are checked by the function (e.g. that trunc is
407     /// single-use) and if missed an empty SDValue is returned.
408     SDValue distributeTruncateThroughAnd(SDNode *N);
409
410   public:
411     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414       auto *F = DAG.getMachineFunction().getFunction();
415       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416                     F->hasFnAttribute(Attribute::MinSize);
417     }
418
419     /// Runs the dag combiner on all nodes in the work list
420     void Run(CombineLevel AtLevel);
421
422     SelectionDAG &getDAG() const { return DAG; }
423
424     /// Returns a type large enough to hold any valid shift amount - before type
425     /// legalization these can be huge.
426     EVT getShiftAmountTy(EVT LHSTy) {
427       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428       if (LHSTy.isVector())
429         return LHSTy;
430       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431                         : TLI.getPointerTy();
432     }
433
434     /// This method returns true if we are running before type legalization or
435     /// if the specified VT is legal.
436     bool isTypeLegal(const EVT &VT) {
437       if (!LegalTypes) return true;
438       return TLI.isTypeLegal(VT);
439     }
440
441     /// Convenience wrapper around TargetLowering::getSetCCResultType
442     EVT getSetCCResultType(EVT VT) const {
443       return TLI.getSetCCResultType(*DAG.getContext(), VT);
444     }
445   };
446 }
447
448
449 namespace {
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453   DAGCombiner &DC;
454 public:
455   explicit WorklistRemover(DAGCombiner &dc)
456     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
457
458   void NodeDeleted(SDNode *N, SDNode *E) override {
459     DC.removeFromWorklist(N);
460   }
461 };
462 }
463
464 //===----------------------------------------------------------------------===//
465 //  TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
467
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469   ((DAGCombiner*)DC)->AddToWorklist(N);
470 }
471
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473   ((DAGCombiner*)DC)->removeFromWorklist(N);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 }
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
484 }
485
486
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 }
491
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 }
496
497 //===----------------------------------------------------------------------===//
498 // Helper Functions
499 //===----------------------------------------------------------------------===//
500
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502   removeFromWorklist(N);
503
504   // If the operands of this node are only used by the node, they will now be
505   // dead. Make sure to re-visit them and recursively delete dead nodes.
506   for (const SDValue &Op : N->ops())
507     // For an operand generating multiple values, one of the values may
508     // become dead allowing further simplification (e.g. split index
509     // arithmetic from an indexed load).
510     if (Op->hasOneUse() || Op->getNumValues() > 1)
511       AddToWorklist(Op.getNode());
512
513   DAG.DeleteNode(N);
514 }
515
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520                                const TargetLowering &TLI,
521                                const TargetOptions *Options,
522                                unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return 2;
525
526   // Don't allow anything with multiple uses.
527   if (!Op.hasOneUse()) return 0;
528
529   // Don't recurse exponentially.
530   if (Depth > 6) return 0;
531
532   switch (Op.getOpcode()) {
533   default: return false;
534   case ISD::ConstantFP:
535     // Don't invert constant FP values after legalize.  The negated constant
536     // isn't necessarily legal.
537     return LegalOperations ? 0 : 1;
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     if (!Options->UnsafeFPMath) return 0;
541
542     // After operation legalization, it might not be legal to create new FSUBs.
543     if (LegalOperations &&
544         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
545       return 0;
546
547     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549                                     Options, Depth + 1))
550       return V;
551     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553                               Depth + 1);
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // fold (fneg (fsub A, B)) -> (fsub B, A)
559     return 1;
560
561   case ISD::FMUL:
562   case ISD::FDIV:
563     if (Options->HonorSignDependentRoundingFPMath()) return 0;
564
565     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572
573   case ISD::FP_EXTEND:
574   case ISD::FP_ROUND:
575   case ISD::FSIN:
576     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
577                               Depth + 1);
578   }
579 }
580
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583                                     bool LegalOperations, unsigned Depth = 0) {
584   const TargetOptions &Options = DAG.getTarget().Options;
585   // fneg is removable even if it has multiple uses.
586   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
587
588   // Don't allow anything with multiple uses.
589   assert(Op.hasOneUse() && "Unknown reuse!");
590
591   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592   switch (Op.getOpcode()) {
593   default: llvm_unreachable("Unknown code");
594   case ISD::ConstantFP: {
595     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596     V.changeSign();
597     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598   }
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     assert(Options.UnsafeFPMath);
602
603     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
606       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                          GetNegatedExpression(Op.getOperand(0), DAG,
608                                               LegalOperations, Depth+1),
609                          Op.getOperand(1));
610     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(1), DAG,
613                                             LegalOperations, Depth+1),
614                        Op.getOperand(0));
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fsub 0, B)) -> B
620     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621       if (N0CFP->getValueAPF().isZero())
622         return Op.getOperand(1);
623
624     // fold (fneg (fsub A, B)) -> (fsub B, A)
625     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626                        Op.getOperand(1), Op.getOperand(0));
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     assert(!Options.HonorSignDependentRoundingFPMath());
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
635       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                          GetNegatedExpression(Op.getOperand(0), DAG,
637                                               LegalOperations, Depth+1),
638                          Op.getOperand(1));
639
640     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(0),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1));
645
646   case ISD::FP_EXTEND:
647   case ISD::FSIN:
648     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649                        GetNegatedExpression(Op.getOperand(0), DAG,
650                                             LegalOperations, Depth+1));
651   case ISD::FP_ROUND:
652       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653                          GetNegatedExpression(Op.getOperand(0), DAG,
654                                               LegalOperations, Depth+1),
655                          Op.getOperand(1));
656   }
657 }
658
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665                                     SDValue &CC) const {
666   if (N.getOpcode() == ISD::SETCC) {
667     LHS = N.getOperand(0);
668     RHS = N.getOperand(1);
669     CC  = N.getOperand(2);
670     return true;
671   }
672
673   if (N.getOpcode() != ISD::SELECT_CC ||
674       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676     return false;
677
678   if (TLI.getBooleanContents(N.getValueType()) ==
679       TargetLowering::UndefinedBooleanContent)
680     return false;
681
682   LHS = N.getOperand(0);
683   RHS = N.getOperand(1);
684   CC  = N.getOperand(4);
685   return true;
686 }
687
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
692   SDValue N0, N1, N2;
693   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
694     return true;
695   return false;
696 }
697
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702   if (!C)
703     return false;
704
705   APInt SplatUndef;
706   unsigned SplatBitSize;
707   bool HasAnyUndefs;
708   EVT EltVT = N->getValueType(0).getVectorElementType();
709   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710                              HasAnyUndefs) &&
711           EltVT.getSizeInBits() >= SplatBitSize);
712 }
713
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717   if (isa<ConstantSDNode>(N))
718     return N.getNode();
719   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720     return N.getNode();
721   return nullptr;
722 }
723
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MGATHER:            return visitMGATHER(N);
1388   case ISD::MLOAD:              return visitMLOAD(N);
1389   case ISD::MSCATTER:           return visitMSCATTER(N);
1390   case ISD::MSTORE:             return visitMSTORE(N);
1391   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397   SDValue RV = visit(N);
1398
1399   // If nothing happened, try a target-specific DAG combine.
1400   if (!RV.getNode()) {
1401     assert(N->getOpcode() != ISD::DELETED_NODE &&
1402            "Node was deleted but visit returned NULL!");
1403
1404     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407       // Expose the DAG combiner to the target combiner impls.
1408       TargetLowering::DAGCombinerInfo
1409         DagCombineInfo(DAG, Level, false, this);
1410
1411       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412     }
1413   }
1414
1415   // If nothing happened still, try promoting the operation.
1416   if (!RV.getNode()) {
1417     switch (N->getOpcode()) {
1418     default: break;
1419     case ISD::ADD:
1420     case ISD::SUB:
1421     case ISD::MUL:
1422     case ISD::AND:
1423     case ISD::OR:
1424     case ISD::XOR:
1425       RV = PromoteIntBinOp(SDValue(N, 0));
1426       break;
1427     case ISD::SHL:
1428     case ISD::SRA:
1429     case ISD::SRL:
1430       RV = PromoteIntShiftOp(SDValue(N, 0));
1431       break;
1432     case ISD::SIGN_EXTEND:
1433     case ISD::ZERO_EXTEND:
1434     case ISD::ANY_EXTEND:
1435       RV = PromoteExtend(SDValue(N, 0));
1436       break;
1437     case ISD::LOAD:
1438       if (PromoteLoad(SDValue(N, 0)))
1439         RV = SDValue(N, 0);
1440       break;
1441     }
1442   }
1443
1444   // If N is a commutative binary node, try commuting it to enable more
1445   // sdisel CSE.
1446   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447       N->getNumValues() == 1) {
1448     SDValue N0 = N->getOperand(0);
1449     SDValue N1 = N->getOperand(1);
1450
1451     // Constant operands are canonicalized to RHS.
1452     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453       SDValue Ops[] = {N1, N0};
1454       SDNode *CSENode;
1455       if (const BinaryWithFlagsSDNode *BinNode =
1456               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458                                       BinNode->Flags.hasNoUnsignedWrap(),
1459                                       BinNode->Flags.hasNoSignedWrap(),
1460                                       BinNode->Flags.hasExact());
1461       } else {
1462         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463       }
1464       if (CSENode)
1465         return SDValue(CSENode, 0);
1466     }
1467   }
1468
1469   return RV;
1470 }
1471
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1473 /// sd operand.
1474 static SDValue getInputChainForNode(SDNode *N) {
1475   if (unsigned NumOps = N->getNumOperands()) {
1476     if (N->getOperand(0).getValueType() == MVT::Other)
1477       return N->getOperand(0);
1478     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479       return N->getOperand(NumOps-1);
1480     for (unsigned i = 1; i < NumOps-1; ++i)
1481       if (N->getOperand(i).getValueType() == MVT::Other)
1482         return N->getOperand(i);
1483   }
1484   return SDValue();
1485 }
1486
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488   // If N has two operands, where one has an input chain equal to the other,
1489   // the 'other' chain is redundant.
1490   if (N->getNumOperands() == 2) {
1491     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492       return N->getOperand(0);
1493     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494       return N->getOperand(1);
1495   }
1496
1497   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1498   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1499   SmallPtrSet<SDNode*, 16> SeenOps;
1500   bool Changed = false;             // If we should replace this token factor.
1501
1502   // Start out with this token factor.
1503   TFs.push_back(N);
1504
1505   // Iterate through token factors.  The TFs grows when new token factors are
1506   // encountered.
1507   for (unsigned i = 0; i < TFs.size(); ++i) {
1508     SDNode *TF = TFs[i];
1509
1510     // Check each of the operands.
1511     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512       SDValue Op = TF->getOperand(i);
1513
1514       switch (Op.getOpcode()) {
1515       case ISD::EntryToken:
1516         // Entry tokens don't need to be added to the list. They are
1517         // redundant.
1518         Changed = true;
1519         break;
1520
1521       case ISD::TokenFactor:
1522         if (Op.hasOneUse() &&
1523             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524           // Queue up for processing.
1525           TFs.push_back(Op.getNode());
1526           // Clean up in case the token factor is removed.
1527           AddToWorklist(Op.getNode());
1528           Changed = true;
1529           break;
1530         }
1531         // Fall thru
1532
1533       default:
1534         // Only add if it isn't already in the list.
1535         if (SeenOps.insert(Op.getNode()).second)
1536           Ops.push_back(Op);
1537         else
1538           Changed = true;
1539         break;
1540       }
1541     }
1542   }
1543
1544   SDValue Result;
1545
1546   // If we've changed things around then replace token factor.
1547   if (Changed) {
1548     if (Ops.empty()) {
1549       // The entry token is the only possible outcome.
1550       Result = DAG.getEntryNode();
1551     } else {
1552       // New and improved token factor.
1553       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1554     }
1555
1556     // Add users to worklist if AA is enabled, since it may introduce
1557     // a lot of new chained token factors while removing memory deps.
1558     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559       : DAG.getSubtarget().useAA();
1560     return CombineTo(N, Result, UseAA /*add to worklist*/);
1561   }
1562
1563   return Result;
1564 }
1565
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568   WorklistRemover DeadNodes(*this);
1569   // Replacing results may cause a different MERGE_VALUES to suddenly
1570   // be CSE'd with N, and carry its uses with it. Iterate until no
1571   // uses remain, to ensure that the node can be safely deleted.
1572   // First add the users of this node to the work list so that they
1573   // can be tried again once they have new operands.
1574   AddUsersToWorklist(N);
1575   do {
1576     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578   } while (!N->use_empty());
1579   deleteAndRecombine(N);
1580   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1581 }
1582
1583 SDValue DAGCombiner::visitADD(SDNode *N) {
1584   SDValue N0 = N->getOperand(0);
1585   SDValue N1 = N->getOperand(1);
1586   EVT VT = N0.getValueType();
1587
1588   // fold vector ops
1589   if (VT.isVector()) {
1590     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1591       return FoldedVOp;
1592
1593     // fold (add x, 0) -> x, vector edition
1594     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1595       return N0;
1596     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1597       return N1;
1598   }
1599
1600   // fold (add x, undef) -> undef
1601   if (N0.getOpcode() == ISD::UNDEF)
1602     return N0;
1603   if (N1.getOpcode() == ISD::UNDEF)
1604     return N1;
1605   // fold (add c1, c2) -> c1+c2
1606   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1607   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1608   if (N0C && N1C)
1609     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1610   // canonicalize constant to RHS
1611   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1612      !isConstantIntBuildVectorOrConstantInt(N1))
1613     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1614   // fold (add x, 0) -> x
1615   if (N1C && N1C->isNullValue())
1616     return N0;
1617   // fold (add Sym, c) -> Sym+c
1618   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1619     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1620         GA->getOpcode() == ISD::GlobalAddress)
1621       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1622                                   GA->getOffset() +
1623                                     (uint64_t)N1C->getSExtValue());
1624   // fold ((c1-A)+c2) -> (c1+c2)-A
1625   if (N1C && N0.getOpcode() == ISD::SUB)
1626     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1627       SDLoc DL(N);
1628       return DAG.getNode(ISD::SUB, DL, VT,
1629                          DAG.getConstant(N1C->getAPIntValue()+
1630                                          N0C->getAPIntValue(), DL, VT),
1631                          N0.getOperand(1));
1632     }
1633   // reassociate add
1634   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1635     return RADD;
1636   // fold ((0-A) + B) -> B-A
1637   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1638       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1639     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1640   // fold (A + (0-B)) -> A-B
1641   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1642       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1643     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1644   // fold (A+(B-A)) -> B
1645   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1646     return N1.getOperand(0);
1647   // fold ((B-A)+A) -> B
1648   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1649     return N0.getOperand(0);
1650   // fold (A+(B-(A+C))) to (B-C)
1651   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1652       N0 == N1.getOperand(1).getOperand(0))
1653     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1654                        N1.getOperand(1).getOperand(1));
1655   // fold (A+(B-(C+A))) to (B-C)
1656   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1657       N0 == N1.getOperand(1).getOperand(1))
1658     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1659                        N1.getOperand(1).getOperand(0));
1660   // fold (A+((B-A)+or-C)) to (B+or-C)
1661   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1662       N1.getOperand(0).getOpcode() == ISD::SUB &&
1663       N0 == N1.getOperand(0).getOperand(1))
1664     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1665                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1666
1667   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1668   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1669     SDValue N00 = N0.getOperand(0);
1670     SDValue N01 = N0.getOperand(1);
1671     SDValue N10 = N1.getOperand(0);
1672     SDValue N11 = N1.getOperand(1);
1673
1674     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1675       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1676                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1677                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1678   }
1679
1680   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1681     return SDValue(N, 0);
1682
1683   // fold (a+b) -> (a|b) iff a and b share no bits.
1684   if (VT.isInteger() && !VT.isVector()) {
1685     APInt LHSZero, LHSOne;
1686     APInt RHSZero, RHSOne;
1687     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1688
1689     if (LHSZero.getBoolValue()) {
1690       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1691
1692       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1693       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1694       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1695         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1696           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1697       }
1698     }
1699   }
1700
1701   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1702   if (N1.getOpcode() == ISD::SHL &&
1703       N1.getOperand(0).getOpcode() == ISD::SUB)
1704     if (ConstantSDNode *C =
1705           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1706       if (C->getAPIntValue() == 0)
1707         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1708                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709                                        N1.getOperand(0).getOperand(1),
1710                                        N1.getOperand(1)));
1711   if (N0.getOpcode() == ISD::SHL &&
1712       N0.getOperand(0).getOpcode() == ISD::SUB)
1713     if (ConstantSDNode *C =
1714           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1715       if (C->getAPIntValue() == 0)
1716         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1717                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1718                                        N0.getOperand(0).getOperand(1),
1719                                        N0.getOperand(1)));
1720
1721   if (N1.getOpcode() == ISD::AND) {
1722     SDValue AndOp0 = N1.getOperand(0);
1723     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1724     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1725     unsigned DestBits = VT.getScalarType().getSizeInBits();
1726
1727     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1728     // and similar xforms where the inner op is either ~0 or 0.
1729     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1730       SDLoc DL(N);
1731       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1732     }
1733   }
1734
1735   // add (sext i1), X -> sub X, (zext i1)
1736   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1737       N0.getOperand(0).getValueType() == MVT::i1 &&
1738       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1739     SDLoc DL(N);
1740     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1741     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1742   }
1743
1744   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1745   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1746     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1747     if (TN->getVT() == MVT::i1) {
1748       SDLoc DL(N);
1749       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1750                                  DAG.getConstant(1, DL, VT));
1751       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1752     }
1753   }
1754
1755   return SDValue();
1756 }
1757
1758 SDValue DAGCombiner::visitADDC(SDNode *N) {
1759   SDValue N0 = N->getOperand(0);
1760   SDValue N1 = N->getOperand(1);
1761   EVT VT = N0.getValueType();
1762
1763   // If the flag result is dead, turn this into an ADD.
1764   if (!N->hasAnyUseOfValue(1))
1765     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1766                      DAG.getNode(ISD::CARRY_FALSE,
1767                                  SDLoc(N), MVT::Glue));
1768
1769   // canonicalize constant to RHS.
1770   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1771   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1772   if (N0C && !N1C)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1774
1775   // fold (addc x, 0) -> x + no carry out
1776   if (N1C && N1C->isNullValue())
1777     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1778                                         SDLoc(N), MVT::Glue));
1779
1780   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1781   APInt LHSZero, LHSOne;
1782   APInt RHSZero, RHSOne;
1783   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1784
1785   if (LHSZero.getBoolValue()) {
1786     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1787
1788     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1789     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1790     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1791       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1792                        DAG.getNode(ISD::CARRY_FALSE,
1793                                    SDLoc(N), MVT::Glue));
1794   }
1795
1796   return SDValue();
1797 }
1798
1799 SDValue DAGCombiner::visitADDE(SDNode *N) {
1800   SDValue N0 = N->getOperand(0);
1801   SDValue N1 = N->getOperand(1);
1802   SDValue CarryIn = N->getOperand(2);
1803
1804   // canonicalize constant to RHS
1805   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1806   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1807   if (N0C && !N1C)
1808     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1809                        N1, N0, CarryIn);
1810
1811   // fold (adde x, y, false) -> (addc x, y)
1812   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1813     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1814
1815   return SDValue();
1816 }
1817
1818 // Since it may not be valid to emit a fold to zero for vector initializers
1819 // check if we can before folding.
1820 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1821                              SelectionDAG &DAG,
1822                              bool LegalOperations, bool LegalTypes) {
1823   if (!VT.isVector())
1824     return DAG.getConstant(0, DL, VT);
1825   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1826     return DAG.getConstant(0, DL, VT);
1827   return SDValue();
1828 }
1829
1830 SDValue DAGCombiner::visitSUB(SDNode *N) {
1831   SDValue N0 = N->getOperand(0);
1832   SDValue N1 = N->getOperand(1);
1833   EVT VT = N0.getValueType();
1834
1835   // fold vector ops
1836   if (VT.isVector()) {
1837     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1838       return FoldedVOp;
1839
1840     // fold (sub x, 0) -> x, vector edition
1841     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1842       return N0;
1843   }
1844
1845   // fold (sub x, x) -> 0
1846   // FIXME: Refactor this and xor and other similar operations together.
1847   if (N0 == N1)
1848     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1849   // fold (sub c1, c2) -> c1-c2
1850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1852   if (N0C && N1C)
1853     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1854   // fold (sub x, c) -> (add x, -c)
1855   if (N1C) {
1856     SDLoc DL(N);
1857     return DAG.getNode(ISD::ADD, DL, VT, N0,
1858                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1859   }
1860   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1861   if (N0C && N0C->isAllOnesValue())
1862     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1863   // fold A-(A-B) -> B
1864   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1865     return N1.getOperand(1);
1866   // fold (A+B)-A -> B
1867   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1868     return N0.getOperand(1);
1869   // fold (A+B)-B -> A
1870   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1871     return N0.getOperand(0);
1872   // fold C2-(A+C1) -> (C2-C1)-A
1873   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1874     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1875   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1876     SDLoc DL(N);
1877     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1878                                    DL, VT);
1879     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1880                        N1.getOperand(0));
1881   }
1882   // fold ((A+(B+or-C))-B) -> A+or-C
1883   if (N0.getOpcode() == ISD::ADD &&
1884       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1885        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1886       N0.getOperand(1).getOperand(0) == N1)
1887     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1888                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1889   // fold ((A+(C+B))-B) -> A+C
1890   if (N0.getOpcode() == ISD::ADD &&
1891       N0.getOperand(1).getOpcode() == ISD::ADD &&
1892       N0.getOperand(1).getOperand(1) == N1)
1893     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1894                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1895   // fold ((A-(B-C))-C) -> A-B
1896   if (N0.getOpcode() == ISD::SUB &&
1897       N0.getOperand(1).getOpcode() == ISD::SUB &&
1898       N0.getOperand(1).getOperand(1) == N1)
1899     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1900                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1901
1902   // If either operand of a sub is undef, the result is undef
1903   if (N0.getOpcode() == ISD::UNDEF)
1904     return N0;
1905   if (N1.getOpcode() == ISD::UNDEF)
1906     return N1;
1907
1908   // If the relocation model supports it, consider symbol offsets.
1909   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1910     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1911       // fold (sub Sym, c) -> Sym-c
1912       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1913         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1914                                     GA->getOffset() -
1915                                       (uint64_t)N1C->getSExtValue());
1916       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1917       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1918         if (GA->getGlobal() == GB->getGlobal())
1919           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1920                                  SDLoc(N), VT);
1921     }
1922
1923   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1924   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1925     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1926     if (TN->getVT() == MVT::i1) {
1927       SDLoc DL(N);
1928       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1929                                  DAG.getConstant(1, DL, VT));
1930       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1931     }
1932   }
1933
1934   return SDValue();
1935 }
1936
1937 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1938   SDValue N0 = N->getOperand(0);
1939   SDValue N1 = N->getOperand(1);
1940   EVT VT = N0.getValueType();
1941
1942   // If the flag result is dead, turn this into an SUB.
1943   if (!N->hasAnyUseOfValue(1))
1944     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1945                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1946                                  MVT::Glue));
1947
1948   // fold (subc x, x) -> 0 + no borrow
1949   if (N0 == N1) {
1950     SDLoc DL(N);
1951     return CombineTo(N, DAG.getConstant(0, DL, VT),
1952                      DAG.getNode(ISD::CARRY_FALSE, DL,
1953                                  MVT::Glue));
1954   }
1955
1956   // fold (subc x, 0) -> x + no borrow
1957   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1958   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1959   if (N1C && N1C->isNullValue())
1960     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1961                                         MVT::Glue));
1962
1963   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1964   if (N0C && N0C->isAllOnesValue())
1965     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1966                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1967                                  MVT::Glue));
1968
1969   return SDValue();
1970 }
1971
1972 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   SDValue CarryIn = N->getOperand(2);
1976
1977   // fold (sube x, y, false) -> (subc x, y)
1978   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1979     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1980
1981   return SDValue();
1982 }
1983
1984 SDValue DAGCombiner::visitMUL(SDNode *N) {
1985   SDValue N0 = N->getOperand(0);
1986   SDValue N1 = N->getOperand(1);
1987   EVT VT = N0.getValueType();
1988
1989   // fold (mul x, undef) -> 0
1990   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1991     return DAG.getConstant(0, SDLoc(N), VT);
1992
1993   bool N0IsConst = false;
1994   bool N1IsConst = false;
1995   APInt ConstValue0, ConstValue1;
1996   // fold vector ops
1997   if (VT.isVector()) {
1998     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1999       return FoldedVOp;
2000
2001     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2002     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2003   } else {
2004     N0IsConst = isa<ConstantSDNode>(N0);
2005     if (N0IsConst)
2006       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2007     N1IsConst = isa<ConstantSDNode>(N1);
2008     if (N1IsConst)
2009       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2010   }
2011
2012   // fold (mul c1, c2) -> c1*c2
2013   if (N0IsConst && N1IsConst)
2014     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2015                                       N0.getNode(), N1.getNode());
2016
2017   // canonicalize constant to RHS (vector doesn't have to splat)
2018   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2019      !isConstantIntBuildVectorOrConstantInt(N1))
2020     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2021   // fold (mul x, 0) -> 0
2022   if (N1IsConst && ConstValue1 == 0)
2023     return N1;
2024   // We require a splat of the entire scalar bit width for non-contiguous
2025   // bit patterns.
2026   bool IsFullSplat =
2027     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2028   // fold (mul x, 1) -> x
2029   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2030     return N0;
2031   // fold (mul x, -1) -> 0-x
2032   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2033     SDLoc DL(N);
2034     return DAG.getNode(ISD::SUB, DL, VT,
2035                        DAG.getConstant(0, DL, VT), N0);
2036   }
2037   // fold (mul x, (1 << c)) -> x << c
2038   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2039     SDLoc DL(N);
2040     return DAG.getNode(ISD::SHL, DL, VT, N0,
2041                        DAG.getConstant(ConstValue1.logBase2(), DL,
2042                                        getShiftAmountTy(N0.getValueType())));
2043   }
2044   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2045   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2046     unsigned Log2Val = (-ConstValue1).logBase2();
2047     SDLoc DL(N);
2048     // FIXME: If the input is something that is easily negated (e.g. a
2049     // single-use add), we should put the negate there.
2050     return DAG.getNode(ISD::SUB, DL, VT,
2051                        DAG.getConstant(0, DL, VT),
2052                        DAG.getNode(ISD::SHL, DL, VT, N0,
2053                             DAG.getConstant(Log2Val, DL,
2054                                       getShiftAmountTy(N0.getValueType()))));
2055   }
2056
2057   APInt Val;
2058   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2059   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2060       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2061                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2062     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2063                              N1, N0.getOperand(1));
2064     AddToWorklist(C3.getNode());
2065     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2066                        N0.getOperand(0), C3);
2067   }
2068
2069   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2070   // use.
2071   {
2072     SDValue Sh(nullptr,0), Y(nullptr,0);
2073     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2074     if (N0.getOpcode() == ISD::SHL &&
2075         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2076                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2077         N0.getNode()->hasOneUse()) {
2078       Sh = N0; Y = N1;
2079     } else if (N1.getOpcode() == ISD::SHL &&
2080                isa<ConstantSDNode>(N1.getOperand(1)) &&
2081                N1.getNode()->hasOneUse()) {
2082       Sh = N1; Y = N0;
2083     }
2084
2085     if (Sh.getNode()) {
2086       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2087                                 Sh.getOperand(0), Y);
2088       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2089                          Mul, Sh.getOperand(1));
2090     }
2091   }
2092
2093   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2094   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2095       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2096                      isa<ConstantSDNode>(N0.getOperand(1))))
2097     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2098                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2099                                    N0.getOperand(0), N1),
2100                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2101                                    N0.getOperand(1), N1));
2102
2103   // reassociate mul
2104   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2105     return RMUL;
2106
2107   return SDValue();
2108 }
2109
2110 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2111   SDValue N0 = N->getOperand(0);
2112   SDValue N1 = N->getOperand(1);
2113   EVT VT = N->getValueType(0);
2114
2115   // fold vector ops
2116   if (VT.isVector())
2117     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2118       return FoldedVOp;
2119
2120   // fold (sdiv c1, c2) -> c1/c2
2121   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123   if (N0C && N1C && !N1C->isNullValue())
2124     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2125   // fold (sdiv X, 1) -> X
2126   if (N1C && N1C->getAPIntValue() == 1LL)
2127     return N0;
2128   // fold (sdiv X, -1) -> 0-X
2129   if (N1C && N1C->isAllOnesValue()) {
2130     SDLoc DL(N);
2131     return DAG.getNode(ISD::SUB, DL, VT,
2132                        DAG.getConstant(0, DL, VT), N0);
2133   }
2134   // If we know the sign bits of both operands are zero, strength reduce to a
2135   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2136   if (!VT.isVector()) {
2137     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2138       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2139                          N0, N1);
2140   }
2141
2142   // fold (sdiv X, pow2) -> simple ops after legalize
2143   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2144                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2145     // If dividing by powers of two is cheap, then don't perform the following
2146     // fold.
2147     if (TLI.isPow2SDivCheap())
2148       return SDValue();
2149
2150     // Target-specific implementation of sdiv x, pow2.
2151     SDValue Res = BuildSDIVPow2(N);
2152     if (Res.getNode())
2153       return Res;
2154
2155     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2156     SDLoc DL(N);
2157
2158     // Splat the sign bit into the register
2159     SDValue SGN =
2160         DAG.getNode(ISD::SRA, DL, VT, N0,
2161                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2162                                     getShiftAmountTy(N0.getValueType())));
2163     AddToWorklist(SGN.getNode());
2164
2165     // Add (N0 < 0) ? abs2 - 1 : 0;
2166     SDValue SRL =
2167         DAG.getNode(ISD::SRL, DL, VT, SGN,
2168                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2169                                     getShiftAmountTy(SGN.getValueType())));
2170     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2171     AddToWorklist(SRL.getNode());
2172     AddToWorklist(ADD.getNode());    // Divide by pow2
2173     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2174                   DAG.getConstant(lg2, DL,
2175                                   getShiftAmountTy(ADD.getValueType())));
2176
2177     // If we're dividing by a positive value, we're done.  Otherwise, we must
2178     // negate the result.
2179     if (N1C->getAPIntValue().isNonNegative())
2180       return SRA;
2181
2182     AddToWorklist(SRA.getNode());
2183     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2184   }
2185
2186   // If integer divide is expensive and we satisfy the requirements, emit an
2187   // alternate sequence.
2188   if (N1C && !TLI.isIntDivCheap()) {
2189     SDValue Op = BuildSDIV(N);
2190     if (Op.getNode()) return Op;
2191   }
2192
2193   // undef / X -> 0
2194   if (N0.getOpcode() == ISD::UNDEF)
2195     return DAG.getConstant(0, SDLoc(N), VT);
2196   // X / undef -> undef
2197   if (N1.getOpcode() == ISD::UNDEF)
2198     return N1;
2199
2200   return SDValue();
2201 }
2202
2203 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2204   SDValue N0 = N->getOperand(0);
2205   SDValue N1 = N->getOperand(1);
2206   EVT VT = N->getValueType(0);
2207
2208   // fold vector ops
2209   if (VT.isVector())
2210     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2211       return FoldedVOp;
2212
2213   // fold (udiv c1, c2) -> c1/c2
2214   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2215   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2216   if (N0C && N1C && !N1C->isNullValue())
2217     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2218   // fold (udiv x, (1 << c)) -> x >>u c
2219   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2220     SDLoc DL(N);
2221     return DAG.getNode(ISD::SRL, DL, VT, N0,
2222                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2223                                        getShiftAmountTy(N0.getValueType())));
2224   }
2225   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2226   if (N1.getOpcode() == ISD::SHL) {
2227     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2228       if (SHC->getAPIntValue().isPowerOf2()) {
2229         EVT ADDVT = N1.getOperand(1).getValueType();
2230         SDLoc DL(N);
2231         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2232                                   N1.getOperand(1),
2233                                   DAG.getConstant(SHC->getAPIntValue()
2234                                                                   .logBase2(),
2235                                                   DL, ADDVT));
2236         AddToWorklist(Add.getNode());
2237         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2238       }
2239     }
2240   }
2241   // fold (udiv x, c) -> alternate
2242   if (N1C && !TLI.isIntDivCheap()) {
2243     SDValue Op = BuildUDIV(N);
2244     if (Op.getNode()) return Op;
2245   }
2246
2247   // undef / X -> 0
2248   if (N0.getOpcode() == ISD::UNDEF)
2249     return DAG.getConstant(0, SDLoc(N), VT);
2250   // X / undef -> undef
2251   if (N1.getOpcode() == ISD::UNDEF)
2252     return N1;
2253
2254   return SDValue();
2255 }
2256
2257 SDValue DAGCombiner::visitSREM(SDNode *N) {
2258   SDValue N0 = N->getOperand(0);
2259   SDValue N1 = N->getOperand(1);
2260   EVT VT = N->getValueType(0);
2261
2262   // fold (srem c1, c2) -> c1%c2
2263   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2264   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2265   if (N0C && N1C && !N1C->isNullValue())
2266     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2267   // If we know the sign bits of both operands are zero, strength reduce to a
2268   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2269   if (!VT.isVector()) {
2270     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2271       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2272   }
2273
2274   // If X/C can be simplified by the division-by-constant logic, lower
2275   // X%C to the equivalent of X-X/C*C.
2276   if (N1C && !N1C->isNullValue()) {
2277     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2278     AddToWorklist(Div.getNode());
2279     SDValue OptimizedDiv = combine(Div.getNode());
2280     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2281       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2282                                 OptimizedDiv, N1);
2283       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2284       AddToWorklist(Mul.getNode());
2285       return Sub;
2286     }
2287   }
2288
2289   // undef % X -> 0
2290   if (N0.getOpcode() == ISD::UNDEF)
2291     return DAG.getConstant(0, SDLoc(N), VT);
2292   // X % undef -> undef
2293   if (N1.getOpcode() == ISD::UNDEF)
2294     return N1;
2295
2296   return SDValue();
2297 }
2298
2299 SDValue DAGCombiner::visitUREM(SDNode *N) {
2300   SDValue N0 = N->getOperand(0);
2301   SDValue N1 = N->getOperand(1);
2302   EVT VT = N->getValueType(0);
2303
2304   // fold (urem c1, c2) -> c1%c2
2305   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2307   if (N0C && N1C && !N1C->isNullValue())
2308     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2309   // fold (urem x, pow2) -> (and x, pow2-1)
2310   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2311     SDLoc DL(N);
2312     return DAG.getNode(ISD::AND, DL, VT, N0,
2313                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2314   }
2315   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2316   if (N1.getOpcode() == ISD::SHL) {
2317     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2318       if (SHC->getAPIntValue().isPowerOf2()) {
2319         SDLoc DL(N);
2320         SDValue Add =
2321           DAG.getNode(ISD::ADD, DL, VT, N1,
2322                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2323                                  VT));
2324         AddToWorklist(Add.getNode());
2325         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2326       }
2327     }
2328   }
2329
2330   // If X/C can be simplified by the division-by-constant logic, lower
2331   // X%C to the equivalent of X-X/C*C.
2332   if (N1C && !N1C->isNullValue()) {
2333     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2334     AddToWorklist(Div.getNode());
2335     SDValue OptimizedDiv = combine(Div.getNode());
2336     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2338                                 OptimizedDiv, N1);
2339       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340       AddToWorklist(Mul.getNode());
2341       return Sub;
2342     }
2343   }
2344
2345   // undef % X -> 0
2346   if (N0.getOpcode() == ISD::UNDEF)
2347     return DAG.getConstant(0, SDLoc(N), VT);
2348   // X % undef -> undef
2349   if (N1.getOpcode() == ISD::UNDEF)
2350     return N1;
2351
2352   return SDValue();
2353 }
2354
2355 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2356   SDValue N0 = N->getOperand(0);
2357   SDValue N1 = N->getOperand(1);
2358   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2359   EVT VT = N->getValueType(0);
2360   SDLoc DL(N);
2361
2362   // fold (mulhs x, 0) -> 0
2363   if (N1C && N1C->isNullValue())
2364     return N1;
2365   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2366   if (N1C && N1C->getAPIntValue() == 1) {
2367     SDLoc DL(N);
2368     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2369                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2370                                        DL,
2371                                        getShiftAmountTy(N0.getValueType())));
2372   }
2373   // fold (mulhs x, undef) -> 0
2374   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2375     return DAG.getConstant(0, SDLoc(N), VT);
2376
2377   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2378   // plus a shift.
2379   if (VT.isSimple() && !VT.isVector()) {
2380     MVT Simple = VT.getSimpleVT();
2381     unsigned SimpleSize = Simple.getSizeInBits();
2382     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2385       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2386       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2387       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2388             DAG.getConstant(SimpleSize, DL,
2389                             getShiftAmountTy(N1.getValueType())));
2390       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2391     }
2392   }
2393
2394   return SDValue();
2395 }
2396
2397 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2398   SDValue N0 = N->getOperand(0);
2399   SDValue N1 = N->getOperand(1);
2400   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2401   EVT VT = N->getValueType(0);
2402   SDLoc DL(N);
2403
2404   // fold (mulhu x, 0) -> 0
2405   if (N1C && N1C->isNullValue())
2406     return N1;
2407   // fold (mulhu x, 1) -> 0
2408   if (N1C && N1C->getAPIntValue() == 1)
2409     return DAG.getConstant(0, DL, N0.getValueType());
2410   // fold (mulhu x, undef) -> 0
2411   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2412     return DAG.getConstant(0, DL, VT);
2413
2414   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2415   // plus a shift.
2416   if (VT.isSimple() && !VT.isVector()) {
2417     MVT Simple = VT.getSimpleVT();
2418     unsigned SimpleSize = Simple.getSizeInBits();
2419     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2420     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2421       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2422       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2423       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2424       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2425             DAG.getConstant(SimpleSize, DL,
2426                             getShiftAmountTy(N1.getValueType())));
2427       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2428     }
2429   }
2430
2431   return SDValue();
2432 }
2433
2434 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2435 /// give the opcodes for the two computations that are being performed. Return
2436 /// true if a simplification was made.
2437 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2438                                                 unsigned HiOp) {
2439   // If the high half is not needed, just compute the low half.
2440   bool HiExists = N->hasAnyUseOfValue(1);
2441   if (!HiExists &&
2442       (!LegalOperations ||
2443        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2444     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2445     return CombineTo(N, Res, Res);
2446   }
2447
2448   // If the low half is not needed, just compute the high half.
2449   bool LoExists = N->hasAnyUseOfValue(0);
2450   if (!LoExists &&
2451       (!LegalOperations ||
2452        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2453     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2454     return CombineTo(N, Res, Res);
2455   }
2456
2457   // If both halves are used, return as it is.
2458   if (LoExists && HiExists)
2459     return SDValue();
2460
2461   // If the two computed results can be simplified separately, separate them.
2462   if (LoExists) {
2463     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2464     AddToWorklist(Lo.getNode());
2465     SDValue LoOpt = combine(Lo.getNode());
2466     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2467         (!LegalOperations ||
2468          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2469       return CombineTo(N, LoOpt, LoOpt);
2470   }
2471
2472   if (HiExists) {
2473     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2474     AddToWorklist(Hi.getNode());
2475     SDValue HiOpt = combine(Hi.getNode());
2476     if (HiOpt.getNode() && HiOpt != Hi &&
2477         (!LegalOperations ||
2478          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2479       return CombineTo(N, HiOpt, HiOpt);
2480   }
2481
2482   return SDValue();
2483 }
2484
2485 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2486   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2487   if (Res.getNode()) return Res;
2488
2489   EVT VT = N->getValueType(0);
2490   SDLoc DL(N);
2491
2492   // If the type is twice as wide is legal, transform the mulhu to a wider
2493   // multiply plus a shift.
2494   if (VT.isSimple() && !VT.isVector()) {
2495     MVT Simple = VT.getSimpleVT();
2496     unsigned SimpleSize = Simple.getSizeInBits();
2497     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2500       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2501       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502       // Compute the high part as N1.
2503       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504             DAG.getConstant(SimpleSize, DL,
2505                             getShiftAmountTy(Lo.getValueType())));
2506       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2507       // Compute the low part as N0.
2508       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2509       return CombineTo(N, Lo, Hi);
2510     }
2511   }
2512
2513   return SDValue();
2514 }
2515
2516 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2517   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2518   if (Res.getNode()) return Res;
2519
2520   EVT VT = N->getValueType(0);
2521   SDLoc DL(N);
2522
2523   // If the type is twice as wide is legal, transform the mulhu to a wider
2524   // multiply plus a shift.
2525   if (VT.isSimple() && !VT.isVector()) {
2526     MVT Simple = VT.getSimpleVT();
2527     unsigned SimpleSize = Simple.getSizeInBits();
2528     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2529     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2530       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2531       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2532       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2533       // Compute the high part as N1.
2534       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2535             DAG.getConstant(SimpleSize, DL,
2536                             getShiftAmountTy(Lo.getValueType())));
2537       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2538       // Compute the low part as N0.
2539       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2540       return CombineTo(N, Lo, Hi);
2541     }
2542   }
2543
2544   return SDValue();
2545 }
2546
2547 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2548   // (smulo x, 2) -> (saddo x, x)
2549   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2550     if (C2->getAPIntValue() == 2)
2551       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2552                          N->getOperand(0), N->getOperand(0));
2553
2554   return SDValue();
2555 }
2556
2557 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2558   // (umulo x, 2) -> (uaddo x, x)
2559   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2560     if (C2->getAPIntValue() == 2)
2561       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2562                          N->getOperand(0), N->getOperand(0));
2563
2564   return SDValue();
2565 }
2566
2567 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2568   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2569   if (Res.getNode()) return Res;
2570
2571   return SDValue();
2572 }
2573
2574 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2575   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2576   if (Res.getNode()) return Res;
2577
2578   return SDValue();
2579 }
2580
2581 /// If this is a binary operator with two operands of the same opcode, try to
2582 /// simplify it.
2583 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2584   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2585   EVT VT = N0.getValueType();
2586   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2587
2588   // Bail early if none of these transforms apply.
2589   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2590
2591   // For each of OP in AND/OR/XOR:
2592   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2593   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2594   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2595   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2596   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2597   //
2598   // do not sink logical op inside of a vector extend, since it may combine
2599   // into a vsetcc.
2600   EVT Op0VT = N0.getOperand(0).getValueType();
2601   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2602        N0.getOpcode() == ISD::SIGN_EXTEND ||
2603        N0.getOpcode() == ISD::BSWAP ||
2604        // Avoid infinite looping with PromoteIntBinOp.
2605        (N0.getOpcode() == ISD::ANY_EXTEND &&
2606         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2607        (N0.getOpcode() == ISD::TRUNCATE &&
2608         (!TLI.isZExtFree(VT, Op0VT) ||
2609          !TLI.isTruncateFree(Op0VT, VT)) &&
2610         TLI.isTypeLegal(Op0VT))) &&
2611       !VT.isVector() &&
2612       Op0VT == N1.getOperand(0).getValueType() &&
2613       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2614     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2615                                  N0.getOperand(0).getValueType(),
2616                                  N0.getOperand(0), N1.getOperand(0));
2617     AddToWorklist(ORNode.getNode());
2618     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2619   }
2620
2621   // For each of OP in SHL/SRL/SRA/AND...
2622   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2623   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2624   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2625   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2626        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2627       N0.getOperand(1) == N1.getOperand(1)) {
2628     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2629                                  N0.getOperand(0).getValueType(),
2630                                  N0.getOperand(0), N1.getOperand(0));
2631     AddToWorklist(ORNode.getNode());
2632     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2633                        ORNode, N0.getOperand(1));
2634   }
2635
2636   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2637   // Only perform this optimization after type legalization and before
2638   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2639   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2640   // we don't want to undo this promotion.
2641   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2642   // on scalars.
2643   if ((N0.getOpcode() == ISD::BITCAST ||
2644        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2645       Level == AfterLegalizeTypes) {
2646     SDValue In0 = N0.getOperand(0);
2647     SDValue In1 = N1.getOperand(0);
2648     EVT In0Ty = In0.getValueType();
2649     EVT In1Ty = In1.getValueType();
2650     SDLoc DL(N);
2651     // If both incoming values are integers, and the original types are the
2652     // same.
2653     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2654       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2655       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2656       AddToWorklist(Op.getNode());
2657       return BC;
2658     }
2659   }
2660
2661   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2662   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2663   // If both shuffles use the same mask, and both shuffle within a single
2664   // vector, then it is worthwhile to move the swizzle after the operation.
2665   // The type-legalizer generates this pattern when loading illegal
2666   // vector types from memory. In many cases this allows additional shuffle
2667   // optimizations.
2668   // There are other cases where moving the shuffle after the xor/and/or
2669   // is profitable even if shuffles don't perform a swizzle.
2670   // If both shuffles use the same mask, and both shuffles have the same first
2671   // or second operand, then it might still be profitable to move the shuffle
2672   // after the xor/and/or operation.
2673   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2674     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2675     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2676
2677     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2678            "Inputs to shuffles are not the same type");
2679
2680     // Check that both shuffles use the same mask. The masks are known to be of
2681     // the same length because the result vector type is the same.
2682     // Check also that shuffles have only one use to avoid introducing extra
2683     // instructions.
2684     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2685         SVN0->getMask().equals(SVN1->getMask())) {
2686       SDValue ShOp = N0->getOperand(1);
2687
2688       // Don't try to fold this node if it requires introducing a
2689       // build vector of all zeros that might be illegal at this stage.
2690       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2691         if (!LegalTypes)
2692           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2693         else
2694           ShOp = SDValue();
2695       }
2696
2697       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2698       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2699       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2700       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2701         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2702                                       N0->getOperand(0), N1->getOperand(0));
2703         AddToWorklist(NewNode.getNode());
2704         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2705                                     &SVN0->getMask()[0]);
2706       }
2707
2708       // Don't try to fold this node if it requires introducing a
2709       // build vector of all zeros that might be illegal at this stage.
2710       ShOp = N0->getOperand(0);
2711       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2712         if (!LegalTypes)
2713           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2714         else
2715           ShOp = SDValue();
2716       }
2717
2718       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2719       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2720       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2721       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2722         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2723                                       N0->getOperand(1), N1->getOperand(1));
2724         AddToWorklist(NewNode.getNode());
2725         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2726                                     &SVN0->getMask()[0]);
2727       }
2728     }
2729   }
2730
2731   return SDValue();
2732 }
2733
2734 /// This contains all DAGCombine rules which reduce two values combined by
2735 /// an And operation to a single value. This makes them reusable in the context
2736 /// of visitSELECT(). Rules involving constants are not included as
2737 /// visitSELECT() already handles those cases.
2738 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2739                                   SDNode *LocReference) {
2740   EVT VT = N1.getValueType();
2741
2742   // fold (and x, undef) -> 0
2743   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2744     return DAG.getConstant(0, SDLoc(LocReference), VT);
2745   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746   SDValue LL, LR, RL, RR, CC0, CC1;
2747   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2748     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2749     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2750
2751     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2752         LL.getValueType().isInteger()) {
2753       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2754       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2755         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2756                                      LR.getValueType(), LL, RL);
2757         AddToWorklist(ORNode.getNode());
2758         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2759       }
2760       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2761       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2762         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2763                                       LR.getValueType(), LL, RL);
2764         AddToWorklist(ANDNode.getNode());
2765         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2766       }
2767       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2768       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2769         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770                                      LR.getValueType(), LL, RL);
2771         AddToWorklist(ORNode.getNode());
2772         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2773       }
2774     }
2775     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2776     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2777         Op0 == Op1 && LL.getValueType().isInteger() &&
2778       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2779                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2780                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2781                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2782       SDLoc DL(N0);
2783       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2784                                     LL, DAG.getConstant(1, DL,
2785                                                         LL.getValueType()));
2786       AddToWorklist(ADDNode.getNode());
2787       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2788                           DAG.getConstant(2, DL, LL.getValueType()),
2789                           ISD::SETUGE);
2790     }
2791     // canonicalize equivalent to ll == rl
2792     if (LL == RR && LR == RL) {
2793       Op1 = ISD::getSetCCSwappedOperands(Op1);
2794       std::swap(RL, RR);
2795     }
2796     if (LL == RL && LR == RR) {
2797       bool isInteger = LL.getValueType().isInteger();
2798       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2799       if (Result != ISD::SETCC_INVALID &&
2800           (!LegalOperations ||
2801            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802             TLI.isOperationLegal(ISD::SETCC,
2803                             getSetCCResultType(N0.getSimpleValueType())))))
2804         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2805                             LL, LR, Result);
2806     }
2807   }
2808
2809   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2810       VT.getSizeInBits() <= 64) {
2811     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2812       APInt ADDC = ADDI->getAPIntValue();
2813       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2814         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2815         // immediate for an add, but it is legal if its top c2 bits are set,
2816         // transform the ADD so the immediate doesn't need to be materialized
2817         // in a register.
2818         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2819           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2820                                              SRLI->getZExtValue());
2821           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2822             ADDC |= Mask;
2823             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2824               SDLoc DL(N0);
2825               SDValue NewAdd =
2826                 DAG.getNode(ISD::ADD, DL, VT,
2827                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2828               CombineTo(N0.getNode(), NewAdd);
2829               // Return N so it doesn't get rechecked!
2830               return SDValue(LocReference, 0);
2831             }
2832           }
2833         }
2834       }
2835     }
2836   }
2837
2838   return SDValue();
2839 }
2840
2841 SDValue DAGCombiner::visitAND(SDNode *N) {
2842   SDValue N0 = N->getOperand(0);
2843   SDValue N1 = N->getOperand(1);
2844   EVT VT = N1.getValueType();
2845
2846   // fold vector ops
2847   if (VT.isVector()) {
2848     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2849       return FoldedVOp;
2850
2851     // fold (and x, 0) -> 0, vector edition
2852     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2853       // do not return N0, because undef node may exist in N0
2854       return DAG.getConstant(
2855           APInt::getNullValue(
2856               N0.getValueType().getScalarType().getSizeInBits()),
2857           SDLoc(N), N0.getValueType());
2858     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2859       // do not return N1, because undef node may exist in N1
2860       return DAG.getConstant(
2861           APInt::getNullValue(
2862               N1.getValueType().getScalarType().getSizeInBits()),
2863           SDLoc(N), N1.getValueType());
2864
2865     // fold (and x, -1) -> x, vector edition
2866     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2867       return N1;
2868     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2869       return N0;
2870   }
2871
2872   // fold (and c1, c2) -> c1&c2
2873   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2874   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2875   if (N0C && N1C)
2876     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2877   // canonicalize constant to RHS
2878   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2879      !isConstantIntBuildVectorOrConstantInt(N1))
2880     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2881   // fold (and x, -1) -> x
2882   if (N1C && N1C->isAllOnesValue())
2883     return N0;
2884   // if (and x, c) is known to be zero, return 0
2885   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2886   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2887                                    APInt::getAllOnesValue(BitWidth)))
2888     return DAG.getConstant(0, SDLoc(N), VT);
2889   // reassociate and
2890   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2891     return RAND;
2892   // fold (and (or x, C), D) -> D if (C & D) == D
2893   if (N1C && N0.getOpcode() == ISD::OR)
2894     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2895       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2896         return N1;
2897   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2898   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2899     SDValue N0Op0 = N0.getOperand(0);
2900     APInt Mask = ~N1C->getAPIntValue();
2901     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2902     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2903       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2904                                  N0.getValueType(), N0Op0);
2905
2906       // Replace uses of the AND with uses of the Zero extend node.
2907       CombineTo(N, Zext);
2908
2909       // We actually want to replace all uses of the any_extend with the
2910       // zero_extend, to avoid duplicating things.  This will later cause this
2911       // AND to be folded.
2912       CombineTo(N0.getNode(), Zext);
2913       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2914     }
2915   }
2916   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2917   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2918   // already be zero by virtue of the width of the base type of the load.
2919   //
2920   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2921   // more cases.
2922   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2923        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2924       N0.getOpcode() == ISD::LOAD) {
2925     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2926                                          N0 : N0.getOperand(0) );
2927
2928     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2929     // This can be a pure constant or a vector splat, in which case we treat the
2930     // vector as a scalar and use the splat value.
2931     APInt Constant = APInt::getNullValue(1);
2932     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2933       Constant = C->getAPIntValue();
2934     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2935       APInt SplatValue, SplatUndef;
2936       unsigned SplatBitSize;
2937       bool HasAnyUndefs;
2938       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2939                                              SplatBitSize, HasAnyUndefs);
2940       if (IsSplat) {
2941         // Undef bits can contribute to a possible optimisation if set, so
2942         // set them.
2943         SplatValue |= SplatUndef;
2944
2945         // The splat value may be something like "0x00FFFFFF", which means 0 for
2946         // the first vector value and FF for the rest, repeating. We need a mask
2947         // that will apply equally to all members of the vector, so AND all the
2948         // lanes of the constant together.
2949         EVT VT = Vector->getValueType(0);
2950         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2951
2952         // If the splat value has been compressed to a bitlength lower
2953         // than the size of the vector lane, we need to re-expand it to
2954         // the lane size.
2955         if (BitWidth > SplatBitSize)
2956           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2957                SplatBitSize < BitWidth;
2958                SplatBitSize = SplatBitSize * 2)
2959             SplatValue |= SplatValue.shl(SplatBitSize);
2960
2961         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2962         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2963         if (SplatBitSize % BitWidth == 0) {
2964           Constant = APInt::getAllOnesValue(BitWidth);
2965           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2966             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2967         }
2968       }
2969     }
2970
2971     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2972     // actually legal and isn't going to get expanded, else this is a false
2973     // optimisation.
2974     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2975                                                     Load->getValueType(0),
2976                                                     Load->getMemoryVT());
2977
2978     // Resize the constant to the same size as the original memory access before
2979     // extension. If it is still the AllOnesValue then this AND is completely
2980     // unneeded.
2981     Constant =
2982       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2983
2984     bool B;
2985     switch (Load->getExtensionType()) {
2986     default: B = false; break;
2987     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2988     case ISD::ZEXTLOAD:
2989     case ISD::NON_EXTLOAD: B = true; break;
2990     }
2991
2992     if (B && Constant.isAllOnesValue()) {
2993       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2994       // preserve semantics once we get rid of the AND.
2995       SDValue NewLoad(Load, 0);
2996       if (Load->getExtensionType() == ISD::EXTLOAD) {
2997         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2998                               Load->getValueType(0), SDLoc(Load),
2999                               Load->getChain(), Load->getBasePtr(),
3000                               Load->getOffset(), Load->getMemoryVT(),
3001                               Load->getMemOperand());
3002         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3003         if (Load->getNumValues() == 3) {
3004           // PRE/POST_INC loads have 3 values.
3005           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3006                            NewLoad.getValue(2) };
3007           CombineTo(Load, To, 3, true);
3008         } else {
3009           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3010         }
3011       }
3012
3013       // Fold the AND away, taking care not to fold to the old load node if we
3014       // replaced it.
3015       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3016
3017       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018     }
3019   }
3020
3021   // fold (and (load x), 255) -> (zextload x, i8)
3022   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3023   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3024   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3025               (N0.getOpcode() == ISD::ANY_EXTEND &&
3026                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3027     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3028     LoadSDNode *LN0 = HasAnyExt
3029       ? cast<LoadSDNode>(N0.getOperand(0))
3030       : cast<LoadSDNode>(N0);
3031     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3032         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3033       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3034       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3035         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036         EVT LoadedVT = LN0->getMemoryVT();
3037         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3038
3039         if (ExtVT == LoadedVT &&
3040             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3041                                                     ExtVT))) {
3042
3043           SDValue NewLoad =
3044             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3045                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3046                            LN0->getMemOperand());
3047           AddToWorklist(N);
3048           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3049           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3050         }
3051
3052         // Do not change the width of a volatile load.
3053         // Do not generate loads of non-round integer types since these can
3054         // be expensive (and would be wrong if the type is not byte sized).
3055         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3056             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3057                                                     ExtVT))) {
3058           EVT PtrType = LN0->getOperand(1).getValueType();
3059
3060           unsigned Alignment = LN0->getAlignment();
3061           SDValue NewPtr = LN0->getBasePtr();
3062
3063           // For big endian targets, we need to add an offset to the pointer
3064           // to load the correct bytes.  For little endian systems, we merely
3065           // need to read fewer bytes from the same pointer.
3066           if (TLI.isBigEndian()) {
3067             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3068             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3069             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3070             SDLoc DL(LN0);
3071             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3072                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3073             Alignment = MinAlign(Alignment, PtrOff);
3074           }
3075
3076           AddToWorklist(NewPtr.getNode());
3077
3078           SDValue Load =
3079             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3080                            LN0->getChain(), NewPtr,
3081                            LN0->getPointerInfo(),
3082                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3083                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3084           AddToWorklist(N);
3085           CombineTo(LN0, Load, Load.getValue(1));
3086           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3087         }
3088       }
3089     }
3090   }
3091
3092   if (SDValue Combined = visitANDLike(N0, N1, N))
3093     return Combined;
3094
3095   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3096   if (N0.getOpcode() == N1.getOpcode()) {
3097     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3098     if (Tmp.getNode()) return Tmp;
3099   }
3100
3101   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3102   // fold (and (sra)) -> (and (srl)) when possible.
3103   if (!VT.isVector() &&
3104       SimplifyDemandedBits(SDValue(N, 0)))
3105     return SDValue(N, 0);
3106
3107   // fold (zext_inreg (extload x)) -> (zextload x)
3108   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3109     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3110     EVT MemVT = LN0->getMemoryVT();
3111     // If we zero all the possible extended bits, then we can turn this into
3112     // a zextload if we are running before legalize or the operation is legal.
3113     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3114     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3115                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3116         ((!LegalOperations && !LN0->isVolatile()) ||
3117          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3118       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3119                                        LN0->getChain(), LN0->getBasePtr(),
3120                                        MemVT, LN0->getMemOperand());
3121       AddToWorklist(N);
3122       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3123       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3124     }
3125   }
3126   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3127   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3128       N0.hasOneUse()) {
3129     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3130     EVT MemVT = LN0->getMemoryVT();
3131     // If we zero all the possible extended bits, then we can turn this into
3132     // a zextload if we are running before legalize or the operation is legal.
3133     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3134     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3135                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3136         ((!LegalOperations && !LN0->isVolatile()) ||
3137          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3138       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3139                                        LN0->getChain(), LN0->getBasePtr(),
3140                                        MemVT, LN0->getMemOperand());
3141       AddToWorklist(N);
3142       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3143       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3144     }
3145   }
3146   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3147   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3148     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3149                                        N0.getOperand(1), false);
3150     if (BSwap.getNode())
3151       return BSwap;
3152   }
3153
3154   return SDValue();
3155 }
3156
3157 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3158 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3159                                         bool DemandHighBits) {
3160   if (!LegalOperations)
3161     return SDValue();
3162
3163   EVT VT = N->getValueType(0);
3164   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3165     return SDValue();
3166   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3167     return SDValue();
3168
3169   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3170   bool LookPassAnd0 = false;
3171   bool LookPassAnd1 = false;
3172   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3173       std::swap(N0, N1);
3174   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3175       std::swap(N0, N1);
3176   if (N0.getOpcode() == ISD::AND) {
3177     if (!N0.getNode()->hasOneUse())
3178       return SDValue();
3179     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3180     if (!N01C || N01C->getZExtValue() != 0xFF00)
3181       return SDValue();
3182     N0 = N0.getOperand(0);
3183     LookPassAnd0 = true;
3184   }
3185
3186   if (N1.getOpcode() == ISD::AND) {
3187     if (!N1.getNode()->hasOneUse())
3188       return SDValue();
3189     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3190     if (!N11C || N11C->getZExtValue() != 0xFF)
3191       return SDValue();
3192     N1 = N1.getOperand(0);
3193     LookPassAnd1 = true;
3194   }
3195
3196   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3197     std::swap(N0, N1);
3198   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3199     return SDValue();
3200   if (!N0.getNode()->hasOneUse() ||
3201       !N1.getNode()->hasOneUse())
3202     return SDValue();
3203
3204   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3206   if (!N01C || !N11C)
3207     return SDValue();
3208   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3209     return SDValue();
3210
3211   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3212   SDValue N00 = N0->getOperand(0);
3213   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3214     if (!N00.getNode()->hasOneUse())
3215       return SDValue();
3216     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3217     if (!N001C || N001C->getZExtValue() != 0xFF)
3218       return SDValue();
3219     N00 = N00.getOperand(0);
3220     LookPassAnd0 = true;
3221   }
3222
3223   SDValue N10 = N1->getOperand(0);
3224   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3225     if (!N10.getNode()->hasOneUse())
3226       return SDValue();
3227     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3228     if (!N101C || N101C->getZExtValue() != 0xFF00)
3229       return SDValue();
3230     N10 = N10.getOperand(0);
3231     LookPassAnd1 = true;
3232   }
3233
3234   if (N00 != N10)
3235     return SDValue();
3236
3237   // Make sure everything beyond the low halfword gets set to zero since the SRL
3238   // 16 will clear the top bits.
3239   unsigned OpSizeInBits = VT.getSizeInBits();
3240   if (DemandHighBits && OpSizeInBits > 16) {
3241     // If the left-shift isn't masked out then the only way this is a bswap is
3242     // if all bits beyond the low 8 are 0. In that case the entire pattern
3243     // reduces to a left shift anyway: leave it for other parts of the combiner.
3244     if (!LookPassAnd0)
3245       return SDValue();
3246
3247     // However, if the right shift isn't masked out then it might be because
3248     // it's not needed. See if we can spot that too.
3249     if (!LookPassAnd1 &&
3250         !DAG.MaskedValueIsZero(
3251             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3252       return SDValue();
3253   }
3254
3255   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3256   if (OpSizeInBits > 16) {
3257     SDLoc DL(N);
3258     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3259                       DAG.getConstant(OpSizeInBits - 16, DL,
3260                                       getShiftAmountTy(VT)));
3261   }
3262   return Res;
3263 }
3264
3265 /// Return true if the specified node is an element that makes up a 32-bit
3266 /// packed halfword byteswap.
3267 /// ((x & 0x000000ff) << 8) |
3268 /// ((x & 0x0000ff00) >> 8) |
3269 /// ((x & 0x00ff0000) << 8) |
3270 /// ((x & 0xff000000) >> 8)
3271 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3272   if (!N.getNode()->hasOneUse())
3273     return false;
3274
3275   unsigned Opc = N.getOpcode();
3276   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3277     return false;
3278
3279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3280   if (!N1C)
3281     return false;
3282
3283   unsigned Num;
3284   switch (N1C->getZExtValue()) {
3285   default:
3286     return false;
3287   case 0xFF:       Num = 0; break;
3288   case 0xFF00:     Num = 1; break;
3289   case 0xFF0000:   Num = 2; break;
3290   case 0xFF000000: Num = 3; break;
3291   }
3292
3293   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3294   SDValue N0 = N.getOperand(0);
3295   if (Opc == ISD::AND) {
3296     if (Num == 0 || Num == 2) {
3297       // (x >> 8) & 0xff
3298       // (x >> 8) & 0xff0000
3299       if (N0.getOpcode() != ISD::SRL)
3300         return false;
3301       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3302       if (!C || C->getZExtValue() != 8)
3303         return false;
3304     } else {
3305       // (x << 8) & 0xff00
3306       // (x << 8) & 0xff000000
3307       if (N0.getOpcode() != ISD::SHL)
3308         return false;
3309       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3310       if (!C || C->getZExtValue() != 8)
3311         return false;
3312     }
3313   } else if (Opc == ISD::SHL) {
3314     // (x & 0xff) << 8
3315     // (x & 0xff0000) << 8
3316     if (Num != 0 && Num != 2)
3317       return false;
3318     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3319     if (!C || C->getZExtValue() != 8)
3320       return false;
3321   } else { // Opc == ISD::SRL
3322     // (x & 0xff00) >> 8
3323     // (x & 0xff000000) >> 8
3324     if (Num != 1 && Num != 3)
3325       return false;
3326     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3327     if (!C || C->getZExtValue() != 8)
3328       return false;
3329   }
3330
3331   if (Parts[Num])
3332     return false;
3333
3334   Parts[Num] = N0.getOperand(0).getNode();
3335   return true;
3336 }
3337
3338 /// Match a 32-bit packed halfword bswap. That is
3339 /// ((x & 0x000000ff) << 8) |
3340 /// ((x & 0x0000ff00) >> 8) |
3341 /// ((x & 0x00ff0000) << 8) |
3342 /// ((x & 0xff000000) >> 8)
3343 /// => (rotl (bswap x), 16)
3344 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3345   if (!LegalOperations)
3346     return SDValue();
3347
3348   EVT VT = N->getValueType(0);
3349   if (VT != MVT::i32)
3350     return SDValue();
3351   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3352     return SDValue();
3353
3354   // Look for either
3355   // (or (or (and), (and)), (or (and), (and)))
3356   // (or (or (or (and), (and)), (and)), (and))
3357   if (N0.getOpcode() != ISD::OR)
3358     return SDValue();
3359   SDValue N00 = N0.getOperand(0);
3360   SDValue N01 = N0.getOperand(1);
3361   SDNode *Parts[4] = {};
3362
3363   if (N1.getOpcode() == ISD::OR &&
3364       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3365     // (or (or (and), (and)), (or (and), (and)))
3366     SDValue N000 = N00.getOperand(0);
3367     if (!isBSwapHWordElement(N000, Parts))
3368       return SDValue();
3369
3370     SDValue N001 = N00.getOperand(1);
3371     if (!isBSwapHWordElement(N001, Parts))
3372       return SDValue();
3373     SDValue N010 = N01.getOperand(0);
3374     if (!isBSwapHWordElement(N010, Parts))
3375       return SDValue();
3376     SDValue N011 = N01.getOperand(1);
3377     if (!isBSwapHWordElement(N011, Parts))
3378       return SDValue();
3379   } else {
3380     // (or (or (or (and), (and)), (and)), (and))
3381     if (!isBSwapHWordElement(N1, Parts))
3382       return SDValue();
3383     if (!isBSwapHWordElement(N01, Parts))
3384       return SDValue();
3385     if (N00.getOpcode() != ISD::OR)
3386       return SDValue();
3387     SDValue N000 = N00.getOperand(0);
3388     if (!isBSwapHWordElement(N000, Parts))
3389       return SDValue();
3390     SDValue N001 = N00.getOperand(1);
3391     if (!isBSwapHWordElement(N001, Parts))
3392       return SDValue();
3393   }
3394
3395   // Make sure the parts are all coming from the same node.
3396   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3397     return SDValue();
3398
3399   SDLoc DL(N);
3400   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3401                               SDValue(Parts[0], 0));
3402
3403   // Result of the bswap should be rotated by 16. If it's not legal, then
3404   // do  (x << 16) | (x >> 16).
3405   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3406   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3407     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3408   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3409     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3410   return DAG.getNode(ISD::OR, DL, VT,
3411                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3412                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3413 }
3414
3415 /// This contains all DAGCombine rules which reduce two values combined by
3416 /// an Or operation to a single value \see visitANDLike().
3417 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3418   EVT VT = N1.getValueType();
3419   // fold (or x, undef) -> -1
3420   if (!LegalOperations &&
3421       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3422     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3423     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3424                            SDLoc(LocReference), VT);
3425   }
3426   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3427   SDValue LL, LR, RL, RR, CC0, CC1;
3428   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3429     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3430     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3431
3432     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3433         LL.getValueType().isInteger()) {
3434       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3435       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3436       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3437           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3438         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3439                                      LR.getValueType(), LL, RL);
3440         AddToWorklist(ORNode.getNode());
3441         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3442       }
3443       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3444       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3445       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3446           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3447         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3448                                       LR.getValueType(), LL, RL);
3449         AddToWorklist(ANDNode.getNode());
3450         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3451       }
3452     }
3453     // canonicalize equivalent to ll == rl
3454     if (LL == RR && LR == RL) {
3455       Op1 = ISD::getSetCCSwappedOperands(Op1);
3456       std::swap(RL, RR);
3457     }
3458     if (LL == RL && LR == RR) {
3459       bool isInteger = LL.getValueType().isInteger();
3460       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3461       if (Result != ISD::SETCC_INVALID &&
3462           (!LegalOperations ||
3463            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3464             TLI.isOperationLegal(ISD::SETCC,
3465               getSetCCResultType(N0.getValueType())))))
3466         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3467                             LL, LR, Result);
3468     }
3469   }
3470
3471   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3472   if (N0.getOpcode() == ISD::AND &&
3473       N1.getOpcode() == ISD::AND &&
3474       N0.getOperand(1).getOpcode() == ISD::Constant &&
3475       N1.getOperand(1).getOpcode() == ISD::Constant &&
3476       // Don't increase # computations.
3477       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3478     // We can only do this xform if we know that bits from X that are set in C2
3479     // but not in C1 are already zero.  Likewise for Y.
3480     const APInt &LHSMask =
3481       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3482     const APInt &RHSMask =
3483       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3484
3485     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3486         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3487       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3488                               N0.getOperand(0), N1.getOperand(0));
3489       SDLoc DL(LocReference);
3490       return DAG.getNode(ISD::AND, DL, VT, X,
3491                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3492     }
3493   }
3494
3495   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3496   if (N0.getOpcode() == ISD::AND &&
3497       N1.getOpcode() == ISD::AND &&
3498       N0.getOperand(0) == N1.getOperand(0) &&
3499       // Don't increase # computations.
3500       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3501     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3502                             N0.getOperand(1), N1.getOperand(1));
3503     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3504   }
3505
3506   return SDValue();
3507 }
3508
3509 SDValue DAGCombiner::visitOR(SDNode *N) {
3510   SDValue N0 = N->getOperand(0);
3511   SDValue N1 = N->getOperand(1);
3512   EVT VT = N1.getValueType();
3513
3514   // fold vector ops
3515   if (VT.isVector()) {
3516     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3517       return FoldedVOp;
3518
3519     // fold (or x, 0) -> x, vector edition
3520     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3521       return N1;
3522     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3523       return N0;
3524
3525     // fold (or x, -1) -> -1, vector edition
3526     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3527       // do not return N0, because undef node may exist in N0
3528       return DAG.getConstant(
3529           APInt::getAllOnesValue(
3530               N0.getValueType().getScalarType().getSizeInBits()),
3531           SDLoc(N), N0.getValueType());
3532     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3533       // do not return N1, because undef node may exist in N1
3534       return DAG.getConstant(
3535           APInt::getAllOnesValue(
3536               N1.getValueType().getScalarType().getSizeInBits()),
3537           SDLoc(N), N1.getValueType());
3538
3539     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3540     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3541     // Do this only if the resulting shuffle is legal.
3542     if (isa<ShuffleVectorSDNode>(N0) &&
3543         isa<ShuffleVectorSDNode>(N1) &&
3544         // Avoid folding a node with illegal type.
3545         TLI.isTypeLegal(VT) &&
3546         N0->getOperand(1) == N1->getOperand(1) &&
3547         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3548       bool CanFold = true;
3549       unsigned NumElts = VT.getVectorNumElements();
3550       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3551       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3552       // We construct two shuffle masks:
3553       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3554       // and N1 as the second operand.
3555       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3556       // and N0 as the second operand.
3557       // We do this because OR is commutable and therefore there might be
3558       // two ways to fold this node into a shuffle.
3559       SmallVector<int,4> Mask1;
3560       SmallVector<int,4> Mask2;
3561
3562       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3563         int M0 = SV0->getMaskElt(i);
3564         int M1 = SV1->getMaskElt(i);
3565
3566         // Both shuffle indexes are undef. Propagate Undef.
3567         if (M0 < 0 && M1 < 0) {
3568           Mask1.push_back(M0);
3569           Mask2.push_back(M0);
3570           continue;
3571         }
3572
3573         if (M0 < 0 || M1 < 0 ||
3574             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3575             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3576           CanFold = false;
3577           break;
3578         }
3579
3580         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3581         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3582       }
3583
3584       if (CanFold) {
3585         // Fold this sequence only if the resulting shuffle is 'legal'.
3586         if (TLI.isShuffleMaskLegal(Mask1, VT))
3587           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3588                                       N1->getOperand(0), &Mask1[0]);
3589         if (TLI.isShuffleMaskLegal(Mask2, VT))
3590           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3591                                       N0->getOperand(0), &Mask2[0]);
3592       }
3593     }
3594   }
3595
3596   // fold (or c1, c2) -> c1|c2
3597   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3598   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3599   if (N0C && N1C)
3600     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3601   // canonicalize constant to RHS
3602   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3603      !isConstantIntBuildVectorOrConstantInt(N1))
3604     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3605   // fold (or x, 0) -> x
3606   if (N1C && N1C->isNullValue())
3607     return N0;
3608   // fold (or x, -1) -> -1
3609   if (N1C && N1C->isAllOnesValue())
3610     return N1;
3611   // fold (or x, c) -> c iff (x & ~c) == 0
3612   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3613     return N1;
3614
3615   if (SDValue Combined = visitORLike(N0, N1, N))
3616     return Combined;
3617
3618   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3619   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3620   if (BSwap.getNode())
3621     return BSwap;
3622   BSwap = MatchBSwapHWordLow(N, N0, N1);
3623   if (BSwap.getNode())
3624     return BSwap;
3625
3626   // reassociate or
3627   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3628     return ROR;
3629   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3630   // iff (c1 & c2) == 0.
3631   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3632              isa<ConstantSDNode>(N0.getOperand(1))) {
3633     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3634     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3635       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3636                                                    N1C, C1))
3637         return DAG.getNode(
3638             ISD::AND, SDLoc(N), VT,
3639             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3640       return SDValue();
3641     }
3642   }
3643   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3644   if (N0.getOpcode() == N1.getOpcode()) {
3645     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3646     if (Tmp.getNode()) return Tmp;
3647   }
3648
3649   // See if this is some rotate idiom.
3650   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3651     return SDValue(Rot, 0);
3652
3653   // Simplify the operands using demanded-bits information.
3654   if (!VT.isVector() &&
3655       SimplifyDemandedBits(SDValue(N, 0)))
3656     return SDValue(N, 0);
3657
3658   return SDValue();
3659 }
3660
3661 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3662 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3663   if (Op.getOpcode() == ISD::AND) {
3664     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3665       Mask = Op.getOperand(1);
3666       Op = Op.getOperand(0);
3667     } else {
3668       return false;
3669     }
3670   }
3671
3672   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3673     Shift = Op;
3674     return true;
3675   }
3676
3677   return false;
3678 }
3679
3680 // Return true if we can prove that, whenever Neg and Pos are both in the
3681 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3682 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3683 //
3684 //     (or (shift1 X, Neg), (shift2 X, Pos))
3685 //
3686 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3687 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3688 // to consider shift amounts with defined behavior.
3689 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3690   // If OpSize is a power of 2 then:
3691   //
3692   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3693   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3694   //
3695   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3696   // for the stronger condition:
3697   //
3698   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3699   //
3700   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3701   // we can just replace Neg with Neg' for the rest of the function.
3702   //
3703   // In other cases we check for the even stronger condition:
3704   //
3705   //     Neg == OpSize - Pos                                    [B]
3706   //
3707   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3708   // behavior if Pos == 0 (and consequently Neg == OpSize).
3709   //
3710   // We could actually use [A] whenever OpSize is a power of 2, but the
3711   // only extra cases that it would match are those uninteresting ones
3712   // where Neg and Pos are never in range at the same time.  E.g. for
3713   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3714   // as well as (sub 32, Pos), but:
3715   //
3716   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3717   //
3718   // always invokes undefined behavior for 32-bit X.
3719   //
3720   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3721   unsigned MaskLoBits = 0;
3722   if (Neg.getOpcode() == ISD::AND &&
3723       isPowerOf2_64(OpSize) &&
3724       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3725       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3726     Neg = Neg.getOperand(0);
3727     MaskLoBits = Log2_64(OpSize);
3728   }
3729
3730   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3731   if (Neg.getOpcode() != ISD::SUB)
3732     return 0;
3733   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3734   if (!NegC)
3735     return 0;
3736   SDValue NegOp1 = Neg.getOperand(1);
3737
3738   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3739   // Pos'.  The truncation is redundant for the purpose of the equality.
3740   if (MaskLoBits &&
3741       Pos.getOpcode() == ISD::AND &&
3742       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3743       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3744     Pos = Pos.getOperand(0);
3745
3746   // The condition we need is now:
3747   //
3748   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3749   //
3750   // If NegOp1 == Pos then we need:
3751   //
3752   //              OpSize & Mask == NegC & Mask
3753   //
3754   // (because "x & Mask" is a truncation and distributes through subtraction).
3755   APInt Width;
3756   if (Pos == NegOp1)
3757     Width = NegC->getAPIntValue();
3758   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3759   // Then the condition we want to prove becomes:
3760   //
3761   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3762   //
3763   // which, again because "x & Mask" is a truncation, becomes:
3764   //
3765   //                NegC & Mask == (OpSize - PosC) & Mask
3766   //              OpSize & Mask == (NegC + PosC) & Mask
3767   else if (Pos.getOpcode() == ISD::ADD &&
3768            Pos.getOperand(0) == NegOp1 &&
3769            Pos.getOperand(1).getOpcode() == ISD::Constant)
3770     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3771              NegC->getAPIntValue());
3772   else
3773     return false;
3774
3775   // Now we just need to check that OpSize & Mask == Width & Mask.
3776   if (MaskLoBits)
3777     // Opsize & Mask is 0 since Mask is Opsize - 1.
3778     return Width.getLoBits(MaskLoBits) == 0;
3779   return Width == OpSize;
3780 }
3781
3782 // A subroutine of MatchRotate used once we have found an OR of two opposite
3783 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3784 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3785 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3786 // Neg with outer conversions stripped away.
3787 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3788                                        SDValue Neg, SDValue InnerPos,
3789                                        SDValue InnerNeg, unsigned PosOpcode,
3790                                        unsigned NegOpcode, SDLoc DL) {
3791   // fold (or (shl x, (*ext y)),
3792   //          (srl x, (*ext (sub 32, y)))) ->
3793   //   (rotl x, y) or (rotr x, (sub 32, y))
3794   //
3795   // fold (or (shl x, (*ext (sub 32, y))),
3796   //          (srl x, (*ext y))) ->
3797   //   (rotr x, y) or (rotl x, (sub 32, y))
3798   EVT VT = Shifted.getValueType();
3799   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3800     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3801     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3802                        HasPos ? Pos : Neg).getNode();
3803   }
3804
3805   return nullptr;
3806 }
3807
3808 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3809 // idioms for rotate, and if the target supports rotation instructions, generate
3810 // a rot[lr].
3811 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3812   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3813   EVT VT = LHS.getValueType();
3814   if (!TLI.isTypeLegal(VT)) return nullptr;
3815
3816   // The target must have at least one rotate flavor.
3817   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3818   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3819   if (!HasROTL && !HasROTR) return nullptr;
3820
3821   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3822   SDValue LHSShift;   // The shift.
3823   SDValue LHSMask;    // AND value if any.
3824   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3825     return nullptr; // Not part of a rotate.
3826
3827   SDValue RHSShift;   // The shift.
3828   SDValue RHSMask;    // AND value if any.
3829   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3830     return nullptr; // Not part of a rotate.
3831
3832   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3833     return nullptr;   // Not shifting the same value.
3834
3835   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3836     return nullptr;   // Shifts must disagree.
3837
3838   // Canonicalize shl to left side in a shl/srl pair.
3839   if (RHSShift.getOpcode() == ISD::SHL) {
3840     std::swap(LHS, RHS);
3841     std::swap(LHSShift, RHSShift);
3842     std::swap(LHSMask , RHSMask );
3843   }
3844
3845   unsigned OpSizeInBits = VT.getSizeInBits();
3846   SDValue LHSShiftArg = LHSShift.getOperand(0);
3847   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3848   SDValue RHSShiftArg = RHSShift.getOperand(0);
3849   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3850
3851   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3852   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3853   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3854       RHSShiftAmt.getOpcode() == ISD::Constant) {
3855     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3856     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3857     if ((LShVal + RShVal) != OpSizeInBits)
3858       return nullptr;
3859
3860     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3861                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3862
3863     // If there is an AND of either shifted operand, apply it to the result.
3864     if (LHSMask.getNode() || RHSMask.getNode()) {
3865       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3866
3867       if (LHSMask.getNode()) {
3868         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3869         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3870       }
3871       if (RHSMask.getNode()) {
3872         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3873         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3874       }
3875
3876       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3877     }
3878
3879     return Rot.getNode();
3880   }
3881
3882   // If there is a mask here, and we have a variable shift, we can't be sure
3883   // that we're masking out the right stuff.
3884   if (LHSMask.getNode() || RHSMask.getNode())
3885     return nullptr;
3886
3887   // If the shift amount is sign/zext/any-extended just peel it off.
3888   SDValue LExtOp0 = LHSShiftAmt;
3889   SDValue RExtOp0 = RHSShiftAmt;
3890   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3894       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3895        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3896        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3897        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3898     LExtOp0 = LHSShiftAmt.getOperand(0);
3899     RExtOp0 = RHSShiftAmt.getOperand(0);
3900   }
3901
3902   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3903                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3904   if (TryL)
3905     return TryL;
3906
3907   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3908                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3909   if (TryR)
3910     return TryR;
3911
3912   return nullptr;
3913 }
3914
3915 SDValue DAGCombiner::visitXOR(SDNode *N) {
3916   SDValue N0 = N->getOperand(0);
3917   SDValue N1 = N->getOperand(1);
3918   EVT VT = N0.getValueType();
3919
3920   // fold vector ops
3921   if (VT.isVector()) {
3922     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3923       return FoldedVOp;
3924
3925     // fold (xor x, 0) -> x, vector edition
3926     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3927       return N1;
3928     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3929       return N0;
3930   }
3931
3932   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3933   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3934     return DAG.getConstant(0, SDLoc(N), VT);
3935   // fold (xor x, undef) -> undef
3936   if (N0.getOpcode() == ISD::UNDEF)
3937     return N0;
3938   if (N1.getOpcode() == ISD::UNDEF)
3939     return N1;
3940   // fold (xor c1, c2) -> c1^c2
3941   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3942   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3943   if (N0C && N1C)
3944     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3945   // canonicalize constant to RHS
3946   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3947      !isConstantIntBuildVectorOrConstantInt(N1))
3948     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3949   // fold (xor x, 0) -> x
3950   if (N1C && N1C->isNullValue())
3951     return N0;
3952   // reassociate xor
3953   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3954     return RXOR;
3955
3956   // fold !(x cc y) -> (x !cc y)
3957   SDValue LHS, RHS, CC;
3958   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3959     bool isInt = LHS.getValueType().isInteger();
3960     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3961                                                isInt);
3962
3963     if (!LegalOperations ||
3964         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3965       switch (N0.getOpcode()) {
3966       default:
3967         llvm_unreachable("Unhandled SetCC Equivalent!");
3968       case ISD::SETCC:
3969         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3970       case ISD::SELECT_CC:
3971         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3972                                N0.getOperand(3), NotCC);
3973       }
3974     }
3975   }
3976
3977   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3978   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3979       N0.getNode()->hasOneUse() &&
3980       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3981     SDValue V = N0.getOperand(0);
3982     SDLoc DL(N0);
3983     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3984                     DAG.getConstant(1, DL, V.getValueType()));
3985     AddToWorklist(V.getNode());
3986     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3987   }
3988
3989   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3990   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3991       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3992     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3993     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3994       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3995       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3996       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3997       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3998       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3999     }
4000   }
4001   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4002   if (N1C && N1C->isAllOnesValue() &&
4003       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4004     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4005     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4006       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4007       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4008       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4009       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4010       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4011     }
4012   }
4013   // fold (xor (and x, y), y) -> (and (not x), y)
4014   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4015       N0->getOperand(1) == N1) {
4016     SDValue X = N0->getOperand(0);
4017     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4018     AddToWorklist(NotX.getNode());
4019     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4020   }
4021   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4022   if (N1C && N0.getOpcode() == ISD::XOR) {
4023     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4024     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4025     if (N00C) {
4026       SDLoc DL(N);
4027       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4028                          DAG.getConstant(N1C->getAPIntValue() ^
4029                                          N00C->getAPIntValue(), DL, VT));
4030     }
4031     if (N01C) {
4032       SDLoc DL(N);
4033       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4034                          DAG.getConstant(N1C->getAPIntValue() ^
4035                                          N01C->getAPIntValue(), DL, VT));
4036     }
4037   }
4038   // fold (xor x, x) -> 0
4039   if (N0 == N1)
4040     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4041
4042   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4043   // Here is a concrete example of this equivalence:
4044   // i16   x ==  14
4045   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4046   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4047   //
4048   // =>
4049   //
4050   // i16     ~1      == 0b1111111111111110
4051   // i16 rol(~1, 14) == 0b1011111111111111
4052   //
4053   // Some additional tips to help conceptualize this transform:
4054   // - Try to see the operation as placing a single zero in a value of all ones.
4055   // - There exists no value for x which would allow the result to contain zero.
4056   // - Values of x larger than the bitwidth are undefined and do not require a
4057   //   consistent result.
4058   // - Pushing the zero left requires shifting one bits in from the right.
4059   // A rotate left of ~1 is a nice way of achieving the desired result.
4060   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4061     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4062       if (N0.getOpcode() == ISD::SHL)
4063         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4064           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4065             SDLoc DL(N);
4066             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4067                                N0.getOperand(1));
4068           }
4069
4070   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4071   if (N0.getOpcode() == N1.getOpcode()) {
4072     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4073     if (Tmp.getNode()) return Tmp;
4074   }
4075
4076   // Simplify the expression using non-local knowledge.
4077   if (!VT.isVector() &&
4078       SimplifyDemandedBits(SDValue(N, 0)))
4079     return SDValue(N, 0);
4080
4081   return SDValue();
4082 }
4083
4084 /// Handle transforms common to the three shifts, when the shift amount is a
4085 /// constant.
4086 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4087   // We can't and shouldn't fold opaque constants.
4088   if (Amt->isOpaque())
4089     return SDValue();
4090
4091   SDNode *LHS = N->getOperand(0).getNode();
4092   if (!LHS->hasOneUse()) return SDValue();
4093
4094   // We want to pull some binops through shifts, so that we have (and (shift))
4095   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4096   // thing happens with address calculations, so it's important to canonicalize
4097   // it.
4098   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4099
4100   switch (LHS->getOpcode()) {
4101   default: return SDValue();
4102   case ISD::OR:
4103   case ISD::XOR:
4104     HighBitSet = false; // We can only transform sra if the high bit is clear.
4105     break;
4106   case ISD::AND:
4107     HighBitSet = true;  // We can only transform sra if the high bit is set.
4108     break;
4109   case ISD::ADD:
4110     if (N->getOpcode() != ISD::SHL)
4111       return SDValue(); // only shl(add) not sr[al](add).
4112     HighBitSet = false; // We can only transform sra if the high bit is clear.
4113     break;
4114   }
4115
4116   // We require the RHS of the binop to be a constant and not opaque as well.
4117   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4118   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4119
4120   // FIXME: disable this unless the input to the binop is a shift by a constant.
4121   // If it is not a shift, it pessimizes some common cases like:
4122   //
4123   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4124   //    int bar(int *X, int i) { return X[i & 255]; }
4125   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4126   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4127        BinOpLHSVal->getOpcode() != ISD::SRA &&
4128        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4129       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4130     return SDValue();
4131
4132   EVT VT = N->getValueType(0);
4133
4134   // If this is a signed shift right, and the high bit is modified by the
4135   // logical operation, do not perform the transformation. The highBitSet
4136   // boolean indicates the value of the high bit of the constant which would
4137   // cause it to be modified for this operation.
4138   if (N->getOpcode() == ISD::SRA) {
4139     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4140     if (BinOpRHSSignSet != HighBitSet)
4141       return SDValue();
4142   }
4143
4144   if (!TLI.isDesirableToCommuteWithShift(LHS))
4145     return SDValue();
4146
4147   // Fold the constants, shifting the binop RHS by the shift amount.
4148   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4149                                N->getValueType(0),
4150                                LHS->getOperand(1), N->getOperand(1));
4151   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4152
4153   // Create the new shift.
4154   SDValue NewShift = DAG.getNode(N->getOpcode(),
4155                                  SDLoc(LHS->getOperand(0)),
4156                                  VT, LHS->getOperand(0), N->getOperand(1));
4157
4158   // Create the new binop.
4159   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4160 }
4161
4162 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4163   assert(N->getOpcode() == ISD::TRUNCATE);
4164   assert(N->getOperand(0).getOpcode() == ISD::AND);
4165
4166   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4167   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4168     SDValue N01 = N->getOperand(0).getOperand(1);
4169
4170     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4171       EVT TruncVT = N->getValueType(0);
4172       SDValue N00 = N->getOperand(0).getOperand(0);
4173       APInt TruncC = N01C->getAPIntValue();
4174       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4175       SDLoc DL(N);
4176
4177       return DAG.getNode(ISD::AND, DL, TruncVT,
4178                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4179                          DAG.getConstant(TruncC, DL, TruncVT));
4180     }
4181   }
4182
4183   return SDValue();
4184 }
4185
4186 SDValue DAGCombiner::visitRotate(SDNode *N) {
4187   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4188   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4189       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4190     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4191     if (NewOp1.getNode())
4192       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4193                          N->getOperand(0), NewOp1);
4194   }
4195   return SDValue();
4196 }
4197
4198 SDValue DAGCombiner::visitSHL(SDNode *N) {
4199   SDValue N0 = N->getOperand(0);
4200   SDValue N1 = N->getOperand(1);
4201   EVT VT = N0.getValueType();
4202   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4203
4204   // fold vector ops
4205   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4206   if (VT.isVector()) {
4207     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4208       return FoldedVOp;
4209
4210     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4211     // If setcc produces all-one true value then:
4212     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4213     if (N1CV && N1CV->isConstant()) {
4214       if (N0.getOpcode() == ISD::AND) {
4215         SDValue N00 = N0->getOperand(0);
4216         SDValue N01 = N0->getOperand(1);
4217         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4218
4219         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4220             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4221                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4222           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4223                                                      N01CV, N1CV))
4224             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4225         }
4226       } else {
4227         N1C = isConstOrConstSplat(N1);
4228       }
4229     }
4230   }
4231
4232   // fold (shl c1, c2) -> c1<<c2
4233   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4234   if (N0C && N1C)
4235     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4236   // fold (shl 0, x) -> 0
4237   if (N0C && N0C->isNullValue())
4238     return N0;
4239   // fold (shl x, c >= size(x)) -> undef
4240   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4241     return DAG.getUNDEF(VT);
4242   // fold (shl x, 0) -> x
4243   if (N1C && N1C->isNullValue())
4244     return N0;
4245   // fold (shl undef, x) -> 0
4246   if (N0.getOpcode() == ISD::UNDEF)
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // if (shl x, c) is known to be zero, return 0
4249   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4250                             APInt::getAllOnesValue(OpSizeInBits)))
4251     return DAG.getConstant(0, SDLoc(N), VT);
4252   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4253   if (N1.getOpcode() == ISD::TRUNCATE &&
4254       N1.getOperand(0).getOpcode() == ISD::AND) {
4255     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4256     if (NewOp1.getNode())
4257       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4258   }
4259
4260   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4261     return SDValue(N, 0);
4262
4263   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4264   if (N1C && N0.getOpcode() == ISD::SHL) {
4265     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4266       uint64_t c1 = N0C1->getZExtValue();
4267       uint64_t c2 = N1C->getZExtValue();
4268       SDLoc DL(N);
4269       if (c1 + c2 >= OpSizeInBits)
4270         return DAG.getConstant(0, DL, VT);
4271       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4272                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4273     }
4274   }
4275
4276   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4277   // For this to be valid, the second form must not preserve any of the bits
4278   // that are shifted out by the inner shift in the first form.  This means
4279   // the outer shift size must be >= the number of bits added by the ext.
4280   // As a corollary, we don't care what kind of ext it is.
4281   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4282               N0.getOpcode() == ISD::ANY_EXTEND ||
4283               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4284       N0.getOperand(0).getOpcode() == ISD::SHL) {
4285     SDValue N0Op0 = N0.getOperand(0);
4286     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4287       uint64_t c1 = N0Op0C1->getZExtValue();
4288       uint64_t c2 = N1C->getZExtValue();
4289       EVT InnerShiftVT = N0Op0.getValueType();
4290       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4291       if (c2 >= OpSizeInBits - InnerShiftSize) {
4292         SDLoc DL(N0);
4293         if (c1 + c2 >= OpSizeInBits)
4294           return DAG.getConstant(0, DL, VT);
4295         return DAG.getNode(ISD::SHL, DL, VT,
4296                            DAG.getNode(N0.getOpcode(), DL, VT,
4297                                        N0Op0->getOperand(0)),
4298                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4299       }
4300     }
4301   }
4302
4303   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4304   // Only fold this if the inner zext has no other uses to avoid increasing
4305   // the total number of instructions.
4306   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4307       N0.getOperand(0).getOpcode() == ISD::SRL) {
4308     SDValue N0Op0 = N0.getOperand(0);
4309     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4310       uint64_t c1 = N0Op0C1->getZExtValue();
4311       if (c1 < VT.getScalarSizeInBits()) {
4312         uint64_t c2 = N1C->getZExtValue();
4313         if (c1 == c2) {
4314           SDValue NewOp0 = N0.getOperand(0);
4315           EVT CountVT = NewOp0.getOperand(1).getValueType();
4316           SDLoc DL(N);
4317           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4318                                        NewOp0,
4319                                        DAG.getConstant(c2, DL, CountVT));
4320           AddToWorklist(NewSHL.getNode());
4321           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4322         }
4323       }
4324     }
4325   }
4326
4327   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4328   //                               (and (srl x, (sub c1, c2), MASK)
4329   // Only fold this if the inner shift has no other uses -- if it does, folding
4330   // this will increase the total number of instructions.
4331   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4332     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4333       uint64_t c1 = N0C1->getZExtValue();
4334       if (c1 < OpSizeInBits) {
4335         uint64_t c2 = N1C->getZExtValue();
4336         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4337         SDValue Shift;
4338         if (c2 > c1) {
4339           Mask = Mask.shl(c2 - c1);
4340           SDLoc DL(N);
4341           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4342                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4343         } else {
4344           Mask = Mask.lshr(c1 - c2);
4345           SDLoc DL(N);
4346           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4347                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4348         }
4349         SDLoc DL(N0);
4350         return DAG.getNode(ISD::AND, DL, VT, Shift,
4351                            DAG.getConstant(Mask, DL, VT));
4352       }
4353     }
4354   }
4355   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4356   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4357     unsigned BitSize = VT.getScalarSizeInBits();
4358     SDLoc DL(N);
4359     SDValue HiBitsMask =
4360       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4361                                             BitSize - N1C->getZExtValue()),
4362                       DL, VT);
4363     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4364                        HiBitsMask);
4365   }
4366
4367   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4368   // Variant of version done on multiply, except mul by a power of 2 is turned
4369   // into a shift.
4370   APInt Val;
4371   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4372       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4373        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4374     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4375     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4376     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4377   }
4378
4379   if (N1C) {
4380     SDValue NewSHL = visitShiftByConstant(N, N1C);
4381     if (NewSHL.getNode())
4382       return NewSHL;
4383   }
4384
4385   return SDValue();
4386 }
4387
4388 SDValue DAGCombiner::visitSRA(SDNode *N) {
4389   SDValue N0 = N->getOperand(0);
4390   SDValue N1 = N->getOperand(1);
4391   EVT VT = N0.getValueType();
4392   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4393
4394   // fold vector ops
4395   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4396   if (VT.isVector()) {
4397     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4398       return FoldedVOp;
4399
4400     N1C = isConstOrConstSplat(N1);
4401   }
4402
4403   // fold (sra c1, c2) -> (sra c1, c2)
4404   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4405   if (N0C && N1C)
4406     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4407   // fold (sra 0, x) -> 0
4408   if (N0C && N0C->isNullValue())
4409     return N0;
4410   // fold (sra -1, x) -> -1
4411   if (N0C && N0C->isAllOnesValue())
4412     return N0;
4413   // fold (sra x, (setge c, size(x))) -> undef
4414   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4415     return DAG.getUNDEF(VT);
4416   // fold (sra x, 0) -> x
4417   if (N1C && N1C->isNullValue())
4418     return N0;
4419   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4420   // sext_inreg.
4421   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4422     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4423     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4424     if (VT.isVector())
4425       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4426                                ExtVT, VT.getVectorNumElements());
4427     if ((!LegalOperations ||
4428          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4429       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4430                          N0.getOperand(0), DAG.getValueType(ExtVT));
4431   }
4432
4433   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4434   if (N1C && N0.getOpcode() == ISD::SRA) {
4435     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4436       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4437       if (Sum >= OpSizeInBits)
4438         Sum = OpSizeInBits - 1;
4439       SDLoc DL(N);
4440       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4441                          DAG.getConstant(Sum, DL, N1.getValueType()));
4442     }
4443   }
4444
4445   // fold (sra (shl X, m), (sub result_size, n))
4446   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4447   // result_size - n != m.
4448   // If truncate is free for the target sext(shl) is likely to result in better
4449   // code.
4450   if (N0.getOpcode() == ISD::SHL && N1C) {
4451     // Get the two constanst of the shifts, CN0 = m, CN = n.
4452     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4453     if (N01C) {
4454       LLVMContext &Ctx = *DAG.getContext();
4455       // Determine what the truncate's result bitsize and type would be.
4456       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4457
4458       if (VT.isVector())
4459         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4460
4461       // Determine the residual right-shift amount.
4462       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4463
4464       // If the shift is not a no-op (in which case this should be just a sign
4465       // extend already), the truncated to type is legal, sign_extend is legal
4466       // on that type, and the truncate to that type is both legal and free,
4467       // perform the transform.
4468       if ((ShiftAmt > 0) &&
4469           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4470           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4471           TLI.isTruncateFree(VT, TruncVT)) {
4472
4473         SDLoc DL(N);
4474         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4475             getShiftAmountTy(N0.getOperand(0).getValueType()));
4476         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4477                                     N0.getOperand(0), Amt);
4478         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4479                                     Shift);
4480         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4481                            N->getValueType(0), Trunc);
4482       }
4483     }
4484   }
4485
4486   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4487   if (N1.getOpcode() == ISD::TRUNCATE &&
4488       N1.getOperand(0).getOpcode() == ISD::AND) {
4489     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4490     if (NewOp1.getNode())
4491       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4492   }
4493
4494   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4495   //      if c1 is equal to the number of bits the trunc removes
4496   if (N0.getOpcode() == ISD::TRUNCATE &&
4497       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4498        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4499       N0.getOperand(0).hasOneUse() &&
4500       N0.getOperand(0).getOperand(1).hasOneUse() &&
4501       N1C) {
4502     SDValue N0Op0 = N0.getOperand(0);
4503     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4504       unsigned LargeShiftVal = LargeShift->getZExtValue();
4505       EVT LargeVT = N0Op0.getValueType();
4506
4507       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4508         SDLoc DL(N);
4509         SDValue Amt =
4510           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4511                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4512         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4513                                   N0Op0.getOperand(0), Amt);
4514         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4515       }
4516     }
4517   }
4518
4519   // Simplify, based on bits shifted out of the LHS.
4520   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4521     return SDValue(N, 0);
4522
4523
4524   // If the sign bit is known to be zero, switch this to a SRL.
4525   if (DAG.SignBitIsZero(N0))
4526     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4527
4528   if (N1C) {
4529     SDValue NewSRA = visitShiftByConstant(N, N1C);
4530     if (NewSRA.getNode())
4531       return NewSRA;
4532   }
4533
4534   return SDValue();
4535 }
4536
4537 SDValue DAGCombiner::visitSRL(SDNode *N) {
4538   SDValue N0 = N->getOperand(0);
4539   SDValue N1 = N->getOperand(1);
4540   EVT VT = N0.getValueType();
4541   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4542
4543   // fold vector ops
4544   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4545   if (VT.isVector()) {
4546     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4547       return FoldedVOp;
4548
4549     N1C = isConstOrConstSplat(N1);
4550   }
4551
4552   // fold (srl c1, c2) -> c1 >>u c2
4553   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4554   if (N0C && N1C)
4555     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4556   // fold (srl 0, x) -> 0
4557   if (N0C && N0C->isNullValue())
4558     return N0;
4559   // fold (srl x, c >= size(x)) -> undef
4560   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4561     return DAG.getUNDEF(VT);
4562   // fold (srl x, 0) -> x
4563   if (N1C && N1C->isNullValue())
4564     return N0;
4565   // if (srl x, c) is known to be zero, return 0
4566   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4567                                    APInt::getAllOnesValue(OpSizeInBits)))
4568     return DAG.getConstant(0, SDLoc(N), VT);
4569
4570   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4571   if (N1C && N0.getOpcode() == ISD::SRL) {
4572     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4573       uint64_t c1 = N01C->getZExtValue();
4574       uint64_t c2 = N1C->getZExtValue();
4575       SDLoc DL(N);
4576       if (c1 + c2 >= OpSizeInBits)
4577         return DAG.getConstant(0, DL, VT);
4578       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4579                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4580     }
4581   }
4582
4583   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4584   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4585       N0.getOperand(0).getOpcode() == ISD::SRL &&
4586       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4587     uint64_t c1 =
4588       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4589     uint64_t c2 = N1C->getZExtValue();
4590     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4591     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4592     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4593     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4594     if (c1 + OpSizeInBits == InnerShiftSize) {
4595       SDLoc DL(N0);
4596       if (c1 + c2 >= InnerShiftSize)
4597         return DAG.getConstant(0, DL, VT);
4598       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4599                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4600                                      N0.getOperand(0)->getOperand(0),
4601                                      DAG.getConstant(c1 + c2, DL,
4602                                                      ShiftCountVT)));
4603     }
4604   }
4605
4606   // fold (srl (shl x, c), c) -> (and x, cst2)
4607   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4608     unsigned BitSize = N0.getScalarValueSizeInBits();
4609     if (BitSize <= 64) {
4610       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4611       SDLoc DL(N);
4612       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4613                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4614     }
4615   }
4616
4617   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4618   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4619     // Shifting in all undef bits?
4620     EVT SmallVT = N0.getOperand(0).getValueType();
4621     unsigned BitSize = SmallVT.getScalarSizeInBits();
4622     if (N1C->getZExtValue() >= BitSize)
4623       return DAG.getUNDEF(VT);
4624
4625     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4626       uint64_t ShiftAmt = N1C->getZExtValue();
4627       SDLoc DL0(N0);
4628       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4629                                        N0.getOperand(0),
4630                           DAG.getConstant(ShiftAmt, DL0,
4631                                           getShiftAmountTy(SmallVT)));
4632       AddToWorklist(SmallShift.getNode());
4633       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4634       SDLoc DL(N);
4635       return DAG.getNode(ISD::AND, DL, VT,
4636                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4637                          DAG.getConstant(Mask, DL, VT));
4638     }
4639   }
4640
4641   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4642   // bit, which is unmodified by sra.
4643   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4644     if (N0.getOpcode() == ISD::SRA)
4645       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4646   }
4647
4648   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4649   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4650       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4651     APInt KnownZero, KnownOne;
4652     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4653
4654     // If any of the input bits are KnownOne, then the input couldn't be all
4655     // zeros, thus the result of the srl will always be zero.
4656     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4657
4658     // If all of the bits input the to ctlz node are known to be zero, then
4659     // the result of the ctlz is "32" and the result of the shift is one.
4660     APInt UnknownBits = ~KnownZero;
4661     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4662
4663     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4664     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4665       // Okay, we know that only that the single bit specified by UnknownBits
4666       // could be set on input to the CTLZ node. If this bit is set, the SRL
4667       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4668       // to an SRL/XOR pair, which is likely to simplify more.
4669       unsigned ShAmt = UnknownBits.countTrailingZeros();
4670       SDValue Op = N0.getOperand(0);
4671
4672       if (ShAmt) {
4673         SDLoc DL(N0);
4674         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4675                   DAG.getConstant(ShAmt, DL,
4676                                   getShiftAmountTy(Op.getValueType())));
4677         AddToWorklist(Op.getNode());
4678       }
4679
4680       SDLoc DL(N);
4681       return DAG.getNode(ISD::XOR, DL, VT,
4682                          Op, DAG.getConstant(1, DL, VT));
4683     }
4684   }
4685
4686   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4687   if (N1.getOpcode() == ISD::TRUNCATE &&
4688       N1.getOperand(0).getOpcode() == ISD::AND) {
4689     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4690     if (NewOp1.getNode())
4691       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4692   }
4693
4694   // fold operands of srl based on knowledge that the low bits are not
4695   // demanded.
4696   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4697     return SDValue(N, 0);
4698
4699   if (N1C) {
4700     SDValue NewSRL = visitShiftByConstant(N, N1C);
4701     if (NewSRL.getNode())
4702       return NewSRL;
4703   }
4704
4705   // Attempt to convert a srl of a load into a narrower zero-extending load.
4706   SDValue NarrowLoad = ReduceLoadWidth(N);
4707   if (NarrowLoad.getNode())
4708     return NarrowLoad;
4709
4710   // Here is a common situation. We want to optimize:
4711   //
4712   //   %a = ...
4713   //   %b = and i32 %a, 2
4714   //   %c = srl i32 %b, 1
4715   //   brcond i32 %c ...
4716   //
4717   // into
4718   //
4719   //   %a = ...
4720   //   %b = and %a, 2
4721   //   %c = setcc eq %b, 0
4722   //   brcond %c ...
4723   //
4724   // However when after the source operand of SRL is optimized into AND, the SRL
4725   // itself may not be optimized further. Look for it and add the BRCOND into
4726   // the worklist.
4727   if (N->hasOneUse()) {
4728     SDNode *Use = *N->use_begin();
4729     if (Use->getOpcode() == ISD::BRCOND)
4730       AddToWorklist(Use);
4731     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4732       // Also look pass the truncate.
4733       Use = *Use->use_begin();
4734       if (Use->getOpcode() == ISD::BRCOND)
4735         AddToWorklist(Use);
4736     }
4737   }
4738
4739   return SDValue();
4740 }
4741
4742 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4743   SDValue N0 = N->getOperand(0);
4744   EVT VT = N->getValueType(0);
4745
4746   // fold (ctlz c1) -> c2
4747   if (isa<ConstantSDNode>(N0))
4748     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4749   return SDValue();
4750 }
4751
4752 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4753   SDValue N0 = N->getOperand(0);
4754   EVT VT = N->getValueType(0);
4755
4756   // fold (ctlz_zero_undef c1) -> c2
4757   if (isa<ConstantSDNode>(N0))
4758     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4759   return SDValue();
4760 }
4761
4762 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4763   SDValue N0 = N->getOperand(0);
4764   EVT VT = N->getValueType(0);
4765
4766   // fold (cttz c1) -> c2
4767   if (isa<ConstantSDNode>(N0))
4768     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4769   return SDValue();
4770 }
4771
4772 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4773   SDValue N0 = N->getOperand(0);
4774   EVT VT = N->getValueType(0);
4775
4776   // fold (cttz_zero_undef c1) -> c2
4777   if (isa<ConstantSDNode>(N0))
4778     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4779   return SDValue();
4780 }
4781
4782 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4783   SDValue N0 = N->getOperand(0);
4784   EVT VT = N->getValueType(0);
4785
4786   // fold (ctpop c1) -> c2
4787   if (isa<ConstantSDNode>(N0))
4788     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4789   return SDValue();
4790 }
4791
4792
4793 /// \brief Generate Min/Max node
4794 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4795                                    SDValue True, SDValue False,
4796                                    ISD::CondCode CC, const TargetLowering &TLI,
4797                                    SelectionDAG &DAG) {
4798   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4799     return SDValue();
4800
4801   switch (CC) {
4802   case ISD::SETOLT:
4803   case ISD::SETOLE:
4804   case ISD::SETLT:
4805   case ISD::SETLE:
4806   case ISD::SETULT:
4807   case ISD::SETULE: {
4808     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4809     if (TLI.isOperationLegal(Opcode, VT))
4810       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4811     return SDValue();
4812   }
4813   case ISD::SETOGT:
4814   case ISD::SETOGE:
4815   case ISD::SETGT:
4816   case ISD::SETGE:
4817   case ISD::SETUGT:
4818   case ISD::SETUGE: {
4819     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4820     if (TLI.isOperationLegal(Opcode, VT))
4821       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4822     return SDValue();
4823   }
4824   default:
4825     return SDValue();
4826   }
4827 }
4828
4829 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4830   SDValue N0 = N->getOperand(0);
4831   SDValue N1 = N->getOperand(1);
4832   SDValue N2 = N->getOperand(2);
4833   EVT VT = N->getValueType(0);
4834   EVT VT0 = N0.getValueType();
4835
4836   // fold (select C, X, X) -> X
4837   if (N1 == N2)
4838     return N1;
4839   // fold (select true, X, Y) -> X
4840   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4841   if (N0C && !N0C->isNullValue())
4842     return N1;
4843   // fold (select false, X, Y) -> Y
4844   if (N0C && N0C->isNullValue())
4845     return N2;
4846   // fold (select C, 1, X) -> (or C, X)
4847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4848   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4849     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4850   // fold (select C, 0, 1) -> (xor C, 1)
4851   // We can't do this reliably if integer based booleans have different contents
4852   // to floating point based booleans. This is because we can't tell whether we
4853   // have an integer-based boolean or a floating-point-based boolean unless we
4854   // can find the SETCC that produced it and inspect its operands. This is
4855   // fairly easy if C is the SETCC node, but it can potentially be
4856   // undiscoverable (or not reasonably discoverable). For example, it could be
4857   // in another basic block or it could require searching a complicated
4858   // expression.
4859   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4860   if (VT.isInteger() &&
4861       (VT0 == MVT::i1 || (VT0.isInteger() &&
4862                           TLI.getBooleanContents(false, false) ==
4863                               TLI.getBooleanContents(false, true) &&
4864                           TLI.getBooleanContents(false, false) ==
4865                               TargetLowering::ZeroOrOneBooleanContent)) &&
4866       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4867     SDValue XORNode;
4868     if (VT == VT0) {
4869       SDLoc DL(N);
4870       return DAG.getNode(ISD::XOR, DL, VT0,
4871                          N0, DAG.getConstant(1, DL, VT0));
4872     }
4873     SDLoc DL0(N0);
4874     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4875                           N0, DAG.getConstant(1, DL0, VT0));
4876     AddToWorklist(XORNode.getNode());
4877     if (VT.bitsGT(VT0))
4878       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4879     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4880   }
4881   // fold (select C, 0, X) -> (and (not C), X)
4882   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4883     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4884     AddToWorklist(NOTNode.getNode());
4885     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4886   }
4887   // fold (select C, X, 1) -> (or (not C), X)
4888   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4889     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4890     AddToWorklist(NOTNode.getNode());
4891     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4892   }
4893   // fold (select C, X, 0) -> (and C, X)
4894   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4895     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4896   // fold (select X, X, Y) -> (or X, Y)
4897   // fold (select X, 1, Y) -> (or X, Y)
4898   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4899     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4900   // fold (select X, Y, X) -> (and X, Y)
4901   // fold (select X, Y, 0) -> (and X, Y)
4902   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4903     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4904
4905   // If we can fold this based on the true/false value, do so.
4906   if (SimplifySelectOps(N, N1, N2))
4907     return SDValue(N, 0);  // Don't revisit N.
4908
4909   // fold selects based on a setcc into other things, such as min/max/abs
4910   if (N0.getOpcode() == ISD::SETCC) {
4911     // select x, y (fcmp lt x, y) -> fminnum x, y
4912     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4913     //
4914     // This is OK if we don't care about what happens if either operand is a
4915     // NaN.
4916     //
4917
4918     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4919     // no signed zeros as well as no nans.
4920     const TargetOptions &Options = DAG.getTarget().Options;
4921     if (Options.UnsafeFPMath &&
4922         VT.isFloatingPoint() && N0.hasOneUse() &&
4923         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4924       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4925
4926       SDValue FMinMax =
4927           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4928                               N1, N2, CC, TLI, DAG);
4929       if (FMinMax)
4930         return FMinMax;
4931     }
4932
4933     if ((!LegalOperations &&
4934          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4935         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4936       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4937                          N0.getOperand(0), N0.getOperand(1),
4938                          N1, N2, N0.getOperand(2));
4939     return SimplifySelect(SDLoc(N), N0, N1, N2);
4940   }
4941
4942   if (VT0 == MVT::i1) {
4943     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4944       // select (and Cond0, Cond1), X, Y
4945       //   -> select Cond0, (select Cond1, X, Y), Y
4946       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4947         SDValue Cond0 = N0->getOperand(0);
4948         SDValue Cond1 = N0->getOperand(1);
4949         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4950                                           N1.getValueType(), Cond1, N1, N2);
4951         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4952                            InnerSelect, N2);
4953       }
4954       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4955       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4956         SDValue Cond0 = N0->getOperand(0);
4957         SDValue Cond1 = N0->getOperand(1);
4958         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4959                                           N1.getValueType(), Cond1, N1, N2);
4960         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4961                            InnerSelect);
4962       }
4963     }
4964
4965     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4966     if (N1->getOpcode() == ISD::SELECT) {
4967       SDValue N1_0 = N1->getOperand(0);
4968       SDValue N1_1 = N1->getOperand(1);
4969       SDValue N1_2 = N1->getOperand(2);
4970       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4971         // Create the actual and node if we can generate good code for it.
4972         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4973           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4974                                     N0, N1_0);
4975           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4976                              N1_1, N2);
4977         }
4978         // Otherwise see if we can optimize the "and" to a better pattern.
4979         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4980           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4981                              N1_1, N2);
4982       }
4983     }
4984     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4985     if (N2->getOpcode() == ISD::SELECT) {
4986       SDValue N2_0 = N2->getOperand(0);
4987       SDValue N2_1 = N2->getOperand(1);
4988       SDValue N2_2 = N2->getOperand(2);
4989       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4990         // Create the actual or node if we can generate good code for it.
4991         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4992           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4993                                    N0, N2_0);
4994           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4995                              N1, N2_2);
4996         }
4997         // Otherwise see if we can optimize to a better pattern.
4998         if (SDValue Combined = visitORLike(N0, N2_0, N))
4999           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5000                              N1, N2_2);
5001       }
5002     }
5003   }
5004
5005   return SDValue();
5006 }
5007
5008 static
5009 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5010   SDLoc DL(N);
5011   EVT LoVT, HiVT;
5012   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5013
5014   // Split the inputs.
5015   SDValue Lo, Hi, LL, LH, RL, RH;
5016   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5017   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5018
5019   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5020   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5021
5022   return std::make_pair(Lo, Hi);
5023 }
5024
5025 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5026 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5027 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5028   SDLoc dl(N);
5029   SDValue Cond = N->getOperand(0);
5030   SDValue LHS = N->getOperand(1);
5031   SDValue RHS = N->getOperand(2);
5032   EVT VT = N->getValueType(0);
5033   int NumElems = VT.getVectorNumElements();
5034   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5035          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5036          Cond.getOpcode() == ISD::BUILD_VECTOR);
5037
5038   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5039   // binary ones here.
5040   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5041     return SDValue();
5042
5043   // We're sure we have an even number of elements due to the
5044   // concat_vectors we have as arguments to vselect.
5045   // Skip BV elements until we find one that's not an UNDEF
5046   // After we find an UNDEF element, keep looping until we get to half the
5047   // length of the BV and see if all the non-undef nodes are the same.
5048   ConstantSDNode *BottomHalf = nullptr;
5049   for (int i = 0; i < NumElems / 2; ++i) {
5050     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5051       continue;
5052
5053     if (BottomHalf == nullptr)
5054       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5055     else if (Cond->getOperand(i).getNode() != BottomHalf)
5056       return SDValue();
5057   }
5058
5059   // Do the same for the second half of the BuildVector
5060   ConstantSDNode *TopHalf = nullptr;
5061   for (int i = NumElems / 2; i < NumElems; ++i) {
5062     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5063       continue;
5064
5065     if (TopHalf == nullptr)
5066       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5067     else if (Cond->getOperand(i).getNode() != TopHalf)
5068       return SDValue();
5069   }
5070
5071   assert(TopHalf && BottomHalf &&
5072          "One half of the selector was all UNDEFs and the other was all the "
5073          "same value. This should have been addressed before this function.");
5074   return DAG.getNode(
5075       ISD::CONCAT_VECTORS, dl, VT,
5076       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5077       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5078 }
5079
5080 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5081
5082   if (Level >= AfterLegalizeTypes)
5083     return SDValue();
5084
5085   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5086   SDValue Mask = MSC->getMask();
5087   SDValue Data  = MSC->getValue();
5088   SDLoc DL(N);
5089
5090   // If the MSCATTER data type requires splitting and the mask is provided by a
5091   // SETCC, then split both nodes and its operands before legalization. This
5092   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5093   // and enables future optimizations (e.g. min/max pattern matching on X86).
5094   if (Mask.getOpcode() != ISD::SETCC)
5095     return SDValue();
5096
5097   // Check if any splitting is required.
5098   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5099       TargetLowering::TypeSplitVector)
5100     return SDValue();
5101   SDValue MaskLo, MaskHi, Lo, Hi;
5102   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5103
5104   EVT LoVT, HiVT;
5105   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5106
5107   SDValue Chain = MSC->getChain();
5108
5109   EVT MemoryVT = MSC->getMemoryVT();
5110   unsigned Alignment = MSC->getOriginalAlignment();
5111
5112   EVT LoMemVT, HiMemVT;
5113   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5114
5115   SDValue DataLo, DataHi;
5116   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5117
5118   SDValue BasePtr = MSC->getBasePtr();
5119   SDValue IndexLo, IndexHi;
5120   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5121
5122   MachineMemOperand *MMO = DAG.getMachineFunction().
5123     getMachineMemOperand(MSC->getPointerInfo(), 
5124                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5125                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5126
5127   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5128   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5129                             DL, OpsLo, MMO);
5130
5131   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5132   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5133                             DL, OpsHi, MMO);
5134
5135   AddToWorklist(Lo.getNode());
5136   AddToWorklist(Hi.getNode());
5137
5138   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5139 }
5140
5141 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5142
5143   if (Level >= AfterLegalizeTypes)
5144     return SDValue();
5145
5146   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5147   SDValue Mask = MST->getMask();
5148   SDValue Data  = MST->getValue();
5149   SDLoc DL(N);
5150
5151   // If the MSTORE data type requires splitting and the mask is provided by a
5152   // SETCC, then split both nodes and its operands before legalization. This
5153   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5154   // and enables future optimizations (e.g. min/max pattern matching on X86).
5155   if (Mask.getOpcode() == ISD::SETCC) {
5156
5157     // Check if any splitting is required.
5158     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5159         TargetLowering::TypeSplitVector)
5160       return SDValue();
5161
5162     SDValue MaskLo, MaskHi, Lo, Hi;
5163     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5164
5165     EVT LoVT, HiVT;
5166     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5167
5168     SDValue Chain = MST->getChain();
5169     SDValue Ptr   = MST->getBasePtr();
5170
5171     EVT MemoryVT = MST->getMemoryVT();
5172     unsigned Alignment = MST->getOriginalAlignment();
5173
5174     // if Alignment is equal to the vector size,
5175     // take the half of it for the second part
5176     unsigned SecondHalfAlignment =
5177       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5178          Alignment/2 : Alignment;
5179
5180     EVT LoMemVT, HiMemVT;
5181     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5182
5183     SDValue DataLo, DataHi;
5184     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5185
5186     MachineMemOperand *MMO = DAG.getMachineFunction().
5187       getMachineMemOperand(MST->getPointerInfo(),
5188                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5189                            Alignment, MST->getAAInfo(), MST->getRanges());
5190
5191     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5192                             MST->isTruncatingStore());
5193
5194     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5195     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5196                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5197
5198     MMO = DAG.getMachineFunction().
5199       getMachineMemOperand(MST->getPointerInfo(),
5200                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5201                            SecondHalfAlignment, MST->getAAInfo(),
5202                            MST->getRanges());
5203
5204     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5205                             MST->isTruncatingStore());
5206
5207     AddToWorklist(Lo.getNode());
5208     AddToWorklist(Hi.getNode());
5209
5210     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5211   }
5212   return SDValue();
5213 }
5214
5215 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5216
5217   if (Level >= AfterLegalizeTypes)
5218     return SDValue();
5219
5220   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5221   SDValue Mask = MGT->getMask();
5222   SDLoc DL(N);
5223
5224   // If the MGATHER result requires splitting and the mask is provided by a
5225   // SETCC, then split both nodes and its operands before legalization. This
5226   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5227   // and enables future optimizations (e.g. min/max pattern matching on X86).
5228
5229   if (Mask.getOpcode() != ISD::SETCC)
5230     return SDValue();
5231
5232   EVT VT = N->getValueType(0);
5233
5234   // Check if any splitting is required.
5235   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5236       TargetLowering::TypeSplitVector)
5237     return SDValue();
5238
5239   SDValue MaskLo, MaskHi, Lo, Hi;
5240   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5241
5242   SDValue Src0 = MGT->getValue();
5243   SDValue Src0Lo, Src0Hi;
5244   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5245
5246   EVT LoVT, HiVT;
5247   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5248
5249   SDValue Chain = MGT->getChain();
5250   EVT MemoryVT = MGT->getMemoryVT();
5251   unsigned Alignment = MGT->getOriginalAlignment();
5252
5253   EVT LoMemVT, HiMemVT;
5254   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5255
5256   SDValue BasePtr = MGT->getBasePtr();
5257   SDValue Index = MGT->getIndex();
5258   SDValue IndexLo, IndexHi;
5259   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5260
5261   MachineMemOperand *MMO = DAG.getMachineFunction().
5262     getMachineMemOperand(MGT->getPointerInfo(), 
5263                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5264                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5265
5266   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5267   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5268                             MMO);
5269
5270   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5271   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5272                             MMO);
5273
5274   AddToWorklist(Lo.getNode());
5275   AddToWorklist(Hi.getNode());
5276
5277   // Build a factor node to remember that this load is independent of the
5278   // other one.
5279   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5280                       Hi.getValue(1));
5281
5282   // Legalized the chain result - switch anything that used the old chain to
5283   // use the new one.
5284   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5285
5286   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5287
5288   SDValue RetOps[] = { GatherRes, Chain };
5289   return DAG.getMergeValues(RetOps, DL);
5290 }
5291
5292 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5293
5294   if (Level >= AfterLegalizeTypes)
5295     return SDValue();
5296
5297   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5298   SDValue Mask = MLD->getMask();
5299   SDLoc DL(N);
5300
5301   // If the MLOAD result requires splitting and the mask is provided by a
5302   // SETCC, then split both nodes and its operands before legalization. This
5303   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5304   // and enables future optimizations (e.g. min/max pattern matching on X86).
5305
5306   if (Mask.getOpcode() == ISD::SETCC) {
5307     EVT VT = N->getValueType(0);
5308
5309     // Check if any splitting is required.
5310     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5311         TargetLowering::TypeSplitVector)
5312       return SDValue();
5313
5314     SDValue MaskLo, MaskHi, Lo, Hi;
5315     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5316
5317     SDValue Src0 = MLD->getSrc0();
5318     SDValue Src0Lo, Src0Hi;
5319     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5320
5321     EVT LoVT, HiVT;
5322     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5323
5324     SDValue Chain = MLD->getChain();
5325     SDValue Ptr   = MLD->getBasePtr();
5326     EVT MemoryVT = MLD->getMemoryVT();
5327     unsigned Alignment = MLD->getOriginalAlignment();
5328
5329     // if Alignment is equal to the vector size,
5330     // take the half of it for the second part
5331     unsigned SecondHalfAlignment =
5332       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5333          Alignment/2 : Alignment;
5334
5335     EVT LoMemVT, HiMemVT;
5336     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5337
5338     MachineMemOperand *MMO = DAG.getMachineFunction().
5339     getMachineMemOperand(MLD->getPointerInfo(),
5340                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5341                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5342
5343     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5344                            ISD::NON_EXTLOAD);
5345
5346     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5347     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5348                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5349
5350     MMO = DAG.getMachineFunction().
5351     getMachineMemOperand(MLD->getPointerInfo(),
5352                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5353                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5354
5355     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5356                            ISD::NON_EXTLOAD);
5357
5358     AddToWorklist(Lo.getNode());
5359     AddToWorklist(Hi.getNode());
5360
5361     // Build a factor node to remember that this load is independent of the
5362     // other one.
5363     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5364                         Hi.getValue(1));
5365
5366     // Legalized the chain result - switch anything that used the old chain to
5367     // use the new one.
5368     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5369
5370     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5371
5372     SDValue RetOps[] = { LoadRes, Chain };
5373     return DAG.getMergeValues(RetOps, DL);
5374   }
5375   return SDValue();
5376 }
5377
5378 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5379   SDValue N0 = N->getOperand(0);
5380   SDValue N1 = N->getOperand(1);
5381   SDValue N2 = N->getOperand(2);
5382   SDLoc DL(N);
5383
5384   // Canonicalize integer abs.
5385   // vselect (setg[te] X,  0),  X, -X ->
5386   // vselect (setgt    X, -1),  X, -X ->
5387   // vselect (setl[te] X,  0), -X,  X ->
5388   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5389   if (N0.getOpcode() == ISD::SETCC) {
5390     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5391     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5392     bool isAbs = false;
5393     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5394
5395     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5396          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5397         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5398       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5399     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5400              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5401       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5402
5403     if (isAbs) {
5404       EVT VT = LHS.getValueType();
5405       SDValue Shift = DAG.getNode(
5406           ISD::SRA, DL, VT, LHS,
5407           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5408       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5409       AddToWorklist(Shift.getNode());
5410       AddToWorklist(Add.getNode());
5411       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5412     }
5413   }
5414
5415   if (SimplifySelectOps(N, N1, N2))
5416     return SDValue(N, 0);  // Don't revisit N.
5417
5418   // If the VSELECT result requires splitting and the mask is provided by a
5419   // SETCC, then split both nodes and its operands before legalization. This
5420   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5421   // and enables future optimizations (e.g. min/max pattern matching on X86).
5422   if (N0.getOpcode() == ISD::SETCC) {
5423     EVT VT = N->getValueType(0);
5424
5425     // Check if any splitting is required.
5426     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5427         TargetLowering::TypeSplitVector)
5428       return SDValue();
5429
5430     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5431     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5432     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5433     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5434
5435     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5436     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5437
5438     // Add the new VSELECT nodes to the work list in case they need to be split
5439     // again.
5440     AddToWorklist(Lo.getNode());
5441     AddToWorklist(Hi.getNode());
5442
5443     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5444   }
5445
5446   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5447   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5448     return N1;
5449   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5450   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5451     return N2;
5452
5453   // The ConvertSelectToConcatVector function is assuming both the above
5454   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5455   // and addressed.
5456   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5457       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5458       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5459     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5460     if (CV.getNode())
5461       return CV;
5462   }
5463
5464   return SDValue();
5465 }
5466
5467 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5468   SDValue N0 = N->getOperand(0);
5469   SDValue N1 = N->getOperand(1);
5470   SDValue N2 = N->getOperand(2);
5471   SDValue N3 = N->getOperand(3);
5472   SDValue N4 = N->getOperand(4);
5473   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5474
5475   // fold select_cc lhs, rhs, x, x, cc -> x
5476   if (N2 == N3)
5477     return N2;
5478
5479   // Determine if the condition we're dealing with is constant
5480   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5481                               N0, N1, CC, SDLoc(N), false);
5482   if (SCC.getNode()) {
5483     AddToWorklist(SCC.getNode());
5484
5485     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5486       if (!SCCC->isNullValue())
5487         return N2;    // cond always true -> true val
5488       else
5489         return N3;    // cond always false -> false val
5490     } else if (SCC->getOpcode() == ISD::UNDEF) {
5491       // When the condition is UNDEF, just return the first operand. This is
5492       // coherent the DAG creation, no setcc node is created in this case
5493       return N2;
5494     } else if (SCC.getOpcode() == ISD::SETCC) {
5495       // Fold to a simpler select_cc
5496       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5497                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5498                          SCC.getOperand(2));
5499     }
5500   }
5501
5502   // If we can fold this based on the true/false value, do so.
5503   if (SimplifySelectOps(N, N2, N3))
5504     return SDValue(N, 0);  // Don't revisit N.
5505
5506   // fold select_cc into other things, such as min/max/abs
5507   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5508 }
5509
5510 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5511   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5512                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5513                        SDLoc(N));
5514 }
5515
5516 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5517 // dag node into a ConstantSDNode or a build_vector of constants.
5518 // This function is called by the DAGCombiner when visiting sext/zext/aext
5519 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5520 // Vector extends are not folded if operations are legal; this is to
5521 // avoid introducing illegal build_vector dag nodes.
5522 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5523                                          SelectionDAG &DAG, bool LegalTypes,
5524                                          bool LegalOperations) {
5525   unsigned Opcode = N->getOpcode();
5526   SDValue N0 = N->getOperand(0);
5527   EVT VT = N->getValueType(0);
5528
5529   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5530          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5531
5532   // fold (sext c1) -> c1
5533   // fold (zext c1) -> c1
5534   // fold (aext c1) -> c1
5535   if (isa<ConstantSDNode>(N0))
5536     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5537
5538   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5539   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5540   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5541   EVT SVT = VT.getScalarType();
5542   if (!(VT.isVector() &&
5543       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5544       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5545     return nullptr;
5546
5547   // We can fold this node into a build_vector.
5548   unsigned VTBits = SVT.getSizeInBits();
5549   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5550   unsigned ShAmt = VTBits - EVTBits;
5551   SmallVector<SDValue, 8> Elts;
5552   unsigned NumElts = N0->getNumOperands();
5553   SDLoc DL(N);
5554
5555   for (unsigned i=0; i != NumElts; ++i) {
5556     SDValue Op = N0->getOperand(i);
5557     if (Op->getOpcode() == ISD::UNDEF) {
5558       Elts.push_back(DAG.getUNDEF(SVT));
5559       continue;
5560     }
5561
5562     SDLoc DL(Op);
5563     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5564     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5565     if (Opcode == ISD::SIGN_EXTEND)
5566       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5567                                      DL, SVT));
5568     else
5569       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5570                                      DL, SVT));
5571   }
5572
5573   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5574 }
5575
5576 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5577 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5578 // transformation. Returns true if extension are possible and the above
5579 // mentioned transformation is profitable.
5580 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5581                                     unsigned ExtOpc,
5582                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5583                                     const TargetLowering &TLI) {
5584   bool HasCopyToRegUses = false;
5585   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5586   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5587                             UE = N0.getNode()->use_end();
5588        UI != UE; ++UI) {
5589     SDNode *User = *UI;
5590     if (User == N)
5591       continue;
5592     if (UI.getUse().getResNo() != N0.getResNo())
5593       continue;
5594     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5595     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5596       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5597       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5598         // Sign bits will be lost after a zext.
5599         return false;
5600       bool Add = false;
5601       for (unsigned i = 0; i != 2; ++i) {
5602         SDValue UseOp = User->getOperand(i);
5603         if (UseOp == N0)
5604           continue;
5605         if (!isa<ConstantSDNode>(UseOp))
5606           return false;
5607         Add = true;
5608       }
5609       if (Add)
5610         ExtendNodes.push_back(User);
5611       continue;
5612     }
5613     // If truncates aren't free and there are users we can't
5614     // extend, it isn't worthwhile.
5615     if (!isTruncFree)
5616       return false;
5617     // Remember if this value is live-out.
5618     if (User->getOpcode() == ISD::CopyToReg)
5619       HasCopyToRegUses = true;
5620   }
5621
5622   if (HasCopyToRegUses) {
5623     bool BothLiveOut = false;
5624     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5625          UI != UE; ++UI) {
5626       SDUse &Use = UI.getUse();
5627       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5628         BothLiveOut = true;
5629         break;
5630       }
5631     }
5632     if (BothLiveOut)
5633       // Both unextended and extended values are live out. There had better be
5634       // a good reason for the transformation.
5635       return ExtendNodes.size();
5636   }
5637   return true;
5638 }
5639
5640 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5641                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5642                                   ISD::NodeType ExtType) {
5643   // Extend SetCC uses if necessary.
5644   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5645     SDNode *SetCC = SetCCs[i];
5646     SmallVector<SDValue, 4> Ops;
5647
5648     for (unsigned j = 0; j != 2; ++j) {
5649       SDValue SOp = SetCC->getOperand(j);
5650       if (SOp == Trunc)
5651         Ops.push_back(ExtLoad);
5652       else
5653         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5654     }
5655
5656     Ops.push_back(SetCC->getOperand(2));
5657     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5658   }
5659 }
5660
5661 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5662 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5663   SDValue N0 = N->getOperand(0);
5664   EVT DstVT = N->getValueType(0);
5665   EVT SrcVT = N0.getValueType();
5666
5667   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5668           N->getOpcode() == ISD::ZERO_EXTEND) &&
5669          "Unexpected node type (not an extend)!");
5670
5671   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5672   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5673   //   (v8i32 (sext (v8i16 (load x))))
5674   // into:
5675   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5676   //                          (v4i32 (sextload (x + 16)))))
5677   // Where uses of the original load, i.e.:
5678   //   (v8i16 (load x))
5679   // are replaced with:
5680   //   (v8i16 (truncate
5681   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5682   //                            (v4i32 (sextload (x + 16)))))))
5683   //
5684   // This combine is only applicable to illegal, but splittable, vectors.
5685   // All legal types, and illegal non-vector types, are handled elsewhere.
5686   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5687   //
5688   if (N0->getOpcode() != ISD::LOAD)
5689     return SDValue();
5690
5691   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5692
5693   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5694       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5695       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5696     return SDValue();
5697
5698   SmallVector<SDNode *, 4> SetCCs;
5699   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5700     return SDValue();
5701
5702   ISD::LoadExtType ExtType =
5703       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5704
5705   // Try to split the vector types to get down to legal types.
5706   EVT SplitSrcVT = SrcVT;
5707   EVT SplitDstVT = DstVT;
5708   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5709          SplitSrcVT.getVectorNumElements() > 1) {
5710     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5711     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5712   }
5713
5714   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5715     return SDValue();
5716
5717   SDLoc DL(N);
5718   const unsigned NumSplits =
5719       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5720   const unsigned Stride = SplitSrcVT.getStoreSize();
5721   SmallVector<SDValue, 4> Loads;
5722   SmallVector<SDValue, 4> Chains;
5723
5724   SDValue BasePtr = LN0->getBasePtr();
5725   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5726     const unsigned Offset = Idx * Stride;
5727     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5728
5729     SDValue SplitLoad = DAG.getExtLoad(
5730         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5731         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5732         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5733         Align, LN0->getAAInfo());
5734
5735     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5736                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5737
5738     Loads.push_back(SplitLoad.getValue(0));
5739     Chains.push_back(SplitLoad.getValue(1));
5740   }
5741
5742   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5743   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5744
5745   CombineTo(N, NewValue);
5746
5747   // Replace uses of the original load (before extension)
5748   // with a truncate of the concatenated sextloaded vectors.
5749   SDValue Trunc =
5750       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5751   CombineTo(N0.getNode(), Trunc, NewChain);
5752   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5753                   (ISD::NodeType)N->getOpcode());
5754   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5755 }
5756
5757 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5758   SDValue N0 = N->getOperand(0);
5759   EVT VT = N->getValueType(0);
5760
5761   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5762                                               LegalOperations))
5763     return SDValue(Res, 0);
5764
5765   // fold (sext (sext x)) -> (sext x)
5766   // fold (sext (aext x)) -> (sext x)
5767   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5768     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5769                        N0.getOperand(0));
5770
5771   if (N0.getOpcode() == ISD::TRUNCATE) {
5772     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5773     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5774     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5775     if (NarrowLoad.getNode()) {
5776       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5777       if (NarrowLoad.getNode() != N0.getNode()) {
5778         CombineTo(N0.getNode(), NarrowLoad);
5779         // CombineTo deleted the truncate, if needed, but not what's under it.
5780         AddToWorklist(oye);
5781       }
5782       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5783     }
5784
5785     // See if the value being truncated is already sign extended.  If so, just
5786     // eliminate the trunc/sext pair.
5787     SDValue Op = N0.getOperand(0);
5788     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5789     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5790     unsigned DestBits = VT.getScalarType().getSizeInBits();
5791     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5792
5793     if (OpBits == DestBits) {
5794       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5795       // bits, it is already ready.
5796       if (NumSignBits > DestBits-MidBits)
5797         return Op;
5798     } else if (OpBits < DestBits) {
5799       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5800       // bits, just sext from i32.
5801       if (NumSignBits > OpBits-MidBits)
5802         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5803     } else {
5804       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5805       // bits, just truncate to i32.
5806       if (NumSignBits > OpBits-MidBits)
5807         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5808     }
5809
5810     // fold (sext (truncate x)) -> (sextinreg x).
5811     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5812                                                  N0.getValueType())) {
5813       if (OpBits < DestBits)
5814         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5815       else if (OpBits > DestBits)
5816         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5817       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5818                          DAG.getValueType(N0.getValueType()));
5819     }
5820   }
5821
5822   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5823   // Only generate vector extloads when 1) they're legal, and 2) they are
5824   // deemed desirable by the target.
5825   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826       ((!LegalOperations && !VT.isVector() &&
5827         !cast<LoadSDNode>(N0)->isVolatile()) ||
5828        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5829     bool DoXform = true;
5830     SmallVector<SDNode*, 4> SetCCs;
5831     if (!N0.hasOneUse())
5832       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5833     if (VT.isVector())
5834       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5835     if (DoXform) {
5836       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5837       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5838                                        LN0->getChain(),
5839                                        LN0->getBasePtr(), N0.getValueType(),
5840                                        LN0->getMemOperand());
5841       CombineTo(N, ExtLoad);
5842       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5843                                   N0.getValueType(), ExtLoad);
5844       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5845       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5846                       ISD::SIGN_EXTEND);
5847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5848     }
5849   }
5850
5851   // fold (sext (load x)) to multiple smaller sextloads.
5852   // Only on illegal but splittable vectors.
5853   if (SDValue ExtLoad = CombineExtLoad(N))
5854     return ExtLoad;
5855
5856   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5857   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5858   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5859       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5860     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861     EVT MemVT = LN0->getMemoryVT();
5862     if ((!LegalOperations && !LN0->isVolatile()) ||
5863         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5864       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5865                                        LN0->getChain(),
5866                                        LN0->getBasePtr(), MemVT,
5867                                        LN0->getMemOperand());
5868       CombineTo(N, ExtLoad);
5869       CombineTo(N0.getNode(),
5870                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5871                             N0.getValueType(), ExtLoad),
5872                 ExtLoad.getValue(1));
5873       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5874     }
5875   }
5876
5877   // fold (sext (and/or/xor (load x), cst)) ->
5878   //      (and/or/xor (sextload x), (sext cst))
5879   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5880        N0.getOpcode() == ISD::XOR) &&
5881       isa<LoadSDNode>(N0.getOperand(0)) &&
5882       N0.getOperand(1).getOpcode() == ISD::Constant &&
5883       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5884       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5885     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5886     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5887       bool DoXform = true;
5888       SmallVector<SDNode*, 4> SetCCs;
5889       if (!N0.hasOneUse())
5890         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5891                                           SetCCs, TLI);
5892       if (DoXform) {
5893         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5894                                          LN0->getChain(), LN0->getBasePtr(),
5895                                          LN0->getMemoryVT(),
5896                                          LN0->getMemOperand());
5897         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5898         Mask = Mask.sext(VT.getSizeInBits());
5899         SDLoc DL(N);
5900         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5901                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5902         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5903                                     SDLoc(N0.getOperand(0)),
5904                                     N0.getOperand(0).getValueType(), ExtLoad);
5905         CombineTo(N, And);
5906         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5907         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5908                         ISD::SIGN_EXTEND);
5909         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5910       }
5911     }
5912   }
5913
5914   if (N0.getOpcode() == ISD::SETCC) {
5915     EVT N0VT = N0.getOperand(0).getValueType();
5916     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5917     // Only do this before legalize for now.
5918     if (VT.isVector() && !LegalOperations &&
5919         TLI.getBooleanContents(N0VT) ==
5920             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5921       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5922       // of the same size as the compared operands. Only optimize sext(setcc())
5923       // if this is the case.
5924       EVT SVT = getSetCCResultType(N0VT);
5925
5926       // We know that the # elements of the results is the same as the
5927       // # elements of the compare (and the # elements of the compare result
5928       // for that matter).  Check to see that they are the same size.  If so,
5929       // we know that the element size of the sext'd result matches the
5930       // element size of the compare operands.
5931       if (VT.getSizeInBits() == SVT.getSizeInBits())
5932         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5933                              N0.getOperand(1),
5934                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5935
5936       // If the desired elements are smaller or larger than the source
5937       // elements we can use a matching integer vector type and then
5938       // truncate/sign extend
5939       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5940       if (SVT == MatchingVectorType) {
5941         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5942                                N0.getOperand(0), N0.getOperand(1),
5943                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5944         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5945       }
5946     }
5947
5948     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5949     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5950     SDLoc DL(N);
5951     SDValue NegOne =
5952       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5953     SDValue SCC =
5954       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5955                        NegOne, DAG.getConstant(0, DL, VT),
5956                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5957     if (SCC.getNode()) return SCC;
5958
5959     if (!VT.isVector()) {
5960       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5961       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5962         SDLoc DL(N);
5963         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5964         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5965                                      N0.getOperand(0), N0.getOperand(1), CC);
5966         return DAG.getSelect(DL, VT, SetCC,
5967                              NegOne, DAG.getConstant(0, DL, VT));
5968       }
5969     }
5970   }
5971
5972   // fold (sext x) -> (zext x) if the sign bit is known zero.
5973   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5974       DAG.SignBitIsZero(N0))
5975     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5976
5977   return SDValue();
5978 }
5979
5980 // isTruncateOf - If N is a truncate of some other value, return true, record
5981 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5982 // This function computes KnownZero to avoid a duplicated call to
5983 // computeKnownBits in the caller.
5984 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5985                          APInt &KnownZero) {
5986   APInt KnownOne;
5987   if (N->getOpcode() == ISD::TRUNCATE) {
5988     Op = N->getOperand(0);
5989     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5990     return true;
5991   }
5992
5993   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5994       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5995     return false;
5996
5997   SDValue Op0 = N->getOperand(0);
5998   SDValue Op1 = N->getOperand(1);
5999   assert(Op0.getValueType() == Op1.getValueType());
6000
6001   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
6002   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
6003   if (COp0 && COp0->isNullValue())
6004     Op = Op1;
6005   else if (COp1 && COp1->isNullValue())
6006     Op = Op0;
6007   else
6008     return false;
6009
6010   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6011
6012   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6013     return false;
6014
6015   return true;
6016 }
6017
6018 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6019   SDValue N0 = N->getOperand(0);
6020   EVT VT = N->getValueType(0);
6021
6022   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6023                                               LegalOperations))
6024     return SDValue(Res, 0);
6025
6026   // fold (zext (zext x)) -> (zext x)
6027   // fold (zext (aext x)) -> (zext x)
6028   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6029     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6030                        N0.getOperand(0));
6031
6032   // fold (zext (truncate x)) -> (zext x) or
6033   //      (zext (truncate x)) -> (truncate x)
6034   // This is valid when the truncated bits of x are already zero.
6035   // FIXME: We should extend this to work for vectors too.
6036   SDValue Op;
6037   APInt KnownZero;
6038   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6039     APInt TruncatedBits =
6040       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6041       APInt(Op.getValueSizeInBits(), 0) :
6042       APInt::getBitsSet(Op.getValueSizeInBits(),
6043                         N0.getValueSizeInBits(),
6044                         std::min(Op.getValueSizeInBits(),
6045                                  VT.getSizeInBits()));
6046     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6047       if (VT.bitsGT(Op.getValueType()))
6048         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6049       if (VT.bitsLT(Op.getValueType()))
6050         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6051
6052       return Op;
6053     }
6054   }
6055
6056   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6057   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6058   if (N0.getOpcode() == ISD::TRUNCATE) {
6059     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6060     if (NarrowLoad.getNode()) {
6061       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6062       if (NarrowLoad.getNode() != N0.getNode()) {
6063         CombineTo(N0.getNode(), NarrowLoad);
6064         // CombineTo deleted the truncate, if needed, but not what's under it.
6065         AddToWorklist(oye);
6066       }
6067       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6068     }
6069   }
6070
6071   // fold (zext (truncate x)) -> (and x, mask)
6072   if (N0.getOpcode() == ISD::TRUNCATE &&
6073       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6074
6075     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6076     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6077     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6078     if (NarrowLoad.getNode()) {
6079       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6080       if (NarrowLoad.getNode() != N0.getNode()) {
6081         CombineTo(N0.getNode(), NarrowLoad);
6082         // CombineTo deleted the truncate, if needed, but not what's under it.
6083         AddToWorklist(oye);
6084       }
6085       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6086     }
6087
6088     SDValue Op = N0.getOperand(0);
6089     if (Op.getValueType().bitsLT(VT)) {
6090       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6091       AddToWorklist(Op.getNode());
6092     } else if (Op.getValueType().bitsGT(VT)) {
6093       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6094       AddToWorklist(Op.getNode());
6095     }
6096     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6097                                   N0.getValueType().getScalarType());
6098   }
6099
6100   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6101   // if either of the casts is not free.
6102   if (N0.getOpcode() == ISD::AND &&
6103       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6104       N0.getOperand(1).getOpcode() == ISD::Constant &&
6105       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6106                            N0.getValueType()) ||
6107        !TLI.isZExtFree(N0.getValueType(), VT))) {
6108     SDValue X = N0.getOperand(0).getOperand(0);
6109     if (X.getValueType().bitsLT(VT)) {
6110       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6111     } else if (X.getValueType().bitsGT(VT)) {
6112       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6113     }
6114     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6115     Mask = Mask.zext(VT.getSizeInBits());
6116     SDLoc DL(N);
6117     return DAG.getNode(ISD::AND, DL, VT,
6118                        X, DAG.getConstant(Mask, DL, VT));
6119   }
6120
6121   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6122   // Only generate vector extloads when 1) they're legal, and 2) they are
6123   // deemed desirable by the target.
6124   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6125       ((!LegalOperations && !VT.isVector() &&
6126         !cast<LoadSDNode>(N0)->isVolatile()) ||
6127        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6128     bool DoXform = true;
6129     SmallVector<SDNode*, 4> SetCCs;
6130     if (!N0.hasOneUse())
6131       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6132     if (VT.isVector())
6133       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6134     if (DoXform) {
6135       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6136       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6137                                        LN0->getChain(),
6138                                        LN0->getBasePtr(), N0.getValueType(),
6139                                        LN0->getMemOperand());
6140       CombineTo(N, ExtLoad);
6141       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6142                                   N0.getValueType(), ExtLoad);
6143       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6144
6145       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6146                       ISD::ZERO_EXTEND);
6147       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6148     }
6149   }
6150
6151   // fold (zext (load x)) to multiple smaller zextloads.
6152   // Only on illegal but splittable vectors.
6153   if (SDValue ExtLoad = CombineExtLoad(N))
6154     return ExtLoad;
6155
6156   // fold (zext (and/or/xor (load x), cst)) ->
6157   //      (and/or/xor (zextload x), (zext cst))
6158   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6159        N0.getOpcode() == ISD::XOR) &&
6160       isa<LoadSDNode>(N0.getOperand(0)) &&
6161       N0.getOperand(1).getOpcode() == ISD::Constant &&
6162       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6163       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6164     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6165     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6166       bool DoXform = true;
6167       SmallVector<SDNode*, 4> SetCCs;
6168       if (!N0.hasOneUse())
6169         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6170                                           SetCCs, TLI);
6171       if (DoXform) {
6172         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6173                                          LN0->getChain(), LN0->getBasePtr(),
6174                                          LN0->getMemoryVT(),
6175                                          LN0->getMemOperand());
6176         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6177         Mask = Mask.zext(VT.getSizeInBits());
6178         SDLoc DL(N);
6179         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6180                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6181         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6182                                     SDLoc(N0.getOperand(0)),
6183                                     N0.getOperand(0).getValueType(), ExtLoad);
6184         CombineTo(N, And);
6185         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6186         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6187                         ISD::ZERO_EXTEND);
6188         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6189       }
6190     }
6191   }
6192
6193   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6194   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6195   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6196       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6197     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6198     EVT MemVT = LN0->getMemoryVT();
6199     if ((!LegalOperations && !LN0->isVolatile()) ||
6200         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6201       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6202                                        LN0->getChain(),
6203                                        LN0->getBasePtr(), MemVT,
6204                                        LN0->getMemOperand());
6205       CombineTo(N, ExtLoad);
6206       CombineTo(N0.getNode(),
6207                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6208                             ExtLoad),
6209                 ExtLoad.getValue(1));
6210       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6211     }
6212   }
6213
6214   if (N0.getOpcode() == ISD::SETCC) {
6215     if (!LegalOperations && VT.isVector() &&
6216         N0.getValueType().getVectorElementType() == MVT::i1) {
6217       EVT N0VT = N0.getOperand(0).getValueType();
6218       if (getSetCCResultType(N0VT) == N0.getValueType())
6219         return SDValue();
6220
6221       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6222       // Only do this before legalize for now.
6223       EVT EltVT = VT.getVectorElementType();
6224       SDLoc DL(N);
6225       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6226                                     DAG.getConstant(1, DL, EltVT));
6227       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6228         // We know that the # elements of the results is the same as the
6229         // # elements of the compare (and the # elements of the compare result
6230         // for that matter).  Check to see that they are the same size.  If so,
6231         // we know that the element size of the sext'd result matches the
6232         // element size of the compare operands.
6233         return DAG.getNode(ISD::AND, DL, VT,
6234                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6235                                          N0.getOperand(1),
6236                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6237                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6238                                        OneOps));
6239
6240       // If the desired elements are smaller or larger than the source
6241       // elements we can use a matching integer vector type and then
6242       // truncate/sign extend
6243       EVT MatchingElementType =
6244         EVT::getIntegerVT(*DAG.getContext(),
6245                           N0VT.getScalarType().getSizeInBits());
6246       EVT MatchingVectorType =
6247         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6248                          N0VT.getVectorNumElements());
6249       SDValue VsetCC =
6250         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6251                       N0.getOperand(1),
6252                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6253       return DAG.getNode(ISD::AND, DL, VT,
6254                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6255                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6256     }
6257
6258     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6259     SDLoc DL(N);
6260     SDValue SCC =
6261       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6262                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6263                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6264     if (SCC.getNode()) return SCC;
6265   }
6266
6267   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6268   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6269       isa<ConstantSDNode>(N0.getOperand(1)) &&
6270       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6271       N0.hasOneUse()) {
6272     SDValue ShAmt = N0.getOperand(1);
6273     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6274     if (N0.getOpcode() == ISD::SHL) {
6275       SDValue InnerZExt = N0.getOperand(0);
6276       // If the original shl may be shifting out bits, do not perform this
6277       // transformation.
6278       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6279         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6280       if (ShAmtVal > KnownZeroBits)
6281         return SDValue();
6282     }
6283
6284     SDLoc DL(N);
6285
6286     // Ensure that the shift amount is wide enough for the shifted value.
6287     if (VT.getSizeInBits() >= 256)
6288       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6289
6290     return DAG.getNode(N0.getOpcode(), DL, VT,
6291                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6292                        ShAmt);
6293   }
6294
6295   return SDValue();
6296 }
6297
6298 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6299   SDValue N0 = N->getOperand(0);
6300   EVT VT = N->getValueType(0);
6301
6302   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6303                                               LegalOperations))
6304     return SDValue(Res, 0);
6305
6306   // fold (aext (aext x)) -> (aext x)
6307   // fold (aext (zext x)) -> (zext x)
6308   // fold (aext (sext x)) -> (sext x)
6309   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6310       N0.getOpcode() == ISD::ZERO_EXTEND ||
6311       N0.getOpcode() == ISD::SIGN_EXTEND)
6312     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6313
6314   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6315   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6316   if (N0.getOpcode() == ISD::TRUNCATE) {
6317     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6318     if (NarrowLoad.getNode()) {
6319       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6320       if (NarrowLoad.getNode() != N0.getNode()) {
6321         CombineTo(N0.getNode(), NarrowLoad);
6322         // CombineTo deleted the truncate, if needed, but not what's under it.
6323         AddToWorklist(oye);
6324       }
6325       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6326     }
6327   }
6328
6329   // fold (aext (truncate x))
6330   if (N0.getOpcode() == ISD::TRUNCATE) {
6331     SDValue TruncOp = N0.getOperand(0);
6332     if (TruncOp.getValueType() == VT)
6333       return TruncOp; // x iff x size == zext size.
6334     if (TruncOp.getValueType().bitsGT(VT))
6335       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6336     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6337   }
6338
6339   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6340   // if the trunc is not free.
6341   if (N0.getOpcode() == ISD::AND &&
6342       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6343       N0.getOperand(1).getOpcode() == ISD::Constant &&
6344       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6345                           N0.getValueType())) {
6346     SDValue X = N0.getOperand(0).getOperand(0);
6347     if (X.getValueType().bitsLT(VT)) {
6348       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6349     } else if (X.getValueType().bitsGT(VT)) {
6350       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6351     }
6352     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6353     Mask = Mask.zext(VT.getSizeInBits());
6354     SDLoc DL(N);
6355     return DAG.getNode(ISD::AND, DL, VT,
6356                        X, DAG.getConstant(Mask, DL, VT));
6357   }
6358
6359   // fold (aext (load x)) -> (aext (truncate (extload x)))
6360   // None of the supported targets knows how to perform load and any_ext
6361   // on vectors in one instruction.  We only perform this transformation on
6362   // scalars.
6363   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6364       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6365       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6366     bool DoXform = true;
6367     SmallVector<SDNode*, 4> SetCCs;
6368     if (!N0.hasOneUse())
6369       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6370     if (DoXform) {
6371       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6372       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6373                                        LN0->getChain(),
6374                                        LN0->getBasePtr(), N0.getValueType(),
6375                                        LN0->getMemOperand());
6376       CombineTo(N, ExtLoad);
6377       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6378                                   N0.getValueType(), ExtLoad);
6379       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6380       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6381                       ISD::ANY_EXTEND);
6382       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6383     }
6384   }
6385
6386   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6387   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6388   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6389   if (N0.getOpcode() == ISD::LOAD &&
6390       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6391       N0.hasOneUse()) {
6392     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6393     ISD::LoadExtType ExtType = LN0->getExtensionType();
6394     EVT MemVT = LN0->getMemoryVT();
6395     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6396       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6397                                        VT, LN0->getChain(), LN0->getBasePtr(),
6398                                        MemVT, LN0->getMemOperand());
6399       CombineTo(N, ExtLoad);
6400       CombineTo(N0.getNode(),
6401                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6402                             N0.getValueType(), ExtLoad),
6403                 ExtLoad.getValue(1));
6404       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6405     }
6406   }
6407
6408   if (N0.getOpcode() == ISD::SETCC) {
6409     // For vectors:
6410     // aext(setcc) -> vsetcc
6411     // aext(setcc) -> truncate(vsetcc)
6412     // aext(setcc) -> aext(vsetcc)
6413     // Only do this before legalize for now.
6414     if (VT.isVector() && !LegalOperations) {
6415       EVT N0VT = N0.getOperand(0).getValueType();
6416         // We know that the # elements of the results is the same as the
6417         // # elements of the compare (and the # elements of the compare result
6418         // for that matter).  Check to see that they are the same size.  If so,
6419         // we know that the element size of the sext'd result matches the
6420         // element size of the compare operands.
6421       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6422         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6423                              N0.getOperand(1),
6424                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6425       // If the desired elements are smaller or larger than the source
6426       // elements we can use a matching integer vector type and then
6427       // truncate/any extend
6428       else {
6429         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6430         SDValue VsetCC =
6431           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6432                         N0.getOperand(1),
6433                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6434         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6435       }
6436     }
6437
6438     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6439     SDLoc DL(N);
6440     SDValue SCC =
6441       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6442                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6443                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6444     if (SCC.getNode())
6445       return SCC;
6446   }
6447
6448   return SDValue();
6449 }
6450
6451 /// See if the specified operand can be simplified with the knowledge that only
6452 /// the bits specified by Mask are used.  If so, return the simpler operand,
6453 /// otherwise return a null SDValue.
6454 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6455   switch (V.getOpcode()) {
6456   default: break;
6457   case ISD::Constant: {
6458     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6459     assert(CV && "Const value should be ConstSDNode.");
6460     const APInt &CVal = CV->getAPIntValue();
6461     APInt NewVal = CVal & Mask;
6462     if (NewVal != CVal)
6463       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6464     break;
6465   }
6466   case ISD::OR:
6467   case ISD::XOR:
6468     // If the LHS or RHS don't contribute bits to the or, drop them.
6469     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6470       return V.getOperand(1);
6471     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6472       return V.getOperand(0);
6473     break;
6474   case ISD::SRL:
6475     // Only look at single-use SRLs.
6476     if (!V.getNode()->hasOneUse())
6477       break;
6478     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6479       // See if we can recursively simplify the LHS.
6480       unsigned Amt = RHSC->getZExtValue();
6481
6482       // Watch out for shift count overflow though.
6483       if (Amt >= Mask.getBitWidth()) break;
6484       APInt NewMask = Mask << Amt;
6485       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6486       if (SimplifyLHS.getNode())
6487         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6488                            SimplifyLHS, V.getOperand(1));
6489     }
6490   }
6491   return SDValue();
6492 }
6493
6494 /// If the result of a wider load is shifted to right of N  bits and then
6495 /// truncated to a narrower type and where N is a multiple of number of bits of
6496 /// the narrower type, transform it to a narrower load from address + N / num of
6497 /// bits of new type. If the result is to be extended, also fold the extension
6498 /// to form a extending load.
6499 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6500   unsigned Opc = N->getOpcode();
6501
6502   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6503   SDValue N0 = N->getOperand(0);
6504   EVT VT = N->getValueType(0);
6505   EVT ExtVT = VT;
6506
6507   // This transformation isn't valid for vector loads.
6508   if (VT.isVector())
6509     return SDValue();
6510
6511   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6512   // extended to VT.
6513   if (Opc == ISD::SIGN_EXTEND_INREG) {
6514     ExtType = ISD::SEXTLOAD;
6515     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6516   } else if (Opc == ISD::SRL) {
6517     // Another special-case: SRL is basically zero-extending a narrower value.
6518     ExtType = ISD::ZEXTLOAD;
6519     N0 = SDValue(N, 0);
6520     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6521     if (!N01) return SDValue();
6522     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6523                               VT.getSizeInBits() - N01->getZExtValue());
6524   }
6525   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6526     return SDValue();
6527
6528   unsigned EVTBits = ExtVT.getSizeInBits();
6529
6530   // Do not generate loads of non-round integer types since these can
6531   // be expensive (and would be wrong if the type is not byte sized).
6532   if (!ExtVT.isRound())
6533     return SDValue();
6534
6535   unsigned ShAmt = 0;
6536   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6537     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6538       ShAmt = N01->getZExtValue();
6539       // Is the shift amount a multiple of size of VT?
6540       if ((ShAmt & (EVTBits-1)) == 0) {
6541         N0 = N0.getOperand(0);
6542         // Is the load width a multiple of size of VT?
6543         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6544           return SDValue();
6545       }
6546
6547       // At this point, we must have a load or else we can't do the transform.
6548       if (!isa<LoadSDNode>(N0)) return SDValue();
6549
6550       // Because a SRL must be assumed to *need* to zero-extend the high bits
6551       // (as opposed to anyext the high bits), we can't combine the zextload
6552       // lowering of SRL and an sextload.
6553       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6554         return SDValue();
6555
6556       // If the shift amount is larger than the input type then we're not
6557       // accessing any of the loaded bytes.  If the load was a zextload/extload
6558       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6559       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6560         return SDValue();
6561     }
6562   }
6563
6564   // If the load is shifted left (and the result isn't shifted back right),
6565   // we can fold the truncate through the shift.
6566   unsigned ShLeftAmt = 0;
6567   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6568       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6569     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6570       ShLeftAmt = N01->getZExtValue();
6571       N0 = N0.getOperand(0);
6572     }
6573   }
6574
6575   // If we haven't found a load, we can't narrow it.  Don't transform one with
6576   // multiple uses, this would require adding a new load.
6577   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6578     return SDValue();
6579
6580   // Don't change the width of a volatile load.
6581   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6582   if (LN0->isVolatile())
6583     return SDValue();
6584
6585   // Verify that we are actually reducing a load width here.
6586   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6587     return SDValue();
6588
6589   // For the transform to be legal, the load must produce only two values
6590   // (the value loaded and the chain).  Don't transform a pre-increment
6591   // load, for example, which produces an extra value.  Otherwise the
6592   // transformation is not equivalent, and the downstream logic to replace
6593   // uses gets things wrong.
6594   if (LN0->getNumValues() > 2)
6595     return SDValue();
6596
6597   // If the load that we're shrinking is an extload and we're not just
6598   // discarding the extension we can't simply shrink the load. Bail.
6599   // TODO: It would be possible to merge the extensions in some cases.
6600   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6601       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6602     return SDValue();
6603
6604   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6605     return SDValue();
6606
6607   EVT PtrType = N0.getOperand(1).getValueType();
6608
6609   if (PtrType == MVT::Untyped || PtrType.isExtended())
6610     // It's not possible to generate a constant of extended or untyped type.
6611     return SDValue();
6612
6613   // For big endian targets, we need to adjust the offset to the pointer to
6614   // load the correct bytes.
6615   if (TLI.isBigEndian()) {
6616     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6617     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6618     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6619   }
6620
6621   uint64_t PtrOff = ShAmt / 8;
6622   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6623   SDLoc DL(LN0);
6624   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6625                                PtrType, LN0->getBasePtr(),
6626                                DAG.getConstant(PtrOff, DL, PtrType));
6627   AddToWorklist(NewPtr.getNode());
6628
6629   SDValue Load;
6630   if (ExtType == ISD::NON_EXTLOAD)
6631     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6632                         LN0->getPointerInfo().getWithOffset(PtrOff),
6633                         LN0->isVolatile(), LN0->isNonTemporal(),
6634                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6635   else
6636     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6637                           LN0->getPointerInfo().getWithOffset(PtrOff),
6638                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6639                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6640
6641   // Replace the old load's chain with the new load's chain.
6642   WorklistRemover DeadNodes(*this);
6643   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6644
6645   // Shift the result left, if we've swallowed a left shift.
6646   SDValue Result = Load;
6647   if (ShLeftAmt != 0) {
6648     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6649     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6650       ShImmTy = VT;
6651     // If the shift amount is as large as the result size (but, presumably,
6652     // no larger than the source) then the useful bits of the result are
6653     // zero; we can't simply return the shortened shift, because the result
6654     // of that operation is undefined.
6655     SDLoc DL(N0);
6656     if (ShLeftAmt >= VT.getSizeInBits())
6657       Result = DAG.getConstant(0, DL, VT);
6658     else
6659       Result = DAG.getNode(ISD::SHL, DL, VT,
6660                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6661   }
6662
6663   // Return the new loaded value.
6664   return Result;
6665 }
6666
6667 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6668   SDValue N0 = N->getOperand(0);
6669   SDValue N1 = N->getOperand(1);
6670   EVT VT = N->getValueType(0);
6671   EVT EVT = cast<VTSDNode>(N1)->getVT();
6672   unsigned VTBits = VT.getScalarType().getSizeInBits();
6673   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6674
6675   // fold (sext_in_reg c1) -> c1
6676   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6677     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6678
6679   // If the input is already sign extended, just drop the extension.
6680   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6681     return N0;
6682
6683   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6684   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6685       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6686     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6687                        N0.getOperand(0), N1);
6688
6689   // fold (sext_in_reg (sext x)) -> (sext x)
6690   // fold (sext_in_reg (aext x)) -> (sext x)
6691   // if x is small enough.
6692   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6693     SDValue N00 = N0.getOperand(0);
6694     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6695         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6696       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6697   }
6698
6699   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6700   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6701     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6702
6703   // fold operands of sext_in_reg based on knowledge that the top bits are not
6704   // demanded.
6705   if (SimplifyDemandedBits(SDValue(N, 0)))
6706     return SDValue(N, 0);
6707
6708   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6709   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6710   SDValue NarrowLoad = ReduceLoadWidth(N);
6711   if (NarrowLoad.getNode())
6712     return NarrowLoad;
6713
6714   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6715   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6716   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6717   if (N0.getOpcode() == ISD::SRL) {
6718     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6719       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6720         // We can turn this into an SRA iff the input to the SRL is already sign
6721         // extended enough.
6722         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6723         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6724           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6725                              N0.getOperand(0), N0.getOperand(1));
6726       }
6727   }
6728
6729   // fold (sext_inreg (extload x)) -> (sextload x)
6730   if (ISD::isEXTLoad(N0.getNode()) &&
6731       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6732       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6733       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6734        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6735     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6736     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6737                                      LN0->getChain(),
6738                                      LN0->getBasePtr(), EVT,
6739                                      LN0->getMemOperand());
6740     CombineTo(N, ExtLoad);
6741     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6742     AddToWorklist(ExtLoad.getNode());
6743     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6744   }
6745   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6746   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6747       N0.hasOneUse() &&
6748       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6749       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6750        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6751     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6752     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6753                                      LN0->getChain(),
6754                                      LN0->getBasePtr(), EVT,
6755                                      LN0->getMemOperand());
6756     CombineTo(N, ExtLoad);
6757     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6758     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6759   }
6760
6761   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6762   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6763     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6764                                        N0.getOperand(1), false);
6765     if (BSwap.getNode())
6766       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6767                          BSwap, N1);
6768   }
6769
6770   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6771   // into a build_vector.
6772   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6773     SmallVector<SDValue, 8> Elts;
6774     unsigned NumElts = N0->getNumOperands();
6775     unsigned ShAmt = VTBits - EVTBits;
6776
6777     for (unsigned i = 0; i != NumElts; ++i) {
6778       SDValue Op = N0->getOperand(i);
6779       if (Op->getOpcode() == ISD::UNDEF) {
6780         Elts.push_back(Op);
6781         continue;
6782       }
6783
6784       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6785       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6786       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6787                                      SDLoc(Op), Op.getValueType()));
6788     }
6789
6790     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6791   }
6792
6793   return SDValue();
6794 }
6795
6796 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6797   SDValue N0 = N->getOperand(0);
6798   EVT VT = N->getValueType(0);
6799   bool isLE = TLI.isLittleEndian();
6800
6801   // noop truncate
6802   if (N0.getValueType() == N->getValueType(0))
6803     return N0;
6804   // fold (truncate c1) -> c1
6805   if (isConstantIntBuildVectorOrConstantInt(N0))
6806     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6807   // fold (truncate (truncate x)) -> (truncate x)
6808   if (N0.getOpcode() == ISD::TRUNCATE)
6809     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6810   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6811   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6812       N0.getOpcode() == ISD::SIGN_EXTEND ||
6813       N0.getOpcode() == ISD::ANY_EXTEND) {
6814     if (N0.getOperand(0).getValueType().bitsLT(VT))
6815       // if the source is smaller than the dest, we still need an extend
6816       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6817                          N0.getOperand(0));
6818     if (N0.getOperand(0).getValueType().bitsGT(VT))
6819       // if the source is larger than the dest, than we just need the truncate
6820       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6821     // if the source and dest are the same type, we can drop both the extend
6822     // and the truncate.
6823     return N0.getOperand(0);
6824   }
6825
6826   // Fold extract-and-trunc into a narrow extract. For example:
6827   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6828   //   i32 y = TRUNCATE(i64 x)
6829   //        -- becomes --
6830   //   v16i8 b = BITCAST (v2i64 val)
6831   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6832   //
6833   // Note: We only run this optimization after type legalization (which often
6834   // creates this pattern) and before operation legalization after which
6835   // we need to be more careful about the vector instructions that we generate.
6836   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6837       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6838
6839     EVT VecTy = N0.getOperand(0).getValueType();
6840     EVT ExTy = N0.getValueType();
6841     EVT TrTy = N->getValueType(0);
6842
6843     unsigned NumElem = VecTy.getVectorNumElements();
6844     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6845
6846     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6847     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6848
6849     SDValue EltNo = N0->getOperand(1);
6850     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6851       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6852       EVT IndexTy = TLI.getVectorIdxTy();
6853       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6854
6855       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6856                               NVT, N0.getOperand(0));
6857
6858       SDLoc DL(N);
6859       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6860                          DL, TrTy, V,
6861                          DAG.getConstant(Index, DL, IndexTy));
6862     }
6863   }
6864
6865   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6866   if (N0.getOpcode() == ISD::SELECT) {
6867     EVT SrcVT = N0.getValueType();
6868     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6869         TLI.isTruncateFree(SrcVT, VT)) {
6870       SDLoc SL(N0);
6871       SDValue Cond = N0.getOperand(0);
6872       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6873       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6874       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6875     }
6876   }
6877
6878   // Fold a series of buildvector, bitcast, and truncate if possible.
6879   // For example fold
6880   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6881   //   (2xi32 (buildvector x, y)).
6882   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6883       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6884       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6885       N0.getOperand(0).hasOneUse()) {
6886
6887     SDValue BuildVect = N0.getOperand(0);
6888     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6889     EVT TruncVecEltTy = VT.getVectorElementType();
6890
6891     // Check that the element types match.
6892     if (BuildVectEltTy == TruncVecEltTy) {
6893       // Now we only need to compute the offset of the truncated elements.
6894       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6895       unsigned TruncVecNumElts = VT.getVectorNumElements();
6896       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6897
6898       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6899              "Invalid number of elements");
6900
6901       SmallVector<SDValue, 8> Opnds;
6902       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6903         Opnds.push_back(BuildVect.getOperand(i));
6904
6905       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6906     }
6907   }
6908
6909   // See if we can simplify the input to this truncate through knowledge that
6910   // only the low bits are being used.
6911   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6912   // Currently we only perform this optimization on scalars because vectors
6913   // may have different active low bits.
6914   if (!VT.isVector()) {
6915     SDValue Shorter =
6916       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6917                                                VT.getSizeInBits()));
6918     if (Shorter.getNode())
6919       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6920   }
6921   // fold (truncate (load x)) -> (smaller load x)
6922   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6923   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6924     SDValue Reduced = ReduceLoadWidth(N);
6925     if (Reduced.getNode())
6926       return Reduced;
6927     // Handle the case where the load remains an extending load even
6928     // after truncation.
6929     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6930       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6931       if (!LN0->isVolatile() &&
6932           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6933         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6934                                          VT, LN0->getChain(), LN0->getBasePtr(),
6935                                          LN0->getMemoryVT(),
6936                                          LN0->getMemOperand());
6937         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6938         return NewLoad;
6939       }
6940     }
6941   }
6942   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6943   // where ... are all 'undef'.
6944   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6945     SmallVector<EVT, 8> VTs;
6946     SDValue V;
6947     unsigned Idx = 0;
6948     unsigned NumDefs = 0;
6949
6950     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6951       SDValue X = N0.getOperand(i);
6952       if (X.getOpcode() != ISD::UNDEF) {
6953         V = X;
6954         Idx = i;
6955         NumDefs++;
6956       }
6957       // Stop if more than one members are non-undef.
6958       if (NumDefs > 1)
6959         break;
6960       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6961                                      VT.getVectorElementType(),
6962                                      X.getValueType().getVectorNumElements()));
6963     }
6964
6965     if (NumDefs == 0)
6966       return DAG.getUNDEF(VT);
6967
6968     if (NumDefs == 1) {
6969       assert(V.getNode() && "The single defined operand is empty!");
6970       SmallVector<SDValue, 8> Opnds;
6971       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6972         if (i != Idx) {
6973           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6974           continue;
6975         }
6976         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6977         AddToWorklist(NV.getNode());
6978         Opnds.push_back(NV);
6979       }
6980       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6981     }
6982   }
6983
6984   // Simplify the operands using demanded-bits information.
6985   if (!VT.isVector() &&
6986       SimplifyDemandedBits(SDValue(N, 0)))
6987     return SDValue(N, 0);
6988
6989   return SDValue();
6990 }
6991
6992 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6993   SDValue Elt = N->getOperand(i);
6994   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6995     return Elt.getNode();
6996   return Elt.getOperand(Elt.getResNo()).getNode();
6997 }
6998
6999 /// build_pair (load, load) -> load
7000 /// if load locations are consecutive.
7001 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7002   assert(N->getOpcode() == ISD::BUILD_PAIR);
7003
7004   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7005   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7006   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7007       LD1->getAddressSpace() != LD2->getAddressSpace())
7008     return SDValue();
7009   EVT LD1VT = LD1->getValueType(0);
7010
7011   if (ISD::isNON_EXTLoad(LD2) &&
7012       LD2->hasOneUse() &&
7013       // If both are volatile this would reduce the number of volatile loads.
7014       // If one is volatile it might be ok, but play conservative and bail out.
7015       !LD1->isVolatile() &&
7016       !LD2->isVolatile() &&
7017       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7018     unsigned Align = LD1->getAlignment();
7019     unsigned NewAlign = TLI.getDataLayout()->
7020       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7021
7022     if (NewAlign <= Align &&
7023         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7024       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7025                          LD1->getBasePtr(), LD1->getPointerInfo(),
7026                          false, false, false, Align);
7027   }
7028
7029   return SDValue();
7030 }
7031
7032 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7033   SDValue N0 = N->getOperand(0);
7034   EVT VT = N->getValueType(0);
7035
7036   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7037   // Only do this before legalize, since afterward the target may be depending
7038   // on the bitconvert.
7039   // First check to see if this is all constant.
7040   if (!LegalTypes &&
7041       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7042       VT.isVector()) {
7043     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7044
7045     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7046     assert(!DestEltVT.isVector() &&
7047            "Element type of vector ValueType must not be vector!");
7048     if (isSimple)
7049       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7050   }
7051
7052   // If the input is a constant, let getNode fold it.
7053   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7054     // If we can't allow illegal operations, we need to check that this is just
7055     // a fp -> int or int -> conversion and that the resulting operation will
7056     // be legal.
7057     if (!LegalOperations ||
7058         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7059          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7060         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7061          TLI.isOperationLegal(ISD::Constant, VT)))
7062       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7063   }
7064
7065   // (conv (conv x, t1), t2) -> (conv x, t2)
7066   if (N0.getOpcode() == ISD::BITCAST)
7067     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7068                        N0.getOperand(0));
7069
7070   // fold (conv (load x)) -> (load (conv*)x)
7071   // If the resultant load doesn't need a higher alignment than the original!
7072   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7073       // Do not change the width of a volatile load.
7074       !cast<LoadSDNode>(N0)->isVolatile() &&
7075       // Do not remove the cast if the types differ in endian layout.
7076       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7077       TLI.hasBigEndianPartOrdering(VT) &&
7078       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7079       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7080     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7081     unsigned Align = TLI.getDataLayout()->
7082       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7083     unsigned OrigAlign = LN0->getAlignment();
7084
7085     if (Align <= OrigAlign) {
7086       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7087                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7088                                  LN0->isVolatile(), LN0->isNonTemporal(),
7089                                  LN0->isInvariant(), OrigAlign,
7090                                  LN0->getAAInfo());
7091       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7092       return Load;
7093     }
7094   }
7095
7096   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7097   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7098   // This often reduces constant pool loads.
7099   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7100        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7101       N0.getNode()->hasOneUse() && VT.isInteger() &&
7102       !VT.isVector() && !N0.getValueType().isVector()) {
7103     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7104                                   N0.getOperand(0));
7105     AddToWorklist(NewConv.getNode());
7106
7107     SDLoc DL(N);
7108     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7109     if (N0.getOpcode() == ISD::FNEG)
7110       return DAG.getNode(ISD::XOR, DL, VT,
7111                          NewConv, DAG.getConstant(SignBit, DL, VT));
7112     assert(N0.getOpcode() == ISD::FABS);
7113     return DAG.getNode(ISD::AND, DL, VT,
7114                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7115   }
7116
7117   // fold (bitconvert (fcopysign cst, x)) ->
7118   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7119   // Note that we don't handle (copysign x, cst) because this can always be
7120   // folded to an fneg or fabs.
7121   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7122       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7123       VT.isInteger() && !VT.isVector()) {
7124     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7125     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7126     if (isTypeLegal(IntXVT)) {
7127       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7128                               IntXVT, N0.getOperand(1));
7129       AddToWorklist(X.getNode());
7130
7131       // If X has a different width than the result/lhs, sext it or truncate it.
7132       unsigned VTWidth = VT.getSizeInBits();
7133       if (OrigXWidth < VTWidth) {
7134         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7135         AddToWorklist(X.getNode());
7136       } else if (OrigXWidth > VTWidth) {
7137         // To get the sign bit in the right place, we have to shift it right
7138         // before truncating.
7139         SDLoc DL(X);
7140         X = DAG.getNode(ISD::SRL, DL,
7141                         X.getValueType(), X,
7142                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7143                                         X.getValueType()));
7144         AddToWorklist(X.getNode());
7145         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7146         AddToWorklist(X.getNode());
7147       }
7148
7149       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7150       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7151                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7152       AddToWorklist(X.getNode());
7153
7154       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7155                                 VT, N0.getOperand(0));
7156       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7157                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7158       AddToWorklist(Cst.getNode());
7159
7160       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7161     }
7162   }
7163
7164   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7165   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7166     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7167     if (CombineLD.getNode())
7168       return CombineLD;
7169   }
7170
7171   // Remove double bitcasts from shuffles - this is often a legacy of
7172   // XformToShuffleWithZero being used to combine bitmaskings (of
7173   // float vectors bitcast to integer vectors) into shuffles.
7174   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7175   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7176       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7177       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7178       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7179     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7180
7181     // If operands are a bitcast, peek through if it casts the original VT.
7182     // If operands are a UNDEF or constant, just bitcast back to original VT.
7183     auto PeekThroughBitcast = [&](SDValue Op) {
7184       if (Op.getOpcode() == ISD::BITCAST &&
7185           Op.getOperand(0)->getValueType(0) == VT)
7186         return SDValue(Op.getOperand(0));
7187       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7188           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7189         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7190       return SDValue();
7191     };
7192
7193     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7194     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7195     if (!(SV0 && SV1))
7196       return SDValue();
7197
7198     int MaskScale =
7199         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7200     SmallVector<int, 8> NewMask;
7201     for (int M : SVN->getMask())
7202       for (int i = 0; i != MaskScale; ++i)
7203         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7204
7205     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7206     if (!LegalMask) {
7207       std::swap(SV0, SV1);
7208       ShuffleVectorSDNode::commuteMask(NewMask);
7209       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7210     }
7211
7212     if (LegalMask)
7213       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7214   }
7215
7216   return SDValue();
7217 }
7218
7219 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7220   EVT VT = N->getValueType(0);
7221   return CombineConsecutiveLoads(N, VT);
7222 }
7223
7224 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7225 /// operands. DstEltVT indicates the destination element value type.
7226 SDValue DAGCombiner::
7227 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7228   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7229
7230   // If this is already the right type, we're done.
7231   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7232
7233   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7234   unsigned DstBitSize = DstEltVT.getSizeInBits();
7235
7236   // If this is a conversion of N elements of one type to N elements of another
7237   // type, convert each element.  This handles FP<->INT cases.
7238   if (SrcBitSize == DstBitSize) {
7239     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7240                               BV->getValueType(0).getVectorNumElements());
7241
7242     // Due to the FP element handling below calling this routine recursively,
7243     // we can end up with a scalar-to-vector node here.
7244     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7245       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7246                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7247                                      DstEltVT, BV->getOperand(0)));
7248
7249     SmallVector<SDValue, 8> Ops;
7250     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7251       SDValue Op = BV->getOperand(i);
7252       // If the vector element type is not legal, the BUILD_VECTOR operands
7253       // are promoted and implicitly truncated.  Make that explicit here.
7254       if (Op.getValueType() != SrcEltVT)
7255         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7256       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7257                                 DstEltVT, Op));
7258       AddToWorklist(Ops.back().getNode());
7259     }
7260     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7261   }
7262
7263   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7264   // handle annoying details of growing/shrinking FP values, we convert them to
7265   // int first.
7266   if (SrcEltVT.isFloatingPoint()) {
7267     // Convert the input float vector to a int vector where the elements are the
7268     // same sizes.
7269     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7270     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7271     SrcEltVT = IntVT;
7272   }
7273
7274   // Now we know the input is an integer vector.  If the output is a FP type,
7275   // convert to integer first, then to FP of the right size.
7276   if (DstEltVT.isFloatingPoint()) {
7277     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7278     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7279
7280     // Next, convert to FP elements of the same size.
7281     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7282   }
7283
7284   SDLoc DL(BV);
7285
7286   // Okay, we know the src/dst types are both integers of differing types.
7287   // Handling growing first.
7288   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7289   if (SrcBitSize < DstBitSize) {
7290     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7291
7292     SmallVector<SDValue, 8> Ops;
7293     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7294          i += NumInputsPerOutput) {
7295       bool isLE = TLI.isLittleEndian();
7296       APInt NewBits = APInt(DstBitSize, 0);
7297       bool EltIsUndef = true;
7298       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7299         // Shift the previously computed bits over.
7300         NewBits <<= SrcBitSize;
7301         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7302         if (Op.getOpcode() == ISD::UNDEF) continue;
7303         EltIsUndef = false;
7304
7305         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7306                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7307       }
7308
7309       if (EltIsUndef)
7310         Ops.push_back(DAG.getUNDEF(DstEltVT));
7311       else
7312         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7313     }
7314
7315     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7316     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7317   }
7318
7319   // Finally, this must be the case where we are shrinking elements: each input
7320   // turns into multiple outputs.
7321   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7322   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7323                             NumOutputsPerInput*BV->getNumOperands());
7324   SmallVector<SDValue, 8> Ops;
7325
7326   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7327     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7328       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7329       continue;
7330     }
7331
7332     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7333                   getAPIntValue().zextOrTrunc(SrcBitSize);
7334
7335     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7336       APInt ThisVal = OpVal.trunc(DstBitSize);
7337       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7338       OpVal = OpVal.lshr(DstBitSize);
7339     }
7340
7341     // For big endian targets, swap the order of the pieces of each element.
7342     if (TLI.isBigEndian())
7343       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7344   }
7345
7346   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7347 }
7348
7349 /// Try to perform FMA combining on a given FADD node.
7350 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7351   SDValue N0 = N->getOperand(0);
7352   SDValue N1 = N->getOperand(1);
7353   EVT VT = N->getValueType(0);
7354   SDLoc SL(N);
7355
7356   const TargetOptions &Options = DAG.getTarget().Options;
7357   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7358                        Options.UnsafeFPMath);
7359
7360   // Floating-point multiply-add with intermediate rounding.
7361   bool HasFMAD = (LegalOperations &&
7362                   TLI.isOperationLegal(ISD::FMAD, VT));
7363
7364   // Floating-point multiply-add without intermediate rounding.
7365   bool HasFMA = ((!LegalOperations ||
7366                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7367                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7368                  UnsafeFPMath);
7369
7370   // No valid opcode, do not combine.
7371   if (!HasFMAD && !HasFMA)
7372     return SDValue();
7373
7374   // Always prefer FMAD to FMA for precision.
7375   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7376   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7377   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7378
7379   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7380   if (N0.getOpcode() == ISD::FMUL &&
7381       (Aggressive || N0->hasOneUse())) {
7382     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7383                        N0.getOperand(0), N0.getOperand(1), N1);
7384   }
7385
7386   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7387   // Note: Commutes FADD operands.
7388   if (N1.getOpcode() == ISD::FMUL &&
7389       (Aggressive || N1->hasOneUse())) {
7390     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7391                        N1.getOperand(0), N1.getOperand(1), N0);
7392   }
7393
7394   // Look through FP_EXTEND nodes to do more combining.
7395   if (UnsafeFPMath && LookThroughFPExt) {
7396     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7397     if (N0.getOpcode() == ISD::FP_EXTEND) {
7398       SDValue N00 = N0.getOperand(0);
7399       if (N00.getOpcode() == ISD::FMUL)
7400         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7401                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7402                                        N00.getOperand(0)),
7403                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7404                                        N00.getOperand(1)), N1);
7405     }
7406
7407     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7408     // Note: Commutes FADD operands.
7409     if (N1.getOpcode() == ISD::FP_EXTEND) {
7410       SDValue N10 = N1.getOperand(0);
7411       if (N10.getOpcode() == ISD::FMUL)
7412         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7414                                        N10.getOperand(0)),
7415                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416                                        N10.getOperand(1)), N0);
7417     }
7418   }
7419
7420   // More folding opportunities when target permits.
7421   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7422     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7423     if (N0.getOpcode() == PreferredFusedOpcode &&
7424         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7425       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7426                          N0.getOperand(0), N0.getOperand(1),
7427                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7428                                      N0.getOperand(2).getOperand(0),
7429                                      N0.getOperand(2).getOperand(1),
7430                                      N1));
7431     }
7432
7433     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7434     if (N1->getOpcode() == PreferredFusedOpcode &&
7435         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7436       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7437                          N1.getOperand(0), N1.getOperand(1),
7438                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7439                                      N1.getOperand(2).getOperand(0),
7440                                      N1.getOperand(2).getOperand(1),
7441                                      N0));
7442     }
7443
7444     if (UnsafeFPMath && LookThroughFPExt) {
7445       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7446       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7447       auto FoldFAddFMAFPExtFMul = [&] (
7448           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7449         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7450                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7451                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7452                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7453                                        Z));
7454       };
7455       if (N0.getOpcode() == PreferredFusedOpcode) {
7456         SDValue N02 = N0.getOperand(2);
7457         if (N02.getOpcode() == ISD::FP_EXTEND) {
7458           SDValue N020 = N02.getOperand(0);
7459           if (N020.getOpcode() == ISD::FMUL)
7460             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7461                                         N020.getOperand(0), N020.getOperand(1),
7462                                         N1);
7463         }
7464       }
7465
7466       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7467       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7468       // FIXME: This turns two single-precision and one double-precision
7469       // operation into two double-precision operations, which might not be
7470       // interesting for all targets, especially GPUs.
7471       auto FoldFAddFPExtFMAFMul = [&] (
7472           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7473         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7475                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7476                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7477                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7478                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7479                                        Z));
7480       };
7481       if (N0.getOpcode() == ISD::FP_EXTEND) {
7482         SDValue N00 = N0.getOperand(0);
7483         if (N00.getOpcode() == PreferredFusedOpcode) {
7484           SDValue N002 = N00.getOperand(2);
7485           if (N002.getOpcode() == ISD::FMUL)
7486             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7487                                         N002.getOperand(0), N002.getOperand(1),
7488                                         N1);
7489         }
7490       }
7491
7492       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7493       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7494       if (N1.getOpcode() == PreferredFusedOpcode) {
7495         SDValue N12 = N1.getOperand(2);
7496         if (N12.getOpcode() == ISD::FP_EXTEND) {
7497           SDValue N120 = N12.getOperand(0);
7498           if (N120.getOpcode() == ISD::FMUL)
7499             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7500                                         N120.getOperand(0), N120.getOperand(1),
7501                                         N0);
7502         }
7503       }
7504
7505       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7506       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7507       // FIXME: This turns two single-precision and one double-precision
7508       // operation into two double-precision operations, which might not be
7509       // interesting for all targets, especially GPUs.
7510       if (N1.getOpcode() == ISD::FP_EXTEND) {
7511         SDValue N10 = N1.getOperand(0);
7512         if (N10.getOpcode() == PreferredFusedOpcode) {
7513           SDValue N102 = N10.getOperand(2);
7514           if (N102.getOpcode() == ISD::FMUL)
7515             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7516                                         N102.getOperand(0), N102.getOperand(1),
7517                                         N0);
7518         }
7519       }
7520     }
7521   }
7522
7523   return SDValue();
7524 }
7525
7526 /// Try to perform FMA combining on a given FSUB node.
7527 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7528   SDValue N0 = N->getOperand(0);
7529   SDValue N1 = N->getOperand(1);
7530   EVT VT = N->getValueType(0);
7531   SDLoc SL(N);
7532
7533   const TargetOptions &Options = DAG.getTarget().Options;
7534   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7535                        Options.UnsafeFPMath);
7536
7537   // Floating-point multiply-add with intermediate rounding.
7538   bool HasFMAD = (LegalOperations &&
7539                   TLI.isOperationLegal(ISD::FMAD, VT));
7540
7541   // Floating-point multiply-add without intermediate rounding.
7542   bool HasFMA = ((!LegalOperations ||
7543                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7544                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7545                  UnsafeFPMath);
7546
7547   // No valid opcode, do not combine.
7548   if (!HasFMAD && !HasFMA)
7549     return SDValue();
7550
7551   // Always prefer FMAD to FMA for precision.
7552   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7553   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7554   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7555
7556   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7557   if (N0.getOpcode() == ISD::FMUL &&
7558       (Aggressive || N0->hasOneUse())) {
7559     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                        N0.getOperand(0), N0.getOperand(1),
7561                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7562   }
7563
7564   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7565   // Note: Commutes FSUB operands.
7566   if (N1.getOpcode() == ISD::FMUL &&
7567       (Aggressive || N1->hasOneUse()))
7568     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7569                        DAG.getNode(ISD::FNEG, SL, VT,
7570                                    N1.getOperand(0)),
7571                        N1.getOperand(1), N0);
7572
7573   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7574   if (N0.getOpcode() == ISD::FNEG &&
7575       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7576       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7577     SDValue N00 = N0.getOperand(0).getOperand(0);
7578     SDValue N01 = N0.getOperand(0).getOperand(1);
7579     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7580                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7581                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7582   }
7583
7584   // Look through FP_EXTEND nodes to do more combining.
7585   if (UnsafeFPMath && LookThroughFPExt) {
7586     // fold (fsub (fpext (fmul x, y)), z)
7587     //   -> (fma (fpext x), (fpext y), (fneg z))
7588     if (N0.getOpcode() == ISD::FP_EXTEND) {
7589       SDValue N00 = N0.getOperand(0);
7590       if (N00.getOpcode() == ISD::FMUL)
7591         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7593                                        N00.getOperand(0)),
7594                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7595                                        N00.getOperand(1)),
7596                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7597     }
7598
7599     // fold (fsub x, (fpext (fmul y, z)))
7600     //   -> (fma (fneg (fpext y)), (fpext z), x)
7601     // Note: Commutes FSUB operands.
7602     if (N1.getOpcode() == ISD::FP_EXTEND) {
7603       SDValue N10 = N1.getOperand(0);
7604       if (N10.getOpcode() == ISD::FMUL)
7605         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7606                            DAG.getNode(ISD::FNEG, SL, VT,
7607                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7608                                                    N10.getOperand(0))),
7609                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7610                                        N10.getOperand(1)),
7611                            N0);
7612     }
7613
7614     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7615     //   -> (fneg (fma (fpext x), (fpext y), z))
7616     // Note: This could be removed with appropriate canonicalization of the
7617     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7618     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7619     // from implementing the canonicalization in visitFSUB.
7620     if (N0.getOpcode() == ISD::FP_EXTEND) {
7621       SDValue N00 = N0.getOperand(0);
7622       if (N00.getOpcode() == ISD::FNEG) {
7623         SDValue N000 = N00.getOperand(0);
7624         if (N000.getOpcode() == ISD::FMUL) {
7625           return DAG.getNode(ISD::FNEG, SL, VT,
7626                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7627                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7628                                                      N000.getOperand(0)),
7629                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7630                                                      N000.getOperand(1)),
7631                                          N1));
7632         }
7633       }
7634     }
7635
7636     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7637     //   -> (fneg (fma (fpext x)), (fpext y), z)
7638     // Note: This could be removed with appropriate canonicalization of the
7639     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7640     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7641     // from implementing the canonicalization in visitFSUB.
7642     if (N0.getOpcode() == ISD::FNEG) {
7643       SDValue N00 = N0.getOperand(0);
7644       if (N00.getOpcode() == ISD::FP_EXTEND) {
7645         SDValue N000 = N00.getOperand(0);
7646         if (N000.getOpcode() == ISD::FMUL) {
7647           return DAG.getNode(ISD::FNEG, SL, VT,
7648                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7649                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7650                                                      N000.getOperand(0)),
7651                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7652                                                      N000.getOperand(1)),
7653                                          N1));
7654         }
7655       }
7656     }
7657
7658   }
7659
7660   // More folding opportunities when target permits.
7661   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7662     // fold (fsub (fma x, y, (fmul u, v)), z)
7663     //   -> (fma x, y (fma u, v, (fneg z)))
7664     if (N0.getOpcode() == PreferredFusedOpcode &&
7665         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7666       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7667                          N0.getOperand(0), N0.getOperand(1),
7668                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7669                                      N0.getOperand(2).getOperand(0),
7670                                      N0.getOperand(2).getOperand(1),
7671                                      DAG.getNode(ISD::FNEG, SL, VT,
7672                                                  N1)));
7673     }
7674
7675     // fold (fsub x, (fma y, z, (fmul u, v)))
7676     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7677     if (N1.getOpcode() == PreferredFusedOpcode &&
7678         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7679       SDValue N20 = N1.getOperand(2).getOperand(0);
7680       SDValue N21 = N1.getOperand(2).getOperand(1);
7681       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682                          DAG.getNode(ISD::FNEG, SL, VT,
7683                                      N1.getOperand(0)),
7684                          N1.getOperand(1),
7685                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7686                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7687
7688                                      N21, N0));
7689     }
7690
7691     if (UnsafeFPMath && LookThroughFPExt) {
7692       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7693       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7694       if (N0.getOpcode() == PreferredFusedOpcode) {
7695         SDValue N02 = N0.getOperand(2);
7696         if (N02.getOpcode() == ISD::FP_EXTEND) {
7697           SDValue N020 = N02.getOperand(0);
7698           if (N020.getOpcode() == ISD::FMUL)
7699             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7700                                N0.getOperand(0), N0.getOperand(1),
7701                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7702                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7703                                                        N020.getOperand(0)),
7704                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7705                                                        N020.getOperand(1)),
7706                                            DAG.getNode(ISD::FNEG, SL, VT,
7707                                                        N1)));
7708         }
7709       }
7710
7711       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7712       //   -> (fma (fpext x), (fpext y),
7713       //           (fma (fpext u), (fpext v), (fneg z)))
7714       // FIXME: This turns two single-precision and one double-precision
7715       // operation into two double-precision operations, which might not be
7716       // interesting for all targets, especially GPUs.
7717       if (N0.getOpcode() == ISD::FP_EXTEND) {
7718         SDValue N00 = N0.getOperand(0);
7719         if (N00.getOpcode() == PreferredFusedOpcode) {
7720           SDValue N002 = N00.getOperand(2);
7721           if (N002.getOpcode() == ISD::FMUL)
7722             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7723                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7724                                            N00.getOperand(0)),
7725                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                            N00.getOperand(1)),
7727                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7728                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7729                                                        N002.getOperand(0)),
7730                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731                                                        N002.getOperand(1)),
7732                                            DAG.getNode(ISD::FNEG, SL, VT,
7733                                                        N1)));
7734         }
7735       }
7736
7737       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7738       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7739       if (N1.getOpcode() == PreferredFusedOpcode &&
7740         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7741         SDValue N120 = N1.getOperand(2).getOperand(0);
7742         if (N120.getOpcode() == ISD::FMUL) {
7743           SDValue N1200 = N120.getOperand(0);
7744           SDValue N1201 = N120.getOperand(1);
7745           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7747                              N1.getOperand(1),
7748                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7749                                          DAG.getNode(ISD::FNEG, SL, VT,
7750                                              DAG.getNode(ISD::FP_EXTEND, SL,
7751                                                          VT, N1200)),
7752                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7753                                                      N1201),
7754                                          N0));
7755         }
7756       }
7757
7758       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7759       //   -> (fma (fneg (fpext y)), (fpext z),
7760       //           (fma (fneg (fpext u)), (fpext v), x))
7761       // FIXME: This turns two single-precision and one double-precision
7762       // operation into two double-precision operations, which might not be
7763       // interesting for all targets, especially GPUs.
7764       if (N1.getOpcode() == ISD::FP_EXTEND &&
7765         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7766         SDValue N100 = N1.getOperand(0).getOperand(0);
7767         SDValue N101 = N1.getOperand(0).getOperand(1);
7768         SDValue N102 = N1.getOperand(0).getOperand(2);
7769         if (N102.getOpcode() == ISD::FMUL) {
7770           SDValue N1020 = N102.getOperand(0);
7771           SDValue N1021 = N102.getOperand(1);
7772           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7773                              DAG.getNode(ISD::FNEG, SL, VT,
7774                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7775                                                      N100)),
7776                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7777                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7778                                          DAG.getNode(ISD::FNEG, SL, VT,
7779                                              DAG.getNode(ISD::FP_EXTEND, SL,
7780                                                          VT, N1020)),
7781                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782                                                      N1021),
7783                                          N0));
7784         }
7785       }
7786     }
7787   }
7788
7789   return SDValue();
7790 }
7791
7792 SDValue DAGCombiner::visitFADD(SDNode *N) {
7793   SDValue N0 = N->getOperand(0);
7794   SDValue N1 = N->getOperand(1);
7795   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7796   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7797   EVT VT = N->getValueType(0);
7798   SDLoc DL(N);
7799   const TargetOptions &Options = DAG.getTarget().Options;
7800
7801   // fold vector ops
7802   if (VT.isVector())
7803     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7804       return FoldedVOp;
7805
7806   // fold (fadd c1, c2) -> c1 + c2
7807   if (N0CFP && N1CFP)
7808     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7809
7810   // canonicalize constant to RHS
7811   if (N0CFP && !N1CFP)
7812     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7813
7814   // fold (fadd A, (fneg B)) -> (fsub A, B)
7815   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7816       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7817     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7818                        GetNegatedExpression(N1, DAG, LegalOperations));
7819
7820   // fold (fadd (fneg A), B) -> (fsub B, A)
7821   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7822       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7823     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7824                        GetNegatedExpression(N0, DAG, LegalOperations));
7825
7826   // If 'unsafe math' is enabled, fold lots of things.
7827   if (Options.UnsafeFPMath) {
7828     // No FP constant should be created after legalization as Instruction
7829     // Selection pass has a hard time dealing with FP constants.
7830     bool AllowNewConst = (Level < AfterLegalizeDAG);
7831
7832     // fold (fadd A, 0) -> A
7833     if (N1CFP && N1CFP->getValueAPF().isZero())
7834       return N0;
7835
7836     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7837     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7838         isa<ConstantFPSDNode>(N0.getOperand(1)))
7839       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7840                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7841
7842     // If allowed, fold (fadd (fneg x), x) -> 0.0
7843     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7844       return DAG.getConstantFP(0.0, DL, VT);
7845
7846     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7847     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7848       return DAG.getConstantFP(0.0, DL, VT);
7849
7850     // We can fold chains of FADD's of the same value into multiplications.
7851     // This transform is not safe in general because we are reducing the number
7852     // of rounding steps.
7853     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7854       if (N0.getOpcode() == ISD::FMUL) {
7855         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7856         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7857
7858         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7859         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7860           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7861                                        DAG.getConstantFP(1.0, DL, VT));
7862           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7863         }
7864
7865         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7866         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7867             N1.getOperand(0) == N1.getOperand(1) &&
7868             N0.getOperand(0) == N1.getOperand(0)) {
7869           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7870                                        DAG.getConstantFP(2.0, DL, VT));
7871           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7872         }
7873       }
7874
7875       if (N1.getOpcode() == ISD::FMUL) {
7876         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7877         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7878
7879         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7880         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7881           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7882                                        DAG.getConstantFP(1.0, DL, VT));
7883           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7884         }
7885
7886         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7887         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7888             N0.getOperand(0) == N0.getOperand(1) &&
7889             N1.getOperand(0) == N0.getOperand(0)) {
7890           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7891                                        DAG.getConstantFP(2.0, DL, VT));
7892           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7893         }
7894       }
7895
7896       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7897         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7898         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7899         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7900             (N0.getOperand(0) == N1)) {
7901           return DAG.getNode(ISD::FMUL, DL, VT,
7902                              N1, DAG.getConstantFP(3.0, DL, VT));
7903         }
7904       }
7905
7906       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7907         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7908         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7909         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7910             N1.getOperand(0) == N0) {
7911           return DAG.getNode(ISD::FMUL, DL, VT,
7912                              N0, DAG.getConstantFP(3.0, DL, VT));
7913         }
7914       }
7915
7916       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7917       if (AllowNewConst &&
7918           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7919           N0.getOperand(0) == N0.getOperand(1) &&
7920           N1.getOperand(0) == N1.getOperand(1) &&
7921           N0.getOperand(0) == N1.getOperand(0)) {
7922         return DAG.getNode(ISD::FMUL, DL, VT,
7923                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7924       }
7925     }
7926   } // enable-unsafe-fp-math
7927
7928   // FADD -> FMA combines:
7929   SDValue Fused = visitFADDForFMACombine(N);
7930   if (Fused) {
7931     AddToWorklist(Fused.getNode());
7932     return Fused;
7933   }
7934
7935   return SDValue();
7936 }
7937
7938 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7939   SDValue N0 = N->getOperand(0);
7940   SDValue N1 = N->getOperand(1);
7941   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7942   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7943   EVT VT = N->getValueType(0);
7944   SDLoc dl(N);
7945   const TargetOptions &Options = DAG.getTarget().Options;
7946
7947   // fold vector ops
7948   if (VT.isVector())
7949     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7950       return FoldedVOp;
7951
7952   // fold (fsub c1, c2) -> c1-c2
7953   if (N0CFP && N1CFP)
7954     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7955
7956   // fold (fsub A, (fneg B)) -> (fadd A, B)
7957   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7958     return DAG.getNode(ISD::FADD, dl, VT, N0,
7959                        GetNegatedExpression(N1, DAG, LegalOperations));
7960
7961   // If 'unsafe math' is enabled, fold lots of things.
7962   if (Options.UnsafeFPMath) {
7963     // (fsub A, 0) -> A
7964     if (N1CFP && N1CFP->getValueAPF().isZero())
7965       return N0;
7966
7967     // (fsub 0, B) -> -B
7968     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7969       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7970         return GetNegatedExpression(N1, DAG, LegalOperations);
7971       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7972         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7973     }
7974
7975     // (fsub x, x) -> 0.0
7976     if (N0 == N1)
7977       return DAG.getConstantFP(0.0f, dl, VT);
7978
7979     // (fsub x, (fadd x, y)) -> (fneg y)
7980     // (fsub x, (fadd y, x)) -> (fneg y)
7981     if (N1.getOpcode() == ISD::FADD) {
7982       SDValue N10 = N1->getOperand(0);
7983       SDValue N11 = N1->getOperand(1);
7984
7985       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7986         return GetNegatedExpression(N11, DAG, LegalOperations);
7987
7988       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7989         return GetNegatedExpression(N10, DAG, LegalOperations);
7990     }
7991   }
7992
7993   // FSUB -> FMA combines:
7994   SDValue Fused = visitFSUBForFMACombine(N);
7995   if (Fused) {
7996     AddToWorklist(Fused.getNode());
7997     return Fused;
7998   }
7999
8000   return SDValue();
8001 }
8002
8003 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8004   SDValue N0 = N->getOperand(0);
8005   SDValue N1 = N->getOperand(1);
8006   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8007   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8008   EVT VT = N->getValueType(0);
8009   SDLoc DL(N);
8010   const TargetOptions &Options = DAG.getTarget().Options;
8011
8012   // fold vector ops
8013   if (VT.isVector()) {
8014     // This just handles C1 * C2 for vectors. Other vector folds are below.
8015     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8016       return FoldedVOp;
8017   }
8018
8019   // fold (fmul c1, c2) -> c1*c2
8020   if (N0CFP && N1CFP)
8021     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8022
8023   // canonicalize constant to RHS
8024   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8025      !isConstantFPBuildVectorOrConstantFP(N1))
8026     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8027
8028   // fold (fmul A, 1.0) -> A
8029   if (N1CFP && N1CFP->isExactlyValue(1.0))
8030     return N0;
8031
8032   if (Options.UnsafeFPMath) {
8033     // fold (fmul A, 0) -> 0
8034     if (N1CFP && N1CFP->getValueAPF().isZero())
8035       return N1;
8036
8037     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8038     if (N0.getOpcode() == ISD::FMUL) {
8039       // Fold scalars or any vector constants (not just splats).
8040       // This fold is done in general by InstCombine, but extra fmul insts
8041       // may have been generated during lowering.
8042       SDValue N00 = N0.getOperand(0);
8043       SDValue N01 = N0.getOperand(1);
8044       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8045       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8046       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8047       
8048       // Check 1: Make sure that the first operand of the inner multiply is NOT
8049       // a constant. Otherwise, we may induce infinite looping.
8050       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8051         // Check 2: Make sure that the second operand of the inner multiply and
8052         // the second operand of the outer multiply are constants.
8053         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8054             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8055           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8056           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8057         }
8058       }
8059     }
8060
8061     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8062     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8063     // during an early run of DAGCombiner can prevent folding with fmuls
8064     // inserted during lowering.
8065     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8066       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8067       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8068       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8069     }
8070   }
8071
8072   // fold (fmul X, 2.0) -> (fadd X, X)
8073   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8074     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8075
8076   // fold (fmul X, -1.0) -> (fneg X)
8077   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8078     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8079       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8080
8081   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8082   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8083     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8084       // Both can be negated for free, check to see if at least one is cheaper
8085       // negated.
8086       if (LHSNeg == 2 || RHSNeg == 2)
8087         return DAG.getNode(ISD::FMUL, DL, VT,
8088                            GetNegatedExpression(N0, DAG, LegalOperations),
8089                            GetNegatedExpression(N1, DAG, LegalOperations));
8090     }
8091   }
8092
8093   return SDValue();
8094 }
8095
8096 SDValue DAGCombiner::visitFMA(SDNode *N) {
8097   SDValue N0 = N->getOperand(0);
8098   SDValue N1 = N->getOperand(1);
8099   SDValue N2 = N->getOperand(2);
8100   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8101   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8102   EVT VT = N->getValueType(0);
8103   SDLoc dl(N);
8104   const TargetOptions &Options = DAG.getTarget().Options;
8105
8106   // Constant fold FMA.
8107   if (isa<ConstantFPSDNode>(N0) &&
8108       isa<ConstantFPSDNode>(N1) &&
8109       isa<ConstantFPSDNode>(N2)) {
8110     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8111   }
8112
8113   if (Options.UnsafeFPMath) {
8114     if (N0CFP && N0CFP->isZero())
8115       return N2;
8116     if (N1CFP && N1CFP->isZero())
8117       return N2;
8118   }
8119   if (N0CFP && N0CFP->isExactlyValue(1.0))
8120     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8121   if (N1CFP && N1CFP->isExactlyValue(1.0))
8122     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8123
8124   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8125   if (N0CFP && !N1CFP)
8126     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8127
8128   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8129   if (Options.UnsafeFPMath && N1CFP &&
8130       N2.getOpcode() == ISD::FMUL &&
8131       N0 == N2.getOperand(0) &&
8132       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8133     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8134                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8135   }
8136
8137
8138   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8139   if (Options.UnsafeFPMath &&
8140       N0.getOpcode() == ISD::FMUL && N1CFP &&
8141       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8142     return DAG.getNode(ISD::FMA, dl, VT,
8143                        N0.getOperand(0),
8144                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8145                        N2);
8146   }
8147
8148   // (fma x, 1, y) -> (fadd x, y)
8149   // (fma x, -1, y) -> (fadd (fneg x), y)
8150   if (N1CFP) {
8151     if (N1CFP->isExactlyValue(1.0))
8152       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8153
8154     if (N1CFP->isExactlyValue(-1.0) &&
8155         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8156       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8157       AddToWorklist(RHSNeg.getNode());
8158       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8159     }
8160   }
8161
8162   // (fma x, c, x) -> (fmul x, (c+1))
8163   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8164     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8165                        DAG.getNode(ISD::FADD, dl, VT,
8166                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8167
8168   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8169   if (Options.UnsafeFPMath && N1CFP &&
8170       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8171     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8172                        DAG.getNode(ISD::FADD, dl, VT,
8173                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8174
8175
8176   return SDValue();
8177 }
8178
8179 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8180   SDValue N0 = N->getOperand(0);
8181   SDValue N1 = N->getOperand(1);
8182   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8183   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8184   EVT VT = N->getValueType(0);
8185   SDLoc DL(N);
8186   const TargetOptions &Options = DAG.getTarget().Options;
8187
8188   // fold vector ops
8189   if (VT.isVector())
8190     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8191       return FoldedVOp;
8192
8193   // fold (fdiv c1, c2) -> c1/c2
8194   if (N0CFP && N1CFP)
8195     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8196
8197   if (Options.UnsafeFPMath) {
8198     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8199     if (N1CFP) {
8200       // Compute the reciprocal 1.0 / c2.
8201       APFloat N1APF = N1CFP->getValueAPF();
8202       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8203       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8204       // Only do the transform if the reciprocal is a legal fp immediate that
8205       // isn't too nasty (eg NaN, denormal, ...).
8206       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8207           (!LegalOperations ||
8208            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8209            // backend)... we should handle this gracefully after Legalize.
8210            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8211            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8212            TLI.isFPImmLegal(Recip, VT)))
8213         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8214                            DAG.getConstantFP(Recip, DL, VT));
8215     }
8216
8217     // If this FDIV is part of a reciprocal square root, it may be folded
8218     // into a target-specific square root estimate instruction.
8219     if (N1.getOpcode() == ISD::FSQRT) {
8220       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8221         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8222       }
8223     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8224                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8225       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8226         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8227         AddToWorklist(RV.getNode());
8228         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8229       }
8230     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8231                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8232       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8233         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8234         AddToWorklist(RV.getNode());
8235         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8236       }
8237     } else if (N1.getOpcode() == ISD::FMUL) {
8238       // Look through an FMUL. Even though this won't remove the FDIV directly,
8239       // it's still worthwhile to get rid of the FSQRT if possible.
8240       SDValue SqrtOp;
8241       SDValue OtherOp;
8242       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8243         SqrtOp = N1.getOperand(0);
8244         OtherOp = N1.getOperand(1);
8245       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8246         SqrtOp = N1.getOperand(1);
8247         OtherOp = N1.getOperand(0);
8248       }
8249       if (SqrtOp.getNode()) {
8250         // We found a FSQRT, so try to make this fold:
8251         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8252         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8253           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8254           AddToWorklist(RV.getNode());
8255           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8256         }
8257       }
8258     }
8259
8260     // Fold into a reciprocal estimate and multiply instead of a real divide.
8261     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8262       AddToWorklist(RV.getNode());
8263       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8264     }
8265   }
8266
8267   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8268   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8269     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8270       // Both can be negated for free, check to see if at least one is cheaper
8271       // negated.
8272       if (LHSNeg == 2 || RHSNeg == 2)
8273         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8274                            GetNegatedExpression(N0, DAG, LegalOperations),
8275                            GetNegatedExpression(N1, DAG, LegalOperations));
8276     }
8277   }
8278
8279   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8280   // reciprocal.
8281   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8282   // Notice that this is not always beneficial. One reason is different target
8283   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8284   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8285   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8286   if (Options.UnsafeFPMath) {
8287     // Skip if current node is a reciprocal.
8288     if (N0CFP && N0CFP->isExactlyValue(1.0))
8289       return SDValue();
8290
8291     SmallVector<SDNode *, 4> Users;
8292     // Find all FDIV users of the same divisor.
8293     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8294                               UE = N1.getNode()->use_end();
8295          UI != UE; ++UI) {
8296       SDNode *User = UI.getUse().getUser();
8297       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8298         Users.push_back(User);
8299     }
8300
8301     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8302       SDLoc DL(N);
8303       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8304       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8305
8306       // Dividend / Divisor -> Dividend * Reciprocal
8307       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8308         if ((*I)->getOperand(0) != FPOne) {
8309           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8310                                         (*I)->getOperand(0), Reciprocal);
8311           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8312         }
8313       }
8314       return SDValue();
8315     }
8316   }
8317
8318   return SDValue();
8319 }
8320
8321 SDValue DAGCombiner::visitFREM(SDNode *N) {
8322   SDValue N0 = N->getOperand(0);
8323   SDValue N1 = N->getOperand(1);
8324   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8325   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8326   EVT VT = N->getValueType(0);
8327
8328   // fold (frem c1, c2) -> fmod(c1,c2)
8329   if (N0CFP && N1CFP)
8330     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8331
8332   return SDValue();
8333 }
8334
8335 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8336   if (DAG.getTarget().Options.UnsafeFPMath &&
8337       !TLI.isFsqrtCheap()) {
8338     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8339     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8340       EVT VT = RV.getValueType();
8341       SDLoc DL(N);
8342       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8343       AddToWorklist(RV.getNode());
8344
8345       // Unfortunately, RV is now NaN if the input was exactly 0.
8346       // Select out this case and force the answer to 0.
8347       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8348       SDValue ZeroCmp =
8349         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8350                      N->getOperand(0), Zero, ISD::SETEQ);
8351       AddToWorklist(ZeroCmp.getNode());
8352       AddToWorklist(RV.getNode());
8353
8354       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8355                        DL, VT, ZeroCmp, Zero, RV);
8356       return RV;
8357     }
8358   }
8359   return SDValue();
8360 }
8361
8362 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8363   SDValue N0 = N->getOperand(0);
8364   SDValue N1 = N->getOperand(1);
8365   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8366   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8367   EVT VT = N->getValueType(0);
8368
8369   if (N0CFP && N1CFP)  // Constant fold
8370     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8371
8372   if (N1CFP) {
8373     const APFloat& V = N1CFP->getValueAPF();
8374     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8375     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8376     if (!V.isNegative()) {
8377       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8378         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8379     } else {
8380       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8381         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8382                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8383     }
8384   }
8385
8386   // copysign(fabs(x), y) -> copysign(x, y)
8387   // copysign(fneg(x), y) -> copysign(x, y)
8388   // copysign(copysign(x,z), y) -> copysign(x, y)
8389   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8390       N0.getOpcode() == ISD::FCOPYSIGN)
8391     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8392                        N0.getOperand(0), N1);
8393
8394   // copysign(x, abs(y)) -> abs(x)
8395   if (N1.getOpcode() == ISD::FABS)
8396     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8397
8398   // copysign(x, copysign(y,z)) -> copysign(x, z)
8399   if (N1.getOpcode() == ISD::FCOPYSIGN)
8400     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8401                        N0, N1.getOperand(1));
8402
8403   // copysign(x, fp_extend(y)) -> copysign(x, y)
8404   // copysign(x, fp_round(y)) -> copysign(x, y)
8405   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8406     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8407                        N0, N1.getOperand(0));
8408
8409   return SDValue();
8410 }
8411
8412 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8413   SDValue N0 = N->getOperand(0);
8414   EVT VT = N->getValueType(0);
8415   EVT OpVT = N0.getValueType();
8416
8417   // fold (sint_to_fp c1) -> c1fp
8418   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8419       // ...but only if the target supports immediate floating-point values
8420       (!LegalOperations ||
8421        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8422     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8423
8424   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8425   // but UINT_TO_FP is legal on this target, try to convert.
8426   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8427       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8428     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8429     if (DAG.SignBitIsZero(N0))
8430       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8431   }
8432
8433   // The next optimizations are desirable only if SELECT_CC can be lowered.
8434   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8435     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8436     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8437         !VT.isVector() &&
8438         (!LegalOperations ||
8439          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8440       SDLoc DL(N);
8441       SDValue Ops[] =
8442         { N0.getOperand(0), N0.getOperand(1),
8443           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8444           N0.getOperand(2) };
8445       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8446     }
8447
8448     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8449     //      (select_cc x, y, 1.0, 0.0,, cc)
8450     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8451         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8452         (!LegalOperations ||
8453          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8454       SDLoc DL(N);
8455       SDValue Ops[] =
8456         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8457           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8458           N0.getOperand(0).getOperand(2) };
8459       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8460     }
8461   }
8462
8463   return SDValue();
8464 }
8465
8466 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8467   SDValue N0 = N->getOperand(0);
8468   EVT VT = N->getValueType(0);
8469   EVT OpVT = N0.getValueType();
8470
8471   // fold (uint_to_fp c1) -> c1fp
8472   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8473       // ...but only if the target supports immediate floating-point values
8474       (!LegalOperations ||
8475        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8476     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8477
8478   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8479   // but SINT_TO_FP is legal on this target, try to convert.
8480   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8481       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8482     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8483     if (DAG.SignBitIsZero(N0))
8484       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8485   }
8486
8487   // The next optimizations are desirable only if SELECT_CC can be lowered.
8488   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8489     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8490
8491     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8492         (!LegalOperations ||
8493          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8494       SDLoc DL(N);
8495       SDValue Ops[] =
8496         { N0.getOperand(0), N0.getOperand(1),
8497           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8498           N0.getOperand(2) };
8499       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8500     }
8501   }
8502
8503   return SDValue();
8504 }
8505
8506 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8507 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8508   SDValue N0 = N->getOperand(0);
8509   EVT VT = N->getValueType(0);
8510
8511   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8512     return SDValue();
8513
8514   SDValue Src = N0.getOperand(0);
8515   EVT SrcVT = Src.getValueType();
8516   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8517   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8518
8519   // We can safely assume the conversion won't overflow the output range,
8520   // because (for example) (uint8_t)18293.f is undefined behavior.
8521
8522   // Since we can assume the conversion won't overflow, our decision as to
8523   // whether the input will fit in the float should depend on the minimum
8524   // of the input range and output range.
8525
8526   // This means this is also safe for a signed input and unsigned output, since
8527   // a negative input would lead to undefined behavior.
8528   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8529   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8530   unsigned ActualSize = std::min(InputSize, OutputSize);
8531   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8532
8533   // We can only fold away the float conversion if the input range can be
8534   // represented exactly in the float range.
8535   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8536     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8537       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8538                                                        : ISD::ZERO_EXTEND;
8539       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8540     }
8541     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8542       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8543     if (SrcVT == VT)
8544       return Src;
8545     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8546   }
8547   return SDValue();
8548 }
8549
8550 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8551   SDValue N0 = N->getOperand(0);
8552   EVT VT = N->getValueType(0);
8553
8554   // fold (fp_to_sint c1fp) -> c1
8555   if (isConstantFPBuildVectorOrConstantFP(N0))
8556     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8557
8558   return FoldIntToFPToInt(N, DAG);
8559 }
8560
8561 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8562   SDValue N0 = N->getOperand(0);
8563   EVT VT = N->getValueType(0);
8564
8565   // fold (fp_to_uint c1fp) -> c1
8566   if (isConstantFPBuildVectorOrConstantFP(N0))
8567     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8568
8569   return FoldIntToFPToInt(N, DAG);
8570 }
8571
8572 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8573   SDValue N0 = N->getOperand(0);
8574   SDValue N1 = N->getOperand(1);
8575   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8576   EVT VT = N->getValueType(0);
8577
8578   // fold (fp_round c1fp) -> c1fp
8579   if (N0CFP)
8580     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8581
8582   // fold (fp_round (fp_extend x)) -> x
8583   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8584     return N0.getOperand(0);
8585
8586   // fold (fp_round (fp_round x)) -> (fp_round x)
8587   if (N0.getOpcode() == ISD::FP_ROUND) {
8588     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8589     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8590     // If the first fp_round isn't a value preserving truncation, it might
8591     // introduce a tie in the second fp_round, that wouldn't occur in the
8592     // single-step fp_round we want to fold to.
8593     // In other words, double rounding isn't the same as rounding.
8594     // Also, this is a value preserving truncation iff both fp_round's are.
8595     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8596       SDLoc DL(N);
8597       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8598                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8599     }
8600   }
8601
8602   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8603   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8604     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8605                               N0.getOperand(0), N1);
8606     AddToWorklist(Tmp.getNode());
8607     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8608                        Tmp, N0.getOperand(1));
8609   }
8610
8611   return SDValue();
8612 }
8613
8614 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8615   SDValue N0 = N->getOperand(0);
8616   EVT VT = N->getValueType(0);
8617   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8618   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8619
8620   // fold (fp_round_inreg c1fp) -> c1fp
8621   if (N0CFP && isTypeLegal(EVT)) {
8622     SDLoc DL(N);
8623     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8624     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8625   }
8626
8627   return SDValue();
8628 }
8629
8630 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8631   SDValue N0 = N->getOperand(0);
8632   EVT VT = N->getValueType(0);
8633
8634   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8635   if (N->hasOneUse() &&
8636       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8637     return SDValue();
8638
8639   // fold (fp_extend c1fp) -> c1fp
8640   if (isConstantFPBuildVectorOrConstantFP(N0))
8641     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8642
8643   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8644   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8645       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8646     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8647
8648   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8649   // value of X.
8650   if (N0.getOpcode() == ISD::FP_ROUND
8651       && N0.getNode()->getConstantOperandVal(1) == 1) {
8652     SDValue In = N0.getOperand(0);
8653     if (In.getValueType() == VT) return In;
8654     if (VT.bitsLT(In.getValueType()))
8655       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8656                          In, N0.getOperand(1));
8657     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8658   }
8659
8660   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8661   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8662        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8663     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8664     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8665                                      LN0->getChain(),
8666                                      LN0->getBasePtr(), N0.getValueType(),
8667                                      LN0->getMemOperand());
8668     CombineTo(N, ExtLoad);
8669     CombineTo(N0.getNode(),
8670               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8671                           N0.getValueType(), ExtLoad,
8672                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8673               ExtLoad.getValue(1));
8674     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8675   }
8676
8677   return SDValue();
8678 }
8679
8680 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8681   SDValue N0 = N->getOperand(0);
8682   EVT VT = N->getValueType(0);
8683
8684   // fold (fceil c1) -> fceil(c1)
8685   if (isConstantFPBuildVectorOrConstantFP(N0))
8686     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8687
8688   return SDValue();
8689 }
8690
8691 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8692   SDValue N0 = N->getOperand(0);
8693   EVT VT = N->getValueType(0);
8694
8695   // fold (ftrunc c1) -> ftrunc(c1)
8696   if (isConstantFPBuildVectorOrConstantFP(N0))
8697     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8698
8699   return SDValue();
8700 }
8701
8702 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8703   SDValue N0 = N->getOperand(0);
8704   EVT VT = N->getValueType(0);
8705
8706   // fold (ffloor c1) -> ffloor(c1)
8707   if (isConstantFPBuildVectorOrConstantFP(N0))
8708     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8709
8710   return SDValue();
8711 }
8712
8713 // FIXME: FNEG and FABS have a lot in common; refactor.
8714 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8715   SDValue N0 = N->getOperand(0);
8716   EVT VT = N->getValueType(0);
8717
8718   // Constant fold FNEG.
8719   if (isConstantFPBuildVectorOrConstantFP(N0))
8720     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8721
8722   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8723                          &DAG.getTarget().Options))
8724     return GetNegatedExpression(N0, DAG, LegalOperations);
8725
8726   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8727   // constant pool values.
8728   if (!TLI.isFNegFree(VT) &&
8729       N0.getOpcode() == ISD::BITCAST &&
8730       N0.getNode()->hasOneUse()) {
8731     SDValue Int = N0.getOperand(0);
8732     EVT IntVT = Int.getValueType();
8733     if (IntVT.isInteger() && !IntVT.isVector()) {
8734       APInt SignMask;
8735       if (N0.getValueType().isVector()) {
8736         // For a vector, get a mask such as 0x80... per scalar element
8737         // and splat it.
8738         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8739         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8740       } else {
8741         // For a scalar, just generate 0x80...
8742         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8743       }
8744       SDLoc DL0(N0);
8745       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8746                         DAG.getConstant(SignMask, DL0, IntVT));
8747       AddToWorklist(Int.getNode());
8748       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8749     }
8750   }
8751
8752   // (fneg (fmul c, x)) -> (fmul -c, x)
8753   if (N0.getOpcode() == ISD::FMUL) {
8754     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8755     if (CFP1) {
8756       APFloat CVal = CFP1->getValueAPF();
8757       CVal.changeSign();
8758       if (Level >= AfterLegalizeDAG &&
8759           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8760            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8761         return DAG.getNode(
8762             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8763             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8764     }
8765   }
8766
8767   return SDValue();
8768 }
8769
8770 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8771   SDValue N0 = N->getOperand(0);
8772   SDValue N1 = N->getOperand(1);
8773   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8774   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8775
8776   if (N0CFP && N1CFP) {
8777     const APFloat &C0 = N0CFP->getValueAPF();
8778     const APFloat &C1 = N1CFP->getValueAPF();
8779     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8780   }
8781
8782   if (N0CFP) {
8783     EVT VT = N->getValueType(0);
8784     // Canonicalize to constant on RHS.
8785     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8786   }
8787
8788   return SDValue();
8789 }
8790
8791 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8792   SDValue N0 = N->getOperand(0);
8793   SDValue N1 = N->getOperand(1);
8794   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8795   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8796
8797   if (N0CFP && N1CFP) {
8798     const APFloat &C0 = N0CFP->getValueAPF();
8799     const APFloat &C1 = N1CFP->getValueAPF();
8800     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8801   }
8802
8803   if (N0CFP) {
8804     EVT VT = N->getValueType(0);
8805     // Canonicalize to constant on RHS.
8806     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8807   }
8808
8809   return SDValue();
8810 }
8811
8812 SDValue DAGCombiner::visitFABS(SDNode *N) {
8813   SDValue N0 = N->getOperand(0);
8814   EVT VT = N->getValueType(0);
8815
8816   // fold (fabs c1) -> fabs(c1)
8817   if (isConstantFPBuildVectorOrConstantFP(N0))
8818     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8819
8820   // fold (fabs (fabs x)) -> (fabs x)
8821   if (N0.getOpcode() == ISD::FABS)
8822     return N->getOperand(0);
8823
8824   // fold (fabs (fneg x)) -> (fabs x)
8825   // fold (fabs (fcopysign x, y)) -> (fabs x)
8826   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8827     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8828
8829   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8830   // constant pool values.
8831   if (!TLI.isFAbsFree(VT) &&
8832       N0.getOpcode() == ISD::BITCAST &&
8833       N0.getNode()->hasOneUse()) {
8834     SDValue Int = N0.getOperand(0);
8835     EVT IntVT = Int.getValueType();
8836     if (IntVT.isInteger() && !IntVT.isVector()) {
8837       APInt SignMask;
8838       if (N0.getValueType().isVector()) {
8839         // For a vector, get a mask such as 0x7f... per scalar element
8840         // and splat it.
8841         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8842         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8843       } else {
8844         // For a scalar, just generate 0x7f...
8845         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8846       }
8847       SDLoc DL(N0);
8848       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8849                         DAG.getConstant(SignMask, DL, IntVT));
8850       AddToWorklist(Int.getNode());
8851       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8852     }
8853   }
8854
8855   return SDValue();
8856 }
8857
8858 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8859   SDValue Chain = N->getOperand(0);
8860   SDValue N1 = N->getOperand(1);
8861   SDValue N2 = N->getOperand(2);
8862
8863   // If N is a constant we could fold this into a fallthrough or unconditional
8864   // branch. However that doesn't happen very often in normal code, because
8865   // Instcombine/SimplifyCFG should have handled the available opportunities.
8866   // If we did this folding here, it would be necessary to update the
8867   // MachineBasicBlock CFG, which is awkward.
8868
8869   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8870   // on the target.
8871   if (N1.getOpcode() == ISD::SETCC &&
8872       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8873                                    N1.getOperand(0).getValueType())) {
8874     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8875                        Chain, N1.getOperand(2),
8876                        N1.getOperand(0), N1.getOperand(1), N2);
8877   }
8878
8879   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8880       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8881        (N1.getOperand(0).hasOneUse() &&
8882         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8883     SDNode *Trunc = nullptr;
8884     if (N1.getOpcode() == ISD::TRUNCATE) {
8885       // Look pass the truncate.
8886       Trunc = N1.getNode();
8887       N1 = N1.getOperand(0);
8888     }
8889
8890     // Match this pattern so that we can generate simpler code:
8891     //
8892     //   %a = ...
8893     //   %b = and i32 %a, 2
8894     //   %c = srl i32 %b, 1
8895     //   brcond i32 %c ...
8896     //
8897     // into
8898     //
8899     //   %a = ...
8900     //   %b = and i32 %a, 2
8901     //   %c = setcc eq %b, 0
8902     //   brcond %c ...
8903     //
8904     // This applies only when the AND constant value has one bit set and the
8905     // SRL constant is equal to the log2 of the AND constant. The back-end is
8906     // smart enough to convert the result into a TEST/JMP sequence.
8907     SDValue Op0 = N1.getOperand(0);
8908     SDValue Op1 = N1.getOperand(1);
8909
8910     if (Op0.getOpcode() == ISD::AND &&
8911         Op1.getOpcode() == ISD::Constant) {
8912       SDValue AndOp1 = Op0.getOperand(1);
8913
8914       if (AndOp1.getOpcode() == ISD::Constant) {
8915         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8916
8917         if (AndConst.isPowerOf2() &&
8918             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8919           SDLoc DL(N);
8920           SDValue SetCC =
8921             DAG.getSetCC(DL,
8922                          getSetCCResultType(Op0.getValueType()),
8923                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8924                          ISD::SETNE);
8925
8926           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8927                                           MVT::Other, Chain, SetCC, N2);
8928           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8929           // will convert it back to (X & C1) >> C2.
8930           CombineTo(N, NewBRCond, false);
8931           // Truncate is dead.
8932           if (Trunc)
8933             deleteAndRecombine(Trunc);
8934           // Replace the uses of SRL with SETCC
8935           WorklistRemover DeadNodes(*this);
8936           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8937           deleteAndRecombine(N1.getNode());
8938           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8939         }
8940       }
8941     }
8942
8943     if (Trunc)
8944       // Restore N1 if the above transformation doesn't match.
8945       N1 = N->getOperand(1);
8946   }
8947
8948   // Transform br(xor(x, y)) -> br(x != y)
8949   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8950   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8951     SDNode *TheXor = N1.getNode();
8952     SDValue Op0 = TheXor->getOperand(0);
8953     SDValue Op1 = TheXor->getOperand(1);
8954     if (Op0.getOpcode() == Op1.getOpcode()) {
8955       // Avoid missing important xor optimizations.
8956       SDValue Tmp = visitXOR(TheXor);
8957       if (Tmp.getNode()) {
8958         if (Tmp.getNode() != TheXor) {
8959           DEBUG(dbgs() << "\nReplacing.8 ";
8960                 TheXor->dump(&DAG);
8961                 dbgs() << "\nWith: ";
8962                 Tmp.getNode()->dump(&DAG);
8963                 dbgs() << '\n');
8964           WorklistRemover DeadNodes(*this);
8965           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8966           deleteAndRecombine(TheXor);
8967           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8968                              MVT::Other, Chain, Tmp, N2);
8969         }
8970
8971         // visitXOR has changed XOR's operands or replaced the XOR completely,
8972         // bail out.
8973         return SDValue(N, 0);
8974       }
8975     }
8976
8977     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8978       bool Equal = false;
8979       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8980         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8981             Op0.getOpcode() == ISD::XOR) {
8982           TheXor = Op0.getNode();
8983           Equal = true;
8984         }
8985
8986       EVT SetCCVT = N1.getValueType();
8987       if (LegalTypes)
8988         SetCCVT = getSetCCResultType(SetCCVT);
8989       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8990                                    SetCCVT,
8991                                    Op0, Op1,
8992                                    Equal ? ISD::SETEQ : ISD::SETNE);
8993       // Replace the uses of XOR with SETCC
8994       WorklistRemover DeadNodes(*this);
8995       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8996       deleteAndRecombine(N1.getNode());
8997       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8998                          MVT::Other, Chain, SetCC, N2);
8999     }
9000   }
9001
9002   return SDValue();
9003 }
9004
9005 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9006 //
9007 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9008   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9009   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9010
9011   // If N is a constant we could fold this into a fallthrough or unconditional
9012   // branch. However that doesn't happen very often in normal code, because
9013   // Instcombine/SimplifyCFG should have handled the available opportunities.
9014   // If we did this folding here, it would be necessary to update the
9015   // MachineBasicBlock CFG, which is awkward.
9016
9017   // Use SimplifySetCC to simplify SETCC's.
9018   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9019                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9020                                false);
9021   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9022
9023   // fold to a simpler setcc
9024   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9025     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9026                        N->getOperand(0), Simp.getOperand(2),
9027                        Simp.getOperand(0), Simp.getOperand(1),
9028                        N->getOperand(4));
9029
9030   return SDValue();
9031 }
9032
9033 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9034 /// and that N may be folded in the load / store addressing mode.
9035 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9036                                     SelectionDAG &DAG,
9037                                     const TargetLowering &TLI) {
9038   EVT VT;
9039   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9040     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9041       return false;
9042     VT = LD->getMemoryVT();
9043   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9044     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9045       return false;
9046     VT = ST->getMemoryVT();
9047   } else
9048     return false;
9049
9050   TargetLowering::AddrMode AM;
9051   if (N->getOpcode() == ISD::ADD) {
9052     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9053     if (Offset)
9054       // [reg +/- imm]
9055       AM.BaseOffs = Offset->getSExtValue();
9056     else
9057       // [reg +/- reg]
9058       AM.Scale = 1;
9059   } else if (N->getOpcode() == ISD::SUB) {
9060     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9061     if (Offset)
9062       // [reg +/- imm]
9063       AM.BaseOffs = -Offset->getSExtValue();
9064     else
9065       // [reg +/- reg]
9066       AM.Scale = 1;
9067   } else
9068     return false;
9069
9070   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9071 }
9072
9073 /// Try turning a load/store into a pre-indexed load/store when the base
9074 /// pointer is an add or subtract and it has other uses besides the load/store.
9075 /// After the transformation, the new indexed load/store has effectively folded
9076 /// the add/subtract in and all of its other uses are redirected to the
9077 /// new load/store.
9078 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9079   if (Level < AfterLegalizeDAG)
9080     return false;
9081
9082   bool isLoad = true;
9083   SDValue Ptr;
9084   EVT VT;
9085   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9086     if (LD->isIndexed())
9087       return false;
9088     VT = LD->getMemoryVT();
9089     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9090         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9091       return false;
9092     Ptr = LD->getBasePtr();
9093   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9094     if (ST->isIndexed())
9095       return false;
9096     VT = ST->getMemoryVT();
9097     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9098         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9099       return false;
9100     Ptr = ST->getBasePtr();
9101     isLoad = false;
9102   } else {
9103     return false;
9104   }
9105
9106   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9107   // out.  There is no reason to make this a preinc/predec.
9108   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9109       Ptr.getNode()->hasOneUse())
9110     return false;
9111
9112   // Ask the target to do addressing mode selection.
9113   SDValue BasePtr;
9114   SDValue Offset;
9115   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9116   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9117     return false;
9118
9119   // Backends without true r+i pre-indexed forms may need to pass a
9120   // constant base with a variable offset so that constant coercion
9121   // will work with the patterns in canonical form.
9122   bool Swapped = false;
9123   if (isa<ConstantSDNode>(BasePtr)) {
9124     std::swap(BasePtr, Offset);
9125     Swapped = true;
9126   }
9127
9128   // Don't create a indexed load / store with zero offset.
9129   if (isa<ConstantSDNode>(Offset) &&
9130       cast<ConstantSDNode>(Offset)->isNullValue())
9131     return false;
9132
9133   // Try turning it into a pre-indexed load / store except when:
9134   // 1) The new base ptr is a frame index.
9135   // 2) If N is a store and the new base ptr is either the same as or is a
9136   //    predecessor of the value being stored.
9137   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9138   //    that would create a cycle.
9139   // 4) All uses are load / store ops that use it as old base ptr.
9140
9141   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9142   // (plus the implicit offset) to a register to preinc anyway.
9143   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9144     return false;
9145
9146   // Check #2.
9147   if (!isLoad) {
9148     SDValue Val = cast<StoreSDNode>(N)->getValue();
9149     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9150       return false;
9151   }
9152
9153   // If the offset is a constant, there may be other adds of constants that
9154   // can be folded with this one. We should do this to avoid having to keep
9155   // a copy of the original base pointer.
9156   SmallVector<SDNode *, 16> OtherUses;
9157   if (isa<ConstantSDNode>(Offset))
9158     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9159                               UE = BasePtr.getNode()->use_end();
9160          UI != UE; ++UI) {
9161       SDUse &Use = UI.getUse();
9162       // Skip the use that is Ptr and uses of other results from BasePtr's
9163       // node (important for nodes that return multiple results).
9164       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9165         continue;
9166
9167       if (Use.getUser()->isPredecessorOf(N))
9168         continue;
9169
9170       if (Use.getUser()->getOpcode() != ISD::ADD &&
9171           Use.getUser()->getOpcode() != ISD::SUB) {
9172         OtherUses.clear();
9173         break;
9174       }
9175
9176       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9177       if (!isa<ConstantSDNode>(Op1)) {
9178         OtherUses.clear();
9179         break;
9180       }
9181
9182       // FIXME: In some cases, we can be smarter about this.
9183       if (Op1.getValueType() != Offset.getValueType()) {
9184         OtherUses.clear();
9185         break;
9186       }
9187
9188       OtherUses.push_back(Use.getUser());
9189     }
9190
9191   if (Swapped)
9192     std::swap(BasePtr, Offset);
9193
9194   // Now check for #3 and #4.
9195   bool RealUse = false;
9196
9197   // Caches for hasPredecessorHelper
9198   SmallPtrSet<const SDNode *, 32> Visited;
9199   SmallVector<const SDNode *, 16> Worklist;
9200
9201   for (SDNode *Use : Ptr.getNode()->uses()) {
9202     if (Use == N)
9203       continue;
9204     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9205       return false;
9206
9207     // If Ptr may be folded in addressing mode of other use, then it's
9208     // not profitable to do this transformation.
9209     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9210       RealUse = true;
9211   }
9212
9213   if (!RealUse)
9214     return false;
9215
9216   SDValue Result;
9217   if (isLoad)
9218     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9219                                 BasePtr, Offset, AM);
9220   else
9221     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9222                                  BasePtr, Offset, AM);
9223   ++PreIndexedNodes;
9224   ++NodesCombined;
9225   DEBUG(dbgs() << "\nReplacing.4 ";
9226         N->dump(&DAG);
9227         dbgs() << "\nWith: ";
9228         Result.getNode()->dump(&DAG);
9229         dbgs() << '\n');
9230   WorklistRemover DeadNodes(*this);
9231   if (isLoad) {
9232     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9233     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9234   } else {
9235     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9236   }
9237
9238   // Finally, since the node is now dead, remove it from the graph.
9239   deleteAndRecombine(N);
9240
9241   if (Swapped)
9242     std::swap(BasePtr, Offset);
9243
9244   // Replace other uses of BasePtr that can be updated to use Ptr
9245   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9246     unsigned OffsetIdx = 1;
9247     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9248       OffsetIdx = 0;
9249     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9250            BasePtr.getNode() && "Expected BasePtr operand");
9251
9252     // We need to replace ptr0 in the following expression:
9253     //   x0 * offset0 + y0 * ptr0 = t0
9254     // knowing that
9255     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9256     //
9257     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9258     // indexed load/store and the expresion that needs to be re-written.
9259     //
9260     // Therefore, we have:
9261     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9262
9263     ConstantSDNode *CN =
9264       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9265     int X0, X1, Y0, Y1;
9266     APInt Offset0 = CN->getAPIntValue();
9267     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9268
9269     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9270     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9271     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9272     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9273
9274     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9275
9276     APInt CNV = Offset0;
9277     if (X0 < 0) CNV = -CNV;
9278     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9279     else CNV = CNV - Offset1;
9280
9281     SDLoc DL(OtherUses[i]);
9282
9283     // We can now generate the new expression.
9284     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9285     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9286
9287     SDValue NewUse = DAG.getNode(Opcode,
9288                                  DL,
9289                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9290     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9291     deleteAndRecombine(OtherUses[i]);
9292   }
9293
9294   // Replace the uses of Ptr with uses of the updated base value.
9295   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9296   deleteAndRecombine(Ptr.getNode());
9297
9298   return true;
9299 }
9300
9301 /// Try to combine a load/store with a add/sub of the base pointer node into a
9302 /// post-indexed load/store. The transformation folded the add/subtract into the
9303 /// new indexed load/store effectively and all of its uses are redirected to the
9304 /// new load/store.
9305 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9306   if (Level < AfterLegalizeDAG)
9307     return false;
9308
9309   bool isLoad = true;
9310   SDValue Ptr;
9311   EVT VT;
9312   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9313     if (LD->isIndexed())
9314       return false;
9315     VT = LD->getMemoryVT();
9316     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9317         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9318       return false;
9319     Ptr = LD->getBasePtr();
9320   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9321     if (ST->isIndexed())
9322       return false;
9323     VT = ST->getMemoryVT();
9324     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9325         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9326       return false;
9327     Ptr = ST->getBasePtr();
9328     isLoad = false;
9329   } else {
9330     return false;
9331   }
9332
9333   if (Ptr.getNode()->hasOneUse())
9334     return false;
9335
9336   for (SDNode *Op : Ptr.getNode()->uses()) {
9337     if (Op == N ||
9338         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9339       continue;
9340
9341     SDValue BasePtr;
9342     SDValue Offset;
9343     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9344     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9345       // Don't create a indexed load / store with zero offset.
9346       if (isa<ConstantSDNode>(Offset) &&
9347           cast<ConstantSDNode>(Offset)->isNullValue())
9348         continue;
9349
9350       // Try turning it into a post-indexed load / store except when
9351       // 1) All uses are load / store ops that use it as base ptr (and
9352       //    it may be folded as addressing mmode).
9353       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9354       //    nor a successor of N. Otherwise, if Op is folded that would
9355       //    create a cycle.
9356
9357       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9358         continue;
9359
9360       // Check for #1.
9361       bool TryNext = false;
9362       for (SDNode *Use : BasePtr.getNode()->uses()) {
9363         if (Use == Ptr.getNode())
9364           continue;
9365
9366         // If all the uses are load / store addresses, then don't do the
9367         // transformation.
9368         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9369           bool RealUse = false;
9370           for (SDNode *UseUse : Use->uses()) {
9371             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9372               RealUse = true;
9373           }
9374
9375           if (!RealUse) {
9376             TryNext = true;
9377             break;
9378           }
9379         }
9380       }
9381
9382       if (TryNext)
9383         continue;
9384
9385       // Check for #2
9386       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9387         SDValue Result = isLoad
9388           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9389                                BasePtr, Offset, AM)
9390           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9391                                 BasePtr, Offset, AM);
9392         ++PostIndexedNodes;
9393         ++NodesCombined;
9394         DEBUG(dbgs() << "\nReplacing.5 ";
9395               N->dump(&DAG);
9396               dbgs() << "\nWith: ";
9397               Result.getNode()->dump(&DAG);
9398               dbgs() << '\n');
9399         WorklistRemover DeadNodes(*this);
9400         if (isLoad) {
9401           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9402           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9403         } else {
9404           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9405         }
9406
9407         // Finally, since the node is now dead, remove it from the graph.
9408         deleteAndRecombine(N);
9409
9410         // Replace the uses of Use with uses of the updated base value.
9411         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9412                                       Result.getValue(isLoad ? 1 : 0));
9413         deleteAndRecombine(Op);
9414         return true;
9415       }
9416     }
9417   }
9418
9419   return false;
9420 }
9421
9422 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9423 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9424   ISD::MemIndexedMode AM = LD->getAddressingMode();
9425   assert(AM != ISD::UNINDEXED);
9426   SDValue BP = LD->getOperand(1);
9427   SDValue Inc = LD->getOperand(2);
9428
9429   // Some backends use TargetConstants for load offsets, but don't expect
9430   // TargetConstants in general ADD nodes. We can convert these constants into
9431   // regular Constants (if the constant is not opaque).
9432   assert((Inc.getOpcode() != ISD::TargetConstant ||
9433           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9434          "Cannot split out indexing using opaque target constants");
9435   if (Inc.getOpcode() == ISD::TargetConstant) {
9436     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9437     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9438                           ConstInc->getValueType(0));
9439   }
9440
9441   unsigned Opc =
9442       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9443   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9444 }
9445
9446 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9447   LoadSDNode *LD  = cast<LoadSDNode>(N);
9448   SDValue Chain = LD->getChain();
9449   SDValue Ptr   = LD->getBasePtr();
9450
9451   // If load is not volatile and there are no uses of the loaded value (and
9452   // the updated indexed value in case of indexed loads), change uses of the
9453   // chain value into uses of the chain input (i.e. delete the dead load).
9454   if (!LD->isVolatile()) {
9455     if (N->getValueType(1) == MVT::Other) {
9456       // Unindexed loads.
9457       if (!N->hasAnyUseOfValue(0)) {
9458         // It's not safe to use the two value CombineTo variant here. e.g.
9459         // v1, chain2 = load chain1, loc
9460         // v2, chain3 = load chain2, loc
9461         // v3         = add v2, c
9462         // Now we replace use of chain2 with chain1.  This makes the second load
9463         // isomorphic to the one we are deleting, and thus makes this load live.
9464         DEBUG(dbgs() << "\nReplacing.6 ";
9465               N->dump(&DAG);
9466               dbgs() << "\nWith chain: ";
9467               Chain.getNode()->dump(&DAG);
9468               dbgs() << "\n");
9469         WorklistRemover DeadNodes(*this);
9470         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9471
9472         if (N->use_empty())
9473           deleteAndRecombine(N);
9474
9475         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9476       }
9477     } else {
9478       // Indexed loads.
9479       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9480
9481       // If this load has an opaque TargetConstant offset, then we cannot split
9482       // the indexing into an add/sub directly (that TargetConstant may not be
9483       // valid for a different type of node, and we cannot convert an opaque
9484       // target constant into a regular constant).
9485       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9486                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9487
9488       if (!N->hasAnyUseOfValue(0) &&
9489           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9490         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9491         SDValue Index;
9492         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9493           Index = SplitIndexingFromLoad(LD);
9494           // Try to fold the base pointer arithmetic into subsequent loads and
9495           // stores.
9496           AddUsersToWorklist(N);
9497         } else
9498           Index = DAG.getUNDEF(N->getValueType(1));
9499         DEBUG(dbgs() << "\nReplacing.7 ";
9500               N->dump(&DAG);
9501               dbgs() << "\nWith: ";
9502               Undef.getNode()->dump(&DAG);
9503               dbgs() << " and 2 other values\n");
9504         WorklistRemover DeadNodes(*this);
9505         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9506         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9507         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9508         deleteAndRecombine(N);
9509         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9510       }
9511     }
9512   }
9513
9514   // If this load is directly stored, replace the load value with the stored
9515   // value.
9516   // TODO: Handle store large -> read small portion.
9517   // TODO: Handle TRUNCSTORE/LOADEXT
9518   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9519     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9520       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9521       if (PrevST->getBasePtr() == Ptr &&
9522           PrevST->getValue().getValueType() == N->getValueType(0))
9523       return CombineTo(N, Chain.getOperand(1), Chain);
9524     }
9525   }
9526
9527   // Try to infer better alignment information than the load already has.
9528   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9529     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9530       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9531         SDValue NewLoad =
9532                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9533                               LD->getValueType(0),
9534                               Chain, Ptr, LD->getPointerInfo(),
9535                               LD->getMemoryVT(),
9536                               LD->isVolatile(), LD->isNonTemporal(),
9537                               LD->isInvariant(), Align, LD->getAAInfo());
9538         if (NewLoad.getNode() != N)
9539           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9540       }
9541     }
9542   }
9543
9544   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9545                                                   : DAG.getSubtarget().useAA();
9546 #ifndef NDEBUG
9547   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9548       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9549     UseAA = false;
9550 #endif
9551   if (UseAA && LD->isUnindexed()) {
9552     // Walk up chain skipping non-aliasing memory nodes.
9553     SDValue BetterChain = FindBetterChain(N, Chain);
9554
9555     // If there is a better chain.
9556     if (Chain != BetterChain) {
9557       SDValue ReplLoad;
9558
9559       // Replace the chain to void dependency.
9560       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9561         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9562                                BetterChain, Ptr, LD->getMemOperand());
9563       } else {
9564         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9565                                   LD->getValueType(0),
9566                                   BetterChain, Ptr, LD->getMemoryVT(),
9567                                   LD->getMemOperand());
9568       }
9569
9570       // Create token factor to keep old chain connected.
9571       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9572                                   MVT::Other, Chain, ReplLoad.getValue(1));
9573
9574       // Make sure the new and old chains are cleaned up.
9575       AddToWorklist(Token.getNode());
9576
9577       // Replace uses with load result and token factor. Don't add users
9578       // to work list.
9579       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9580     }
9581   }
9582
9583   // Try transforming N to an indexed load.
9584   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9585     return SDValue(N, 0);
9586
9587   // Try to slice up N to more direct loads if the slices are mapped to
9588   // different register banks or pairing can take place.
9589   if (SliceUpLoad(N))
9590     return SDValue(N, 0);
9591
9592   return SDValue();
9593 }
9594
9595 namespace {
9596 /// \brief Helper structure used to slice a load in smaller loads.
9597 /// Basically a slice is obtained from the following sequence:
9598 /// Origin = load Ty1, Base
9599 /// Shift = srl Ty1 Origin, CstTy Amount
9600 /// Inst = trunc Shift to Ty2
9601 ///
9602 /// Then, it will be rewriten into:
9603 /// Slice = load SliceTy, Base + SliceOffset
9604 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9605 ///
9606 /// SliceTy is deduced from the number of bits that are actually used to
9607 /// build Inst.
9608 struct LoadedSlice {
9609   /// \brief Helper structure used to compute the cost of a slice.
9610   struct Cost {
9611     /// Are we optimizing for code size.
9612     bool ForCodeSize;
9613     /// Various cost.
9614     unsigned Loads;
9615     unsigned Truncates;
9616     unsigned CrossRegisterBanksCopies;
9617     unsigned ZExts;
9618     unsigned Shift;
9619
9620     Cost(bool ForCodeSize = false)
9621         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9622           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9623
9624     /// \brief Get the cost of one isolated slice.
9625     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9626         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9627           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9628       EVT TruncType = LS.Inst->getValueType(0);
9629       EVT LoadedType = LS.getLoadedType();
9630       if (TruncType != LoadedType &&
9631           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9632         ZExts = 1;
9633     }
9634
9635     /// \brief Account for slicing gain in the current cost.
9636     /// Slicing provide a few gains like removing a shift or a
9637     /// truncate. This method allows to grow the cost of the original
9638     /// load with the gain from this slice.
9639     void addSliceGain(const LoadedSlice &LS) {
9640       // Each slice saves a truncate.
9641       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9642       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9643                               LS.Inst->getOperand(0).getValueType()))
9644         ++Truncates;
9645       // If there is a shift amount, this slice gets rid of it.
9646       if (LS.Shift)
9647         ++Shift;
9648       // If this slice can merge a cross register bank copy, account for it.
9649       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9650         ++CrossRegisterBanksCopies;
9651     }
9652
9653     Cost &operator+=(const Cost &RHS) {
9654       Loads += RHS.Loads;
9655       Truncates += RHS.Truncates;
9656       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9657       ZExts += RHS.ZExts;
9658       Shift += RHS.Shift;
9659       return *this;
9660     }
9661
9662     bool operator==(const Cost &RHS) const {
9663       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9664              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9665              ZExts == RHS.ZExts && Shift == RHS.Shift;
9666     }
9667
9668     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9669
9670     bool operator<(const Cost &RHS) const {
9671       // Assume cross register banks copies are as expensive as loads.
9672       // FIXME: Do we want some more target hooks?
9673       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9674       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9675       // Unless we are optimizing for code size, consider the
9676       // expensive operation first.
9677       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9678         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9679       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9680              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9681     }
9682
9683     bool operator>(const Cost &RHS) const { return RHS < *this; }
9684
9685     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9686
9687     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9688   };
9689   // The last instruction that represent the slice. This should be a
9690   // truncate instruction.
9691   SDNode *Inst;
9692   // The original load instruction.
9693   LoadSDNode *Origin;
9694   // The right shift amount in bits from the original load.
9695   unsigned Shift;
9696   // The DAG from which Origin came from.
9697   // This is used to get some contextual information about legal types, etc.
9698   SelectionDAG *DAG;
9699
9700   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9701               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9702       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9703
9704   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9705   /// \return Result is \p BitWidth and has used bits set to 1 and
9706   ///         not used bits set to 0.
9707   APInt getUsedBits() const {
9708     // Reproduce the trunc(lshr) sequence:
9709     // - Start from the truncated value.
9710     // - Zero extend to the desired bit width.
9711     // - Shift left.
9712     assert(Origin && "No original load to compare against.");
9713     unsigned BitWidth = Origin->getValueSizeInBits(0);
9714     assert(Inst && "This slice is not bound to an instruction");
9715     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9716            "Extracted slice is bigger than the whole type!");
9717     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9718     UsedBits.setAllBits();
9719     UsedBits = UsedBits.zext(BitWidth);
9720     UsedBits <<= Shift;
9721     return UsedBits;
9722   }
9723
9724   /// \brief Get the size of the slice to be loaded in bytes.
9725   unsigned getLoadedSize() const {
9726     unsigned SliceSize = getUsedBits().countPopulation();
9727     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9728     return SliceSize / 8;
9729   }
9730
9731   /// \brief Get the type that will be loaded for this slice.
9732   /// Note: This may not be the final type for the slice.
9733   EVT getLoadedType() const {
9734     assert(DAG && "Missing context");
9735     LLVMContext &Ctxt = *DAG->getContext();
9736     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9737   }
9738
9739   /// \brief Get the alignment of the load used for this slice.
9740   unsigned getAlignment() const {
9741     unsigned Alignment = Origin->getAlignment();
9742     unsigned Offset = getOffsetFromBase();
9743     if (Offset != 0)
9744       Alignment = MinAlign(Alignment, Alignment + Offset);
9745     return Alignment;
9746   }
9747
9748   /// \brief Check if this slice can be rewritten with legal operations.
9749   bool isLegal() const {
9750     // An invalid slice is not legal.
9751     if (!Origin || !Inst || !DAG)
9752       return false;
9753
9754     // Offsets are for indexed load only, we do not handle that.
9755     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9756       return false;
9757
9758     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9759
9760     // Check that the type is legal.
9761     EVT SliceType = getLoadedType();
9762     if (!TLI.isTypeLegal(SliceType))
9763       return false;
9764
9765     // Check that the load is legal for this type.
9766     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9767       return false;
9768
9769     // Check that the offset can be computed.
9770     // 1. Check its type.
9771     EVT PtrType = Origin->getBasePtr().getValueType();
9772     if (PtrType == MVT::Untyped || PtrType.isExtended())
9773       return false;
9774
9775     // 2. Check that it fits in the immediate.
9776     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9777       return false;
9778
9779     // 3. Check that the computation is legal.
9780     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9781       return false;
9782
9783     // Check that the zext is legal if it needs one.
9784     EVT TruncateType = Inst->getValueType(0);
9785     if (TruncateType != SliceType &&
9786         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9787       return false;
9788
9789     return true;
9790   }
9791
9792   /// \brief Get the offset in bytes of this slice in the original chunk of
9793   /// bits.
9794   /// \pre DAG != nullptr.
9795   uint64_t getOffsetFromBase() const {
9796     assert(DAG && "Missing context.");
9797     bool IsBigEndian =
9798         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9799     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9800     uint64_t Offset = Shift / 8;
9801     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9802     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9803            "The size of the original loaded type is not a multiple of a"
9804            " byte.");
9805     // If Offset is bigger than TySizeInBytes, it means we are loading all
9806     // zeros. This should have been optimized before in the process.
9807     assert(TySizeInBytes > Offset &&
9808            "Invalid shift amount for given loaded size");
9809     if (IsBigEndian)
9810       Offset = TySizeInBytes - Offset - getLoadedSize();
9811     return Offset;
9812   }
9813
9814   /// \brief Generate the sequence of instructions to load the slice
9815   /// represented by this object and redirect the uses of this slice to
9816   /// this new sequence of instructions.
9817   /// \pre this->Inst && this->Origin are valid Instructions and this
9818   /// object passed the legal check: LoadedSlice::isLegal returned true.
9819   /// \return The last instruction of the sequence used to load the slice.
9820   SDValue loadSlice() const {
9821     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9822     const SDValue &OldBaseAddr = Origin->getBasePtr();
9823     SDValue BaseAddr = OldBaseAddr;
9824     // Get the offset in that chunk of bytes w.r.t. the endianess.
9825     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9826     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9827     if (Offset) {
9828       // BaseAddr = BaseAddr + Offset.
9829       EVT ArithType = BaseAddr.getValueType();
9830       SDLoc DL(Origin);
9831       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9832                               DAG->getConstant(Offset, DL, ArithType));
9833     }
9834
9835     // Create the type of the loaded slice according to its size.
9836     EVT SliceType = getLoadedType();
9837
9838     // Create the load for the slice.
9839     SDValue LastInst = DAG->getLoad(
9840         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9841         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9842         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9843     // If the final type is not the same as the loaded type, this means that
9844     // we have to pad with zero. Create a zero extend for that.
9845     EVT FinalType = Inst->getValueType(0);
9846     if (SliceType != FinalType)
9847       LastInst =
9848           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9849     return LastInst;
9850   }
9851
9852   /// \brief Check if this slice can be merged with an expensive cross register
9853   /// bank copy. E.g.,
9854   /// i = load i32
9855   /// f = bitcast i32 i to float
9856   bool canMergeExpensiveCrossRegisterBankCopy() const {
9857     if (!Inst || !Inst->hasOneUse())
9858       return false;
9859     SDNode *Use = *Inst->use_begin();
9860     if (Use->getOpcode() != ISD::BITCAST)
9861       return false;
9862     assert(DAG && "Missing context");
9863     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9864     EVT ResVT = Use->getValueType(0);
9865     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9866     const TargetRegisterClass *ArgRC =
9867         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9868     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9869       return false;
9870
9871     // At this point, we know that we perform a cross-register-bank copy.
9872     // Check if it is expensive.
9873     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9874     // Assume bitcasts are cheap, unless both register classes do not
9875     // explicitly share a common sub class.
9876     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9877       return false;
9878
9879     // Check if it will be merged with the load.
9880     // 1. Check the alignment constraint.
9881     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9882         ResVT.getTypeForEVT(*DAG->getContext()));
9883
9884     if (RequiredAlignment > getAlignment())
9885       return false;
9886
9887     // 2. Check that the load is a legal operation for that type.
9888     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9889       return false;
9890
9891     // 3. Check that we do not have a zext in the way.
9892     if (Inst->getValueType(0) != getLoadedType())
9893       return false;
9894
9895     return true;
9896   }
9897 };
9898 }
9899
9900 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9901 /// \p UsedBits looks like 0..0 1..1 0..0.
9902 static bool areUsedBitsDense(const APInt &UsedBits) {
9903   // If all the bits are one, this is dense!
9904   if (UsedBits.isAllOnesValue())
9905     return true;
9906
9907   // Get rid of the unused bits on the right.
9908   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9909   // Get rid of the unused bits on the left.
9910   if (NarrowedUsedBits.countLeadingZeros())
9911     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9912   // Check that the chunk of bits is completely used.
9913   return NarrowedUsedBits.isAllOnesValue();
9914 }
9915
9916 /// \brief Check whether or not \p First and \p Second are next to each other
9917 /// in memory. This means that there is no hole between the bits loaded
9918 /// by \p First and the bits loaded by \p Second.
9919 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9920                                      const LoadedSlice &Second) {
9921   assert(First.Origin == Second.Origin && First.Origin &&
9922          "Unable to match different memory origins.");
9923   APInt UsedBits = First.getUsedBits();
9924   assert((UsedBits & Second.getUsedBits()) == 0 &&
9925          "Slices are not supposed to overlap.");
9926   UsedBits |= Second.getUsedBits();
9927   return areUsedBitsDense(UsedBits);
9928 }
9929
9930 /// \brief Adjust the \p GlobalLSCost according to the target
9931 /// paring capabilities and the layout of the slices.
9932 /// \pre \p GlobalLSCost should account for at least as many loads as
9933 /// there is in the slices in \p LoadedSlices.
9934 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9935                                  LoadedSlice::Cost &GlobalLSCost) {
9936   unsigned NumberOfSlices = LoadedSlices.size();
9937   // If there is less than 2 elements, no pairing is possible.
9938   if (NumberOfSlices < 2)
9939     return;
9940
9941   // Sort the slices so that elements that are likely to be next to each
9942   // other in memory are next to each other in the list.
9943   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9944             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9945     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9946     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9947   });
9948   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9949   // First (resp. Second) is the first (resp. Second) potentially candidate
9950   // to be placed in a paired load.
9951   const LoadedSlice *First = nullptr;
9952   const LoadedSlice *Second = nullptr;
9953   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9954                 // Set the beginning of the pair.
9955                                                            First = Second) {
9956
9957     Second = &LoadedSlices[CurrSlice];
9958
9959     // If First is NULL, it means we start a new pair.
9960     // Get to the next slice.
9961     if (!First)
9962       continue;
9963
9964     EVT LoadedType = First->getLoadedType();
9965
9966     // If the types of the slices are different, we cannot pair them.
9967     if (LoadedType != Second->getLoadedType())
9968       continue;
9969
9970     // Check if the target supplies paired loads for this type.
9971     unsigned RequiredAlignment = 0;
9972     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9973       // move to the next pair, this type is hopeless.
9974       Second = nullptr;
9975       continue;
9976     }
9977     // Check if we meet the alignment requirement.
9978     if (RequiredAlignment > First->getAlignment())
9979       continue;
9980
9981     // Check that both loads are next to each other in memory.
9982     if (!areSlicesNextToEachOther(*First, *Second))
9983       continue;
9984
9985     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9986     --GlobalLSCost.Loads;
9987     // Move to the next pair.
9988     Second = nullptr;
9989   }
9990 }
9991
9992 /// \brief Check the profitability of all involved LoadedSlice.
9993 /// Currently, it is considered profitable if there is exactly two
9994 /// involved slices (1) which are (2) next to each other in memory, and
9995 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9996 ///
9997 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9998 /// the elements themselves.
9999 ///
10000 /// FIXME: When the cost model will be mature enough, we can relax
10001 /// constraints (1) and (2).
10002 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10003                                 const APInt &UsedBits, bool ForCodeSize) {
10004   unsigned NumberOfSlices = LoadedSlices.size();
10005   if (StressLoadSlicing)
10006     return NumberOfSlices > 1;
10007
10008   // Check (1).
10009   if (NumberOfSlices != 2)
10010     return false;
10011
10012   // Check (2).
10013   if (!areUsedBitsDense(UsedBits))
10014     return false;
10015
10016   // Check (3).
10017   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10018   // The original code has one big load.
10019   OrigCost.Loads = 1;
10020   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10021     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10022     // Accumulate the cost of all the slices.
10023     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10024     GlobalSlicingCost += SliceCost;
10025
10026     // Account as cost in the original configuration the gain obtained
10027     // with the current slices.
10028     OrigCost.addSliceGain(LS);
10029   }
10030
10031   // If the target supports paired load, adjust the cost accordingly.
10032   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10033   return OrigCost > GlobalSlicingCost;
10034 }
10035
10036 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10037 /// operations, split it in the various pieces being extracted.
10038 ///
10039 /// This sort of thing is introduced by SROA.
10040 /// This slicing takes care not to insert overlapping loads.
10041 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10042 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10043   if (Level < AfterLegalizeDAG)
10044     return false;
10045
10046   LoadSDNode *LD = cast<LoadSDNode>(N);
10047   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10048       !LD->getValueType(0).isInteger())
10049     return false;
10050
10051   // Keep track of already used bits to detect overlapping values.
10052   // In that case, we will just abort the transformation.
10053   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10054
10055   SmallVector<LoadedSlice, 4> LoadedSlices;
10056
10057   // Check if this load is used as several smaller chunks of bits.
10058   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10059   // of computation for each trunc.
10060   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10061        UI != UIEnd; ++UI) {
10062     // Skip the uses of the chain.
10063     if (UI.getUse().getResNo() != 0)
10064       continue;
10065
10066     SDNode *User = *UI;
10067     unsigned Shift = 0;
10068
10069     // Check if this is a trunc(lshr).
10070     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10071         isa<ConstantSDNode>(User->getOperand(1))) {
10072       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10073       User = *User->use_begin();
10074     }
10075
10076     // At this point, User is a Truncate, iff we encountered, trunc or
10077     // trunc(lshr).
10078     if (User->getOpcode() != ISD::TRUNCATE)
10079       return false;
10080
10081     // The width of the type must be a power of 2 and greater than 8-bits.
10082     // Otherwise the load cannot be represented in LLVM IR.
10083     // Moreover, if we shifted with a non-8-bits multiple, the slice
10084     // will be across several bytes. We do not support that.
10085     unsigned Width = User->getValueSizeInBits(0);
10086     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10087       return 0;
10088
10089     // Build the slice for this chain of computations.
10090     LoadedSlice LS(User, LD, Shift, &DAG);
10091     APInt CurrentUsedBits = LS.getUsedBits();
10092
10093     // Check if this slice overlaps with another.
10094     if ((CurrentUsedBits & UsedBits) != 0)
10095       return false;
10096     // Update the bits used globally.
10097     UsedBits |= CurrentUsedBits;
10098
10099     // Check if the new slice would be legal.
10100     if (!LS.isLegal())
10101       return false;
10102
10103     // Record the slice.
10104     LoadedSlices.push_back(LS);
10105   }
10106
10107   // Abort slicing if it does not seem to be profitable.
10108   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10109     return false;
10110
10111   ++SlicedLoads;
10112
10113   // Rewrite each chain to use an independent load.
10114   // By construction, each chain can be represented by a unique load.
10115
10116   // Prepare the argument for the new token factor for all the slices.
10117   SmallVector<SDValue, 8> ArgChains;
10118   for (SmallVectorImpl<LoadedSlice>::const_iterator
10119            LSIt = LoadedSlices.begin(),
10120            LSItEnd = LoadedSlices.end();
10121        LSIt != LSItEnd; ++LSIt) {
10122     SDValue SliceInst = LSIt->loadSlice();
10123     CombineTo(LSIt->Inst, SliceInst, true);
10124     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10125       SliceInst = SliceInst.getOperand(0);
10126     assert(SliceInst->getOpcode() == ISD::LOAD &&
10127            "It takes more than a zext to get to the loaded slice!!");
10128     ArgChains.push_back(SliceInst.getValue(1));
10129   }
10130
10131   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10132                               ArgChains);
10133   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10134   return true;
10135 }
10136
10137 /// Check to see if V is (and load (ptr), imm), where the load is having
10138 /// specific bytes cleared out.  If so, return the byte size being masked out
10139 /// and the shift amount.
10140 static std::pair<unsigned, unsigned>
10141 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10142   std::pair<unsigned, unsigned> Result(0, 0);
10143
10144   // Check for the structure we're looking for.
10145   if (V->getOpcode() != ISD::AND ||
10146       !isa<ConstantSDNode>(V->getOperand(1)) ||
10147       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10148     return Result;
10149
10150   // Check the chain and pointer.
10151   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10152   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10153
10154   // The store should be chained directly to the load or be an operand of a
10155   // tokenfactor.
10156   if (LD == Chain.getNode())
10157     ; // ok.
10158   else if (Chain->getOpcode() != ISD::TokenFactor)
10159     return Result; // Fail.
10160   else {
10161     bool isOk = false;
10162     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10163       if (Chain->getOperand(i).getNode() == LD) {
10164         isOk = true;
10165         break;
10166       }
10167     if (!isOk) return Result;
10168   }
10169
10170   // This only handles simple types.
10171   if (V.getValueType() != MVT::i16 &&
10172       V.getValueType() != MVT::i32 &&
10173       V.getValueType() != MVT::i64)
10174     return Result;
10175
10176   // Check the constant mask.  Invert it so that the bits being masked out are
10177   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10178   // follow the sign bit for uniformity.
10179   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10180   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10181   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10182   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10183   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10184   if (NotMaskLZ == 64) return Result;  // All zero mask.
10185
10186   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10187   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10188     return Result;
10189
10190   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10191   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10192     NotMaskLZ -= 64-V.getValueSizeInBits();
10193
10194   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10195   switch (MaskedBytes) {
10196   case 1:
10197   case 2:
10198   case 4: break;
10199   default: return Result; // All one mask, or 5-byte mask.
10200   }
10201
10202   // Verify that the first bit starts at a multiple of mask so that the access
10203   // is aligned the same as the access width.
10204   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10205
10206   Result.first = MaskedBytes;
10207   Result.second = NotMaskTZ/8;
10208   return Result;
10209 }
10210
10211
10212 /// Check to see if IVal is something that provides a value as specified by
10213 /// MaskInfo. If so, replace the specified store with a narrower store of
10214 /// truncated IVal.
10215 static SDNode *
10216 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10217                                 SDValue IVal, StoreSDNode *St,
10218                                 DAGCombiner *DC) {
10219   unsigned NumBytes = MaskInfo.first;
10220   unsigned ByteShift = MaskInfo.second;
10221   SelectionDAG &DAG = DC->getDAG();
10222
10223   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10224   // that uses this.  If not, this is not a replacement.
10225   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10226                                   ByteShift*8, (ByteShift+NumBytes)*8);
10227   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10228
10229   // Check that it is legal on the target to do this.  It is legal if the new
10230   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10231   // legalization.
10232   MVT VT = MVT::getIntegerVT(NumBytes*8);
10233   if (!DC->isTypeLegal(VT))
10234     return nullptr;
10235
10236   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10237   // shifted by ByteShift and truncated down to NumBytes.
10238   if (ByteShift) {
10239     SDLoc DL(IVal);
10240     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10241                        DAG.getConstant(ByteShift*8, DL,
10242                                     DC->getShiftAmountTy(IVal.getValueType())));
10243   }
10244
10245   // Figure out the offset for the store and the alignment of the access.
10246   unsigned StOffset;
10247   unsigned NewAlign = St->getAlignment();
10248
10249   if (DAG.getTargetLoweringInfo().isLittleEndian())
10250     StOffset = ByteShift;
10251   else
10252     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10253
10254   SDValue Ptr = St->getBasePtr();
10255   if (StOffset) {
10256     SDLoc DL(IVal);
10257     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10258                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10259     NewAlign = MinAlign(NewAlign, StOffset);
10260   }
10261
10262   // Truncate down to the new size.
10263   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10264
10265   ++OpsNarrowed;
10266   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10267                       St->getPointerInfo().getWithOffset(StOffset),
10268                       false, false, NewAlign).getNode();
10269 }
10270
10271
10272 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10273 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10274 /// narrowing the load and store if it would end up being a win for performance
10275 /// or code size.
10276 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10277   StoreSDNode *ST  = cast<StoreSDNode>(N);
10278   if (ST->isVolatile())
10279     return SDValue();
10280
10281   SDValue Chain = ST->getChain();
10282   SDValue Value = ST->getValue();
10283   SDValue Ptr   = ST->getBasePtr();
10284   EVT VT = Value.getValueType();
10285
10286   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10287     return SDValue();
10288
10289   unsigned Opc = Value.getOpcode();
10290
10291   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10292   // is a byte mask indicating a consecutive number of bytes, check to see if
10293   // Y is known to provide just those bytes.  If so, we try to replace the
10294   // load + replace + store sequence with a single (narrower) store, which makes
10295   // the load dead.
10296   if (Opc == ISD::OR) {
10297     std::pair<unsigned, unsigned> MaskedLoad;
10298     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10299     if (MaskedLoad.first)
10300       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10301                                                   Value.getOperand(1), ST,this))
10302         return SDValue(NewST, 0);
10303
10304     // Or is commutative, so try swapping X and Y.
10305     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10306     if (MaskedLoad.first)
10307       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10308                                                   Value.getOperand(0), ST,this))
10309         return SDValue(NewST, 0);
10310   }
10311
10312   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10313       Value.getOperand(1).getOpcode() != ISD::Constant)
10314     return SDValue();
10315
10316   SDValue N0 = Value.getOperand(0);
10317   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10318       Chain == SDValue(N0.getNode(), 1)) {
10319     LoadSDNode *LD = cast<LoadSDNode>(N0);
10320     if (LD->getBasePtr() != Ptr ||
10321         LD->getPointerInfo().getAddrSpace() !=
10322         ST->getPointerInfo().getAddrSpace())
10323       return SDValue();
10324
10325     // Find the type to narrow it the load / op / store to.
10326     SDValue N1 = Value.getOperand(1);
10327     unsigned BitWidth = N1.getValueSizeInBits();
10328     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10329     if (Opc == ISD::AND)
10330       Imm ^= APInt::getAllOnesValue(BitWidth);
10331     if (Imm == 0 || Imm.isAllOnesValue())
10332       return SDValue();
10333     unsigned ShAmt = Imm.countTrailingZeros();
10334     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10335     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10336     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10337     // The narrowing should be profitable, the load/store operation should be
10338     // legal (or custom) and the store size should be equal to the NewVT width.
10339     while (NewBW < BitWidth &&
10340            (NewVT.getStoreSizeInBits() != NewBW ||
10341             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10342             !TLI.isNarrowingProfitable(VT, NewVT))) {
10343       NewBW = NextPowerOf2(NewBW);
10344       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10345     }
10346     if (NewBW >= BitWidth)
10347       return SDValue();
10348
10349     // If the lsb changed does not start at the type bitwidth boundary,
10350     // start at the previous one.
10351     if (ShAmt % NewBW)
10352       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10353     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10354                                    std::min(BitWidth, ShAmt + NewBW));
10355     if ((Imm & Mask) == Imm) {
10356       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10357       if (Opc == ISD::AND)
10358         NewImm ^= APInt::getAllOnesValue(NewBW);
10359       uint64_t PtrOff = ShAmt / 8;
10360       // For big endian targets, we need to adjust the offset to the pointer to
10361       // load the correct bytes.
10362       if (TLI.isBigEndian())
10363         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10364
10365       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10366       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10367       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10368         return SDValue();
10369
10370       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10371                                    Ptr.getValueType(), Ptr,
10372                                    DAG.getConstant(PtrOff, SDLoc(LD),
10373                                                    Ptr.getValueType()));
10374       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10375                                   LD->getChain(), NewPtr,
10376                                   LD->getPointerInfo().getWithOffset(PtrOff),
10377                                   LD->isVolatile(), LD->isNonTemporal(),
10378                                   LD->isInvariant(), NewAlign,
10379                                   LD->getAAInfo());
10380       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10381                                    DAG.getConstant(NewImm, SDLoc(Value),
10382                                                    NewVT));
10383       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10384                                    NewVal, NewPtr,
10385                                    ST->getPointerInfo().getWithOffset(PtrOff),
10386                                    false, false, NewAlign);
10387
10388       AddToWorklist(NewPtr.getNode());
10389       AddToWorklist(NewLD.getNode());
10390       AddToWorklist(NewVal.getNode());
10391       WorklistRemover DeadNodes(*this);
10392       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10393       ++OpsNarrowed;
10394       return NewST;
10395     }
10396   }
10397
10398   return SDValue();
10399 }
10400
10401 /// For a given floating point load / store pair, if the load value isn't used
10402 /// by any other operations, then consider transforming the pair to integer
10403 /// load / store operations if the target deems the transformation profitable.
10404 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10405   StoreSDNode *ST  = cast<StoreSDNode>(N);
10406   SDValue Chain = ST->getChain();
10407   SDValue Value = ST->getValue();
10408   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10409       Value.hasOneUse() &&
10410       Chain == SDValue(Value.getNode(), 1)) {
10411     LoadSDNode *LD = cast<LoadSDNode>(Value);
10412     EVT VT = LD->getMemoryVT();
10413     if (!VT.isFloatingPoint() ||
10414         VT != ST->getMemoryVT() ||
10415         LD->isNonTemporal() ||
10416         ST->isNonTemporal() ||
10417         LD->getPointerInfo().getAddrSpace() != 0 ||
10418         ST->getPointerInfo().getAddrSpace() != 0)
10419       return SDValue();
10420
10421     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10422     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10423         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10424         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10425         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10426       return SDValue();
10427
10428     unsigned LDAlign = LD->getAlignment();
10429     unsigned STAlign = ST->getAlignment();
10430     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10431     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10432     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10433       return SDValue();
10434
10435     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10436                                 LD->getChain(), LD->getBasePtr(),
10437                                 LD->getPointerInfo(),
10438                                 false, false, false, LDAlign);
10439
10440     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10441                                  NewLD, ST->getBasePtr(),
10442                                  ST->getPointerInfo(),
10443                                  false, false, STAlign);
10444
10445     AddToWorklist(NewLD.getNode());
10446     AddToWorklist(NewST.getNode());
10447     WorklistRemover DeadNodes(*this);
10448     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10449     ++LdStFP2Int;
10450     return NewST;
10451   }
10452
10453   return SDValue();
10454 }
10455
10456 namespace {
10457 /// Helper struct to parse and store a memory address as base + index + offset.
10458 /// We ignore sign extensions when it is safe to do so.
10459 /// The following two expressions are not equivalent. To differentiate we need
10460 /// to store whether there was a sign extension involved in the index
10461 /// computation.
10462 ///  (load (i64 add (i64 copyfromreg %c)
10463 ///                 (i64 signextend (add (i8 load %index)
10464 ///                                      (i8 1))))
10465 /// vs
10466 ///
10467 /// (load (i64 add (i64 copyfromreg %c)
10468 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10469 ///                                         (i32 1)))))
10470 struct BaseIndexOffset {
10471   SDValue Base;
10472   SDValue Index;
10473   int64_t Offset;
10474   bool IsIndexSignExt;
10475
10476   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10477
10478   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10479                   bool IsIndexSignExt) :
10480     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10481
10482   bool equalBaseIndex(const BaseIndexOffset &Other) {
10483     return Other.Base == Base && Other.Index == Index &&
10484       Other.IsIndexSignExt == IsIndexSignExt;
10485   }
10486
10487   /// Parses tree in Ptr for base, index, offset addresses.
10488   static BaseIndexOffset match(SDValue Ptr) {
10489     bool IsIndexSignExt = false;
10490
10491     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10492     // instruction, then it could be just the BASE or everything else we don't
10493     // know how to handle. Just use Ptr as BASE and give up.
10494     if (Ptr->getOpcode() != ISD::ADD)
10495       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10496
10497     // We know that we have at least an ADD instruction. Try to pattern match
10498     // the simple case of BASE + OFFSET.
10499     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10500       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10501       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10502                               IsIndexSignExt);
10503     }
10504
10505     // Inside a loop the current BASE pointer is calculated using an ADD and a
10506     // MUL instruction. In this case Ptr is the actual BASE pointer.
10507     // (i64 add (i64 %array_ptr)
10508     //          (i64 mul (i64 %induction_var)
10509     //                   (i64 %element_size)))
10510     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10511       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10512
10513     // Look at Base + Index + Offset cases.
10514     SDValue Base = Ptr->getOperand(0);
10515     SDValue IndexOffset = Ptr->getOperand(1);
10516
10517     // Skip signextends.
10518     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10519       IndexOffset = IndexOffset->getOperand(0);
10520       IsIndexSignExt = true;
10521     }
10522
10523     // Either the case of Base + Index (no offset) or something else.
10524     if (IndexOffset->getOpcode() != ISD::ADD)
10525       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10526
10527     // Now we have the case of Base + Index + offset.
10528     SDValue Index = IndexOffset->getOperand(0);
10529     SDValue Offset = IndexOffset->getOperand(1);
10530
10531     if (!isa<ConstantSDNode>(Offset))
10532       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10533
10534     // Ignore signextends.
10535     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10536       Index = Index->getOperand(0);
10537       IsIndexSignExt = true;
10538     } else IsIndexSignExt = false;
10539
10540     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10541     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10542   }
10543 };
10544 } // namespace
10545
10546 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10547                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10548                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10549   // Make sure we have something to merge.
10550   if (NumElem < 2)
10551     return false;
10552
10553   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10554   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10555   unsigned LatestNodeUsed = 0;
10556
10557   for (unsigned i=0; i < NumElem; ++i) {
10558     // Find a chain for the new wide-store operand. Notice that some
10559     // of the store nodes that we found may not be selected for inclusion
10560     // in the wide store. The chain we use needs to be the chain of the
10561     // latest store node which is *used* and replaced by the wide store.
10562     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10563       LatestNodeUsed = i;
10564   }
10565
10566   // The latest Node in the DAG.
10567   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10568   SDLoc DL(StoreNodes[0].MemNode);
10569
10570   SDValue StoredVal;
10571   if (UseVector) {
10572     // Find a legal type for the vector store.
10573     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10574     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10575     if (IsConstantSrc) {
10576       // A vector store with a constant source implies that the constant is
10577       // zero; we only handle merging stores of constant zeros because the zero
10578       // can be materialized without a load.
10579       // It may be beneficial to loosen this restriction to allow non-zero
10580       // store merging.
10581       StoredVal = DAG.getConstant(0, DL, Ty);
10582     } else {
10583       SmallVector<SDValue, 8> Ops;
10584       for (unsigned i = 0; i < NumElem ; ++i) {
10585         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10586         SDValue Val = St->getValue();
10587         // All of the operands of a BUILD_VECTOR must have the same type.
10588         if (Val.getValueType() != MemVT)
10589           return false;
10590         Ops.push_back(Val);
10591       }
10592
10593       // Build the extracted vector elements back into a vector.
10594       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10595     }
10596   } else {
10597     // We should always use a vector store when merging extracted vector
10598     // elements, so this path implies a store of constants.
10599     assert(IsConstantSrc && "Merged vector elements should use vector store");
10600
10601     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10602     APInt StoreInt(StoreBW, 0);
10603
10604     // Construct a single integer constant which is made of the smaller
10605     // constant inputs.
10606     bool IsLE = TLI.isLittleEndian();
10607     for (unsigned i = 0; i < NumElem ; ++i) {
10608       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10609       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10610       SDValue Val = St->getValue();
10611       StoreInt <<= ElementSizeBytes*8;
10612       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10613         StoreInt |= C->getAPIntValue().zext(StoreBW);
10614       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10615         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10616       } else {
10617         llvm_unreachable("Invalid constant element type");
10618       }
10619     }
10620
10621     // Create the new Load and Store operations.
10622     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10623     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10624   }
10625
10626   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10627                                   FirstInChain->getBasePtr(),
10628                                   FirstInChain->getPointerInfo(),
10629                                   false, false,
10630                                   FirstInChain->getAlignment());
10631
10632   // Replace the last store with the new store
10633   CombineTo(LatestOp, NewStore);
10634   // Erase all other stores.
10635   for (unsigned i = 0; i < NumElem ; ++i) {
10636     if (StoreNodes[i].MemNode == LatestOp)
10637       continue;
10638     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10639     // ReplaceAllUsesWith will replace all uses that existed when it was
10640     // called, but graph optimizations may cause new ones to appear. For
10641     // example, the case in pr14333 looks like
10642     //
10643     //  St's chain -> St -> another store -> X
10644     //
10645     // And the only difference from St to the other store is the chain.
10646     // When we change it's chain to be St's chain they become identical,
10647     // get CSEed and the net result is that X is now a use of St.
10648     // Since we know that St is redundant, just iterate.
10649     while (!St->use_empty())
10650       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10651     deleteAndRecombine(St);
10652   }
10653
10654   return true;
10655 }
10656
10657 static bool allowableAlignment(const SelectionDAG &DAG,
10658                                const TargetLowering &TLI, EVT EVTTy,
10659                                unsigned AS, unsigned Align) {
10660   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10661     return true;
10662
10663   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10664   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10665   return (Align >= ABIAlignment);
10666 }
10667
10668 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10669   if (OptLevel == CodeGenOpt::None)
10670     return false;
10671
10672   EVT MemVT = St->getMemoryVT();
10673   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10674   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10675       Attribute::NoImplicitFloat);
10676
10677   // This function cannot currently deal with non-byte-sized memory sizes.
10678   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10679     return false;
10680
10681   // Don't merge vectors into wider inputs.
10682   if (MemVT.isVector() || !MemVT.isSimple())
10683     return false;
10684
10685   // Perform an early exit check. Do not bother looking at stored values that
10686   // are not constants, loads, or extracted vector elements.
10687   SDValue StoredVal = St->getValue();
10688   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10689   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10690                        isa<ConstantFPSDNode>(StoredVal);
10691   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10692
10693   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10694     return false;
10695
10696   // Only look at ends of store sequences.
10697   SDValue Chain = SDValue(St, 0);
10698   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10699     return false;
10700
10701   // This holds the base pointer, index, and the offset in bytes from the base
10702   // pointer.
10703   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10704
10705   // We must have a base and an offset.
10706   if (!BasePtr.Base.getNode())
10707     return false;
10708
10709   // Do not handle stores to undef base pointers.
10710   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10711     return false;
10712
10713   // Save the LoadSDNodes that we find in the chain.
10714   // We need to make sure that these nodes do not interfere with
10715   // any of the store nodes.
10716   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10717
10718   // Save the StoreSDNodes that we find in the chain.
10719   SmallVector<MemOpLink, 8> StoreNodes;
10720
10721   // Walk up the chain and look for nodes with offsets from the same
10722   // base pointer. Stop when reaching an instruction with a different kind
10723   // or instruction which has a different base pointer.
10724   unsigned Seq = 0;
10725   StoreSDNode *Index = St;
10726   while (Index) {
10727     // If the chain has more than one use, then we can't reorder the mem ops.
10728     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10729       break;
10730
10731     // Find the base pointer and offset for this memory node.
10732     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10733
10734     // Check that the base pointer is the same as the original one.
10735     if (!Ptr.equalBaseIndex(BasePtr))
10736       break;
10737
10738     // The memory operands must not be volatile.
10739     if (Index->isVolatile() || Index->isIndexed())
10740       break;
10741
10742     // No truncation.
10743     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10744       if (St->isTruncatingStore())
10745         break;
10746
10747     // The stored memory type must be the same.
10748     if (Index->getMemoryVT() != MemVT)
10749       break;
10750
10751     // We found a potential memory operand to merge.
10752     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10753
10754     // Find the next memory operand in the chain. If the next operand in the
10755     // chain is a store then move up and continue the scan with the next
10756     // memory operand. If the next operand is a load save it and use alias
10757     // information to check if it interferes with anything.
10758     SDNode *NextInChain = Index->getChain().getNode();
10759     while (1) {
10760       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10761         // We found a store node. Use it for the next iteration.
10762         Index = STn;
10763         break;
10764       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10765         if (Ldn->isVolatile()) {
10766           Index = nullptr;
10767           break;
10768         }
10769
10770         // Save the load node for later. Continue the scan.
10771         AliasLoadNodes.push_back(Ldn);
10772         NextInChain = Ldn->getChain().getNode();
10773         continue;
10774       } else {
10775         Index = nullptr;
10776         break;
10777       }
10778     }
10779   }
10780
10781   // Check if there is anything to merge.
10782   if (StoreNodes.size() < 2)
10783     return false;
10784
10785   // Sort the memory operands according to their distance from the base pointer.
10786   std::sort(StoreNodes.begin(), StoreNodes.end(),
10787             [](MemOpLink LHS, MemOpLink RHS) {
10788     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10789            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10790             LHS.SequenceNum > RHS.SequenceNum);
10791   });
10792
10793   // Scan the memory operations on the chain and find the first non-consecutive
10794   // store memory address.
10795   unsigned LastConsecutiveStore = 0;
10796   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10797   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10798
10799     // Check that the addresses are consecutive starting from the second
10800     // element in the list of stores.
10801     if (i > 0) {
10802       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10803       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10804         break;
10805     }
10806
10807     bool Alias = false;
10808     // Check if this store interferes with any of the loads that we found.
10809     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10810       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10811         Alias = true;
10812         break;
10813       }
10814     // We found a load that alias with this store. Stop the sequence.
10815     if (Alias)
10816       break;
10817
10818     // Mark this node as useful.
10819     LastConsecutiveStore = i;
10820   }
10821
10822   // The node with the lowest store address.
10823   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10824   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10825   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10826
10827   // Store the constants into memory as one consecutive store.
10828   if (IsConstantSrc) {
10829     unsigned LastLegalType = 0;
10830     unsigned LastLegalVectorType = 0;
10831     bool NonZero = false;
10832     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10833       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10834       SDValue StoredVal = St->getValue();
10835
10836       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10837         NonZero |= !C->isNullValue();
10838       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10839         NonZero |= !C->getConstantFPValue()->isNullValue();
10840       } else {
10841         // Non-constant.
10842         break;
10843       }
10844
10845       // Find a legal type for the constant store.
10846       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10847       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10848       if (TLI.isTypeLegal(StoreTy) &&
10849           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10850                              FirstStoreAlign)) {
10851         LastLegalType = i+1;
10852       // Or check whether a truncstore is legal.
10853       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10854                  TargetLowering::TypePromoteInteger) {
10855         EVT LegalizedStoredValueTy =
10856           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10857         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10858             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10859                                FirstStoreAlign)) {
10860           LastLegalType = i + 1;
10861         }
10862       }
10863
10864       // Find a legal type for the vector store.
10865       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10866       if (TLI.isTypeLegal(Ty) &&
10867           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10868         LastLegalVectorType = i + 1;
10869       }
10870     }
10871
10872     // We only use vectors if the constant is known to be zero and the
10873     // function is not marked with the noimplicitfloat attribute.
10874     if (NonZero || NoVectors)
10875       LastLegalVectorType = 0;
10876
10877     // Check if we found a legal integer type to store.
10878     if (LastLegalType == 0 && LastLegalVectorType == 0)
10879       return false;
10880
10881     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10882     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10883
10884     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10885                                            true, UseVector);
10886   }
10887
10888   // When extracting multiple vector elements, try to store them
10889   // in one vector store rather than a sequence of scalar stores.
10890   if (IsExtractVecEltSrc) {
10891     unsigned NumElem = 0;
10892     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10893       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10894       SDValue StoredVal = St->getValue();
10895       // This restriction could be loosened.
10896       // Bail out if any stored values are not elements extracted from a vector.
10897       // It should be possible to handle mixed sources, but load sources need
10898       // more careful handling (see the block of code below that handles
10899       // consecutive loads).
10900       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10901         return false;
10902
10903       // Find a legal type for the vector store.
10904       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10905       if (TLI.isTypeLegal(Ty) &&
10906           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10907         NumElem = i + 1;
10908     }
10909
10910     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10911                                            false, true);
10912   }
10913
10914   // Below we handle the case of multiple consecutive stores that
10915   // come from multiple consecutive loads. We merge them into a single
10916   // wide load and a single wide store.
10917
10918   // Look for load nodes which are used by the stored values.
10919   SmallVector<MemOpLink, 8> LoadNodes;
10920
10921   // Find acceptable loads. Loads need to have the same chain (token factor),
10922   // must not be zext, volatile, indexed, and they must be consecutive.
10923   BaseIndexOffset LdBasePtr;
10924   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10925     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10926     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10927     if (!Ld) break;
10928
10929     // Loads must only have one use.
10930     if (!Ld->hasNUsesOfValue(1, 0))
10931       break;
10932
10933     // The memory operands must not be volatile.
10934     if (Ld->isVolatile() || Ld->isIndexed())
10935       break;
10936
10937     // We do not accept ext loads.
10938     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10939       break;
10940
10941     // The stored memory type must be the same.
10942     if (Ld->getMemoryVT() != MemVT)
10943       break;
10944
10945     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10946     // If this is not the first ptr that we check.
10947     if (LdBasePtr.Base.getNode()) {
10948       // The base ptr must be the same.
10949       if (!LdPtr.equalBaseIndex(LdBasePtr))
10950         break;
10951     } else {
10952       // Check that all other base pointers are the same as this one.
10953       LdBasePtr = LdPtr;
10954     }
10955
10956     // We found a potential memory operand to merge.
10957     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10958   }
10959
10960   if (LoadNodes.size() < 2)
10961     return false;
10962
10963   // If we have load/store pair instructions and we only have two values,
10964   // don't bother.
10965   unsigned RequiredAlignment;
10966   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10967       St->getAlignment() >= RequiredAlignment)
10968     return false;
10969
10970   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10971   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10972   unsigned FirstLoadAlign = FirstLoad->getAlignment();
10973
10974   // Scan the memory operations on the chain and find the first non-consecutive
10975   // load memory address. These variables hold the index in the store node
10976   // array.
10977   unsigned LastConsecutiveLoad = 0;
10978   // This variable refers to the size and not index in the array.
10979   unsigned LastLegalVectorType = 0;
10980   unsigned LastLegalIntegerType = 0;
10981   StartAddress = LoadNodes[0].OffsetFromBase;
10982   SDValue FirstChain = FirstLoad->getChain();
10983   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10984     // All loads much share the same chain.
10985     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10986       break;
10987
10988     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10989     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10990       break;
10991     LastConsecutiveLoad = i;
10992
10993     // Find a legal type for the vector store.
10994     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10995     if (TLI.isTypeLegal(StoreTy) &&
10996         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10997         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10998       LastLegalVectorType = i + 1;
10999     }
11000
11001     // Find a legal type for the integer store.
11002     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11003     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11004     if (TLI.isTypeLegal(StoreTy) &&
11005         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11006         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11007       LastLegalIntegerType = i + 1;
11008     // Or check whether a truncstore and extload is legal.
11009     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11010              TargetLowering::TypePromoteInteger) {
11011       EVT LegalizedStoredValueTy =
11012         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11013       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11014           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11015           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11016           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11017           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11018                              FirstStoreAlign) &&
11019           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11020                              FirstLoadAlign))
11021         LastLegalIntegerType = i+1;
11022     }
11023   }
11024
11025   // Only use vector types if the vector type is larger than the integer type.
11026   // If they are the same, use integers.
11027   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11028   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11029
11030   // We add +1 here because the LastXXX variables refer to location while
11031   // the NumElem refers to array/index size.
11032   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11033   NumElem = std::min(LastLegalType, NumElem);
11034
11035   if (NumElem < 2)
11036     return false;
11037
11038   // The latest Node in the DAG.
11039   unsigned LatestNodeUsed = 0;
11040   for (unsigned i=1; i<NumElem; ++i) {
11041     // Find a chain for the new wide-store operand. Notice that some
11042     // of the store nodes that we found may not be selected for inclusion
11043     // in the wide store. The chain we use needs to be the chain of the
11044     // latest store node which is *used* and replaced by the wide store.
11045     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11046       LatestNodeUsed = i;
11047   }
11048
11049   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11050
11051   // Find if it is better to use vectors or integers to load and store
11052   // to memory.
11053   EVT JointMemOpVT;
11054   if (UseVectorTy) {
11055     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11056   } else {
11057     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11058     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11059   }
11060
11061   SDLoc LoadDL(LoadNodes[0].MemNode);
11062   SDLoc StoreDL(StoreNodes[0].MemNode);
11063
11064   SDValue NewLoad = DAG.getLoad(
11065       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11066       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11067
11068   SDValue NewStore = DAG.getStore(
11069       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11070       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11071
11072   // Replace one of the loads with the new load.
11073   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11074   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11075                                 SDValue(NewLoad.getNode(), 1));
11076
11077   // Remove the rest of the load chains.
11078   for (unsigned i = 1; i < NumElem ; ++i) {
11079     // Replace all chain users of the old load nodes with the chain of the new
11080     // load node.
11081     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11082     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11083   }
11084
11085   // Replace the last store with the new store.
11086   CombineTo(LatestOp, NewStore);
11087   // Erase all other stores.
11088   for (unsigned i = 0; i < NumElem ; ++i) {
11089     // Remove all Store nodes.
11090     if (StoreNodes[i].MemNode == LatestOp)
11091       continue;
11092     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11093     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11094     deleteAndRecombine(St);
11095   }
11096
11097   return true;
11098 }
11099
11100 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11101   StoreSDNode *ST  = cast<StoreSDNode>(N);
11102   SDValue Chain = ST->getChain();
11103   SDValue Value = ST->getValue();
11104   SDValue Ptr   = ST->getBasePtr();
11105
11106   // If this is a store of a bit convert, store the input value if the
11107   // resultant store does not need a higher alignment than the original.
11108   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11109       ST->isUnindexed()) {
11110     unsigned OrigAlign = ST->getAlignment();
11111     EVT SVT = Value.getOperand(0).getValueType();
11112     unsigned Align = TLI.getDataLayout()->
11113       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11114     if (Align <= OrigAlign &&
11115         ((!LegalOperations && !ST->isVolatile()) ||
11116          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11117       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11118                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11119                           ST->isNonTemporal(), OrigAlign,
11120                           ST->getAAInfo());
11121   }
11122
11123   // Turn 'store undef, Ptr' -> nothing.
11124   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11125     return Chain;
11126
11127   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11128   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11129     // NOTE: If the original store is volatile, this transform must not increase
11130     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11131     // processor operation but an i64 (which is not legal) requires two.  So the
11132     // transform should not be done in this case.
11133     if (Value.getOpcode() != ISD::TargetConstantFP) {
11134       SDValue Tmp;
11135       switch (CFP->getSimpleValueType(0).SimpleTy) {
11136       default: llvm_unreachable("Unknown FP type");
11137       case MVT::f16:    // We don't do this for these yet.
11138       case MVT::f80:
11139       case MVT::f128:
11140       case MVT::ppcf128:
11141         break;
11142       case MVT::f32:
11143         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11144             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11145           ;
11146           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11147                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11148                               MVT::i32);
11149           return DAG.getStore(Chain, SDLoc(N), Tmp,
11150                               Ptr, ST->getMemOperand());
11151         }
11152         break;
11153       case MVT::f64:
11154         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11155              !ST->isVolatile()) ||
11156             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11157           ;
11158           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11159                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11160           return DAG.getStore(Chain, SDLoc(N), Tmp,
11161                               Ptr, ST->getMemOperand());
11162         }
11163
11164         if (!ST->isVolatile() &&
11165             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11166           // Many FP stores are not made apparent until after legalize, e.g. for
11167           // argument passing.  Since this is so common, custom legalize the
11168           // 64-bit integer store into two 32-bit stores.
11169           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11170           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11171           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11172           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11173
11174           unsigned Alignment = ST->getAlignment();
11175           bool isVolatile = ST->isVolatile();
11176           bool isNonTemporal = ST->isNonTemporal();
11177           AAMDNodes AAInfo = ST->getAAInfo();
11178
11179           SDLoc DL(N);
11180
11181           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11182                                      Ptr, ST->getPointerInfo(),
11183                                      isVolatile, isNonTemporal,
11184                                      ST->getAlignment(), AAInfo);
11185           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11186                             DAG.getConstant(4, DL, Ptr.getValueType()));
11187           Alignment = MinAlign(Alignment, 4U);
11188           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11189                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11190                                      isVolatile, isNonTemporal,
11191                                      Alignment, AAInfo);
11192           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11193                              St0, St1);
11194         }
11195
11196         break;
11197       }
11198     }
11199   }
11200
11201   // Try to infer better alignment information than the store already has.
11202   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11203     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11204       if (Align > ST->getAlignment()) {
11205         SDValue NewStore =
11206                DAG.getTruncStore(Chain, SDLoc(N), Value,
11207                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11208                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11209                                  ST->getAAInfo());
11210         if (NewStore.getNode() != N)
11211           return CombineTo(ST, NewStore, true);
11212       }
11213     }
11214   }
11215
11216   // Try transforming a pair floating point load / store ops to integer
11217   // load / store ops.
11218   SDValue NewST = TransformFPLoadStorePair(N);
11219   if (NewST.getNode())
11220     return NewST;
11221
11222   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11223                                                   : DAG.getSubtarget().useAA();
11224 #ifndef NDEBUG
11225   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11226       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11227     UseAA = false;
11228 #endif
11229   if (UseAA && ST->isUnindexed()) {
11230     // Walk up chain skipping non-aliasing memory nodes.
11231     SDValue BetterChain = FindBetterChain(N, Chain);
11232
11233     // If there is a better chain.
11234     if (Chain != BetterChain) {
11235       SDValue ReplStore;
11236
11237       // Replace the chain to avoid dependency.
11238       if (ST->isTruncatingStore()) {
11239         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11240                                       ST->getMemoryVT(), ST->getMemOperand());
11241       } else {
11242         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11243                                  ST->getMemOperand());
11244       }
11245
11246       // Create token to keep both nodes around.
11247       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11248                                   MVT::Other, Chain, ReplStore);
11249
11250       // Make sure the new and old chains are cleaned up.
11251       AddToWorklist(Token.getNode());
11252
11253       // Don't add users to work list.
11254       return CombineTo(N, Token, false);
11255     }
11256   }
11257
11258   // Try transforming N to an indexed store.
11259   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11260     return SDValue(N, 0);
11261
11262   // FIXME: is there such a thing as a truncating indexed store?
11263   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11264       Value.getValueType().isInteger()) {
11265     // See if we can simplify the input to this truncstore with knowledge that
11266     // only the low bits are being used.  For example:
11267     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11268     SDValue Shorter =
11269       GetDemandedBits(Value,
11270                       APInt::getLowBitsSet(
11271                         Value.getValueType().getScalarType().getSizeInBits(),
11272                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11273     AddToWorklist(Value.getNode());
11274     if (Shorter.getNode())
11275       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11276                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11277
11278     // Otherwise, see if we can simplify the operation with
11279     // SimplifyDemandedBits, which only works if the value has a single use.
11280     if (SimplifyDemandedBits(Value,
11281                         APInt::getLowBitsSet(
11282                           Value.getValueType().getScalarType().getSizeInBits(),
11283                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11284       return SDValue(N, 0);
11285   }
11286
11287   // If this is a load followed by a store to the same location, then the store
11288   // is dead/noop.
11289   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11290     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11291         ST->isUnindexed() && !ST->isVolatile() &&
11292         // There can't be any side effects between the load and store, such as
11293         // a call or store.
11294         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11295       // The store is dead, remove it.
11296       return Chain;
11297     }
11298   }
11299
11300   // If this is a store followed by a store with the same value to the same
11301   // location, then the store is dead/noop.
11302   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11303     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11304         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11305         ST1->isUnindexed() && !ST1->isVolatile()) {
11306       // The store is dead, remove it.
11307       return Chain;
11308     }
11309   }
11310
11311   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11312   // truncating store.  We can do this even if this is already a truncstore.
11313   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11314       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11315       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11316                             ST->getMemoryVT())) {
11317     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11318                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11319   }
11320
11321   // Only perform this optimization before the types are legal, because we
11322   // don't want to perform this optimization on every DAGCombine invocation.
11323   if (!LegalTypes) {
11324     bool EverChanged = false;
11325
11326     do {
11327       // There can be multiple store sequences on the same chain.
11328       // Keep trying to merge store sequences until we are unable to do so
11329       // or until we merge the last store on the chain.
11330       bool Changed = MergeConsecutiveStores(ST);
11331       EverChanged |= Changed;
11332       if (!Changed) break;
11333     } while (ST->getOpcode() != ISD::DELETED_NODE);
11334
11335     if (EverChanged)
11336       return SDValue(N, 0);
11337   }
11338
11339   return ReduceLoadOpStoreWidth(N);
11340 }
11341
11342 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11343   SDValue InVec = N->getOperand(0);
11344   SDValue InVal = N->getOperand(1);
11345   SDValue EltNo = N->getOperand(2);
11346   SDLoc dl(N);
11347
11348   // If the inserted element is an UNDEF, just use the input vector.
11349   if (InVal.getOpcode() == ISD::UNDEF)
11350     return InVec;
11351
11352   EVT VT = InVec.getValueType();
11353
11354   // If we can't generate a legal BUILD_VECTOR, exit
11355   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11356     return SDValue();
11357
11358   // Check that we know which element is being inserted
11359   if (!isa<ConstantSDNode>(EltNo))
11360     return SDValue();
11361   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11362
11363   // Canonicalize insert_vector_elt dag nodes.
11364   // Example:
11365   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11366   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11367   //
11368   // Do this only if the child insert_vector node has one use; also
11369   // do this only if indices are both constants and Idx1 < Idx0.
11370   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11371       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11372     unsigned OtherElt =
11373       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11374     if (Elt < OtherElt) {
11375       // Swap nodes.
11376       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11377                                   InVec.getOperand(0), InVal, EltNo);
11378       AddToWorklist(NewOp.getNode());
11379       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11380                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11381     }
11382   }
11383
11384   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11385   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11386   // vector elements.
11387   SmallVector<SDValue, 8> Ops;
11388   // Do not combine these two vectors if the output vector will not replace
11389   // the input vector.
11390   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11391     Ops.append(InVec.getNode()->op_begin(),
11392                InVec.getNode()->op_end());
11393   } else if (InVec.getOpcode() == ISD::UNDEF) {
11394     unsigned NElts = VT.getVectorNumElements();
11395     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11396   } else {
11397     return SDValue();
11398   }
11399
11400   // Insert the element
11401   if (Elt < Ops.size()) {
11402     // All the operands of BUILD_VECTOR must have the same type;
11403     // we enforce that here.
11404     EVT OpVT = Ops[0].getValueType();
11405     if (InVal.getValueType() != OpVT)
11406       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11407                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11408                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11409     Ops[Elt] = InVal;
11410   }
11411
11412   // Return the new vector
11413   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11414 }
11415
11416 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11417     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11418   EVT ResultVT = EVE->getValueType(0);
11419   EVT VecEltVT = InVecVT.getVectorElementType();
11420   unsigned Align = OriginalLoad->getAlignment();
11421   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11422       VecEltVT.getTypeForEVT(*DAG.getContext()));
11423
11424   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11425     return SDValue();
11426
11427   Align = NewAlign;
11428
11429   SDValue NewPtr = OriginalLoad->getBasePtr();
11430   SDValue Offset;
11431   EVT PtrType = NewPtr.getValueType();
11432   MachinePointerInfo MPI;
11433   SDLoc DL(EVE);
11434   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11435     int Elt = ConstEltNo->getZExtValue();
11436     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11437     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11438     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11439   } else {
11440     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11441     Offset = DAG.getNode(
11442         ISD::MUL, DL, PtrType, Offset,
11443         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11444     MPI = OriginalLoad->getPointerInfo();
11445   }
11446   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11447
11448   // The replacement we need to do here is a little tricky: we need to
11449   // replace an extractelement of a load with a load.
11450   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11451   // Note that this replacement assumes that the extractvalue is the only
11452   // use of the load; that's okay because we don't want to perform this
11453   // transformation in other cases anyway.
11454   SDValue Load;
11455   SDValue Chain;
11456   if (ResultVT.bitsGT(VecEltVT)) {
11457     // If the result type of vextract is wider than the load, then issue an
11458     // extending load instead.
11459     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11460                                                   VecEltVT)
11461                                    ? ISD::ZEXTLOAD
11462                                    : ISD::EXTLOAD;
11463     Load = DAG.getExtLoad(
11464         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11465         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11466         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11467     Chain = Load.getValue(1);
11468   } else {
11469     Load = DAG.getLoad(
11470         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11471         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11472         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11473     Chain = Load.getValue(1);
11474     if (ResultVT.bitsLT(VecEltVT))
11475       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11476     else
11477       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11478   }
11479   WorklistRemover DeadNodes(*this);
11480   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11481   SDValue To[] = { Load, Chain };
11482   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11483   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11484   // worklist explicitly as well.
11485   AddToWorklist(Load.getNode());
11486   AddUsersToWorklist(Load.getNode()); // Add users too
11487   // Make sure to revisit this node to clean it up; it will usually be dead.
11488   AddToWorklist(EVE);
11489   ++OpsNarrowed;
11490   return SDValue(EVE, 0);
11491 }
11492
11493 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11494   // (vextract (scalar_to_vector val, 0) -> val
11495   SDValue InVec = N->getOperand(0);
11496   EVT VT = InVec.getValueType();
11497   EVT NVT = N->getValueType(0);
11498
11499   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11500     // Check if the result type doesn't match the inserted element type. A
11501     // SCALAR_TO_VECTOR may truncate the inserted element and the
11502     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11503     SDValue InOp = InVec.getOperand(0);
11504     if (InOp.getValueType() != NVT) {
11505       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11506       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11507     }
11508     return InOp;
11509   }
11510
11511   SDValue EltNo = N->getOperand(1);
11512   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11513
11514   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11515   // We only perform this optimization before the op legalization phase because
11516   // we may introduce new vector instructions which are not backed by TD
11517   // patterns. For example on AVX, extracting elements from a wide vector
11518   // without using extract_subvector. However, if we can find an underlying
11519   // scalar value, then we can always use that.
11520   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11521       && ConstEltNo) {
11522     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11523     int NumElem = VT.getVectorNumElements();
11524     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11525     // Find the new index to extract from.
11526     int OrigElt = SVOp->getMaskElt(Elt);
11527
11528     // Extracting an undef index is undef.
11529     if (OrigElt == -1)
11530       return DAG.getUNDEF(NVT);
11531
11532     // Select the right vector half to extract from.
11533     SDValue SVInVec;
11534     if (OrigElt < NumElem) {
11535       SVInVec = InVec->getOperand(0);
11536     } else {
11537       SVInVec = InVec->getOperand(1);
11538       OrigElt -= NumElem;
11539     }
11540
11541     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11542       SDValue InOp = SVInVec.getOperand(OrigElt);
11543       if (InOp.getValueType() != NVT) {
11544         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11545         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11546       }
11547
11548       return InOp;
11549     }
11550
11551     // FIXME: We should handle recursing on other vector shuffles and
11552     // scalar_to_vector here as well.
11553
11554     if (!LegalOperations) {
11555       EVT IndexTy = TLI.getVectorIdxTy();
11556       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11557                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11558     }
11559   }
11560
11561   bool BCNumEltsChanged = false;
11562   EVT ExtVT = VT.getVectorElementType();
11563   EVT LVT = ExtVT;
11564
11565   // If the result of load has to be truncated, then it's not necessarily
11566   // profitable.
11567   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11568     return SDValue();
11569
11570   if (InVec.getOpcode() == ISD::BITCAST) {
11571     // Don't duplicate a load with other uses.
11572     if (!InVec.hasOneUse())
11573       return SDValue();
11574
11575     EVT BCVT = InVec.getOperand(0).getValueType();
11576     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11577       return SDValue();
11578     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11579       BCNumEltsChanged = true;
11580     InVec = InVec.getOperand(0);
11581     ExtVT = BCVT.getVectorElementType();
11582   }
11583
11584   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11585   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11586       ISD::isNormalLoad(InVec.getNode()) &&
11587       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11588     SDValue Index = N->getOperand(1);
11589     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11590       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11591                                                            OrigLoad);
11592   }
11593
11594   // Perform only after legalization to ensure build_vector / vector_shuffle
11595   // optimizations have already been done.
11596   if (!LegalOperations) return SDValue();
11597
11598   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11599   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11600   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11601
11602   if (ConstEltNo) {
11603     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11604
11605     LoadSDNode *LN0 = nullptr;
11606     const ShuffleVectorSDNode *SVN = nullptr;
11607     if (ISD::isNormalLoad(InVec.getNode())) {
11608       LN0 = cast<LoadSDNode>(InVec);
11609     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11610                InVec.getOperand(0).getValueType() == ExtVT &&
11611                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11612       // Don't duplicate a load with other uses.
11613       if (!InVec.hasOneUse())
11614         return SDValue();
11615
11616       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11617     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11618       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11619       // =>
11620       // (load $addr+1*size)
11621
11622       // Don't duplicate a load with other uses.
11623       if (!InVec.hasOneUse())
11624         return SDValue();
11625
11626       // If the bit convert changed the number of elements, it is unsafe
11627       // to examine the mask.
11628       if (BCNumEltsChanged)
11629         return SDValue();
11630
11631       // Select the input vector, guarding against out of range extract vector.
11632       unsigned NumElems = VT.getVectorNumElements();
11633       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11634       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11635
11636       if (InVec.getOpcode() == ISD::BITCAST) {
11637         // Don't duplicate a load with other uses.
11638         if (!InVec.hasOneUse())
11639           return SDValue();
11640
11641         InVec = InVec.getOperand(0);
11642       }
11643       if (ISD::isNormalLoad(InVec.getNode())) {
11644         LN0 = cast<LoadSDNode>(InVec);
11645         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11646         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11647       }
11648     }
11649
11650     // Make sure we found a non-volatile load and the extractelement is
11651     // the only use.
11652     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11653       return SDValue();
11654
11655     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11656     if (Elt == -1)
11657       return DAG.getUNDEF(LVT);
11658
11659     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11660   }
11661
11662   return SDValue();
11663 }
11664
11665 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11666 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11667   // We perform this optimization post type-legalization because
11668   // the type-legalizer often scalarizes integer-promoted vectors.
11669   // Performing this optimization before may create bit-casts which
11670   // will be type-legalized to complex code sequences.
11671   // We perform this optimization only before the operation legalizer because we
11672   // may introduce illegal operations.
11673   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11674     return SDValue();
11675
11676   unsigned NumInScalars = N->getNumOperands();
11677   SDLoc dl(N);
11678   EVT VT = N->getValueType(0);
11679
11680   // Check to see if this is a BUILD_VECTOR of a bunch of values
11681   // which come from any_extend or zero_extend nodes. If so, we can create
11682   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11683   // optimizations. We do not handle sign-extend because we can't fill the sign
11684   // using shuffles.
11685   EVT SourceType = MVT::Other;
11686   bool AllAnyExt = true;
11687
11688   for (unsigned i = 0; i != NumInScalars; ++i) {
11689     SDValue In = N->getOperand(i);
11690     // Ignore undef inputs.
11691     if (In.getOpcode() == ISD::UNDEF) continue;
11692
11693     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11694     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11695
11696     // Abort if the element is not an extension.
11697     if (!ZeroExt && !AnyExt) {
11698       SourceType = MVT::Other;
11699       break;
11700     }
11701
11702     // The input is a ZeroExt or AnyExt. Check the original type.
11703     EVT InTy = In.getOperand(0).getValueType();
11704
11705     // Check that all of the widened source types are the same.
11706     if (SourceType == MVT::Other)
11707       // First time.
11708       SourceType = InTy;
11709     else if (InTy != SourceType) {
11710       // Multiple income types. Abort.
11711       SourceType = MVT::Other;
11712       break;
11713     }
11714
11715     // Check if all of the extends are ANY_EXTENDs.
11716     AllAnyExt &= AnyExt;
11717   }
11718
11719   // In order to have valid types, all of the inputs must be extended from the
11720   // same source type and all of the inputs must be any or zero extend.
11721   // Scalar sizes must be a power of two.
11722   EVT OutScalarTy = VT.getScalarType();
11723   bool ValidTypes = SourceType != MVT::Other &&
11724                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11725                  isPowerOf2_32(SourceType.getSizeInBits());
11726
11727   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11728   // turn into a single shuffle instruction.
11729   if (!ValidTypes)
11730     return SDValue();
11731
11732   bool isLE = TLI.isLittleEndian();
11733   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11734   assert(ElemRatio > 1 && "Invalid element size ratio");
11735   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11736                                DAG.getConstant(0, SDLoc(N), SourceType);
11737
11738   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11739   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11740
11741   // Populate the new build_vector
11742   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11743     SDValue Cast = N->getOperand(i);
11744     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11745             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11746             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11747     SDValue In;
11748     if (Cast.getOpcode() == ISD::UNDEF)
11749       In = DAG.getUNDEF(SourceType);
11750     else
11751       In = Cast->getOperand(0);
11752     unsigned Index = isLE ? (i * ElemRatio) :
11753                             (i * ElemRatio + (ElemRatio - 1));
11754
11755     assert(Index < Ops.size() && "Invalid index");
11756     Ops[Index] = In;
11757   }
11758
11759   // The type of the new BUILD_VECTOR node.
11760   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11761   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11762          "Invalid vector size");
11763   // Check if the new vector type is legal.
11764   if (!isTypeLegal(VecVT)) return SDValue();
11765
11766   // Make the new BUILD_VECTOR.
11767   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11768
11769   // The new BUILD_VECTOR node has the potential to be further optimized.
11770   AddToWorklist(BV.getNode());
11771   // Bitcast to the desired type.
11772   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11773 }
11774
11775 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11776   EVT VT = N->getValueType(0);
11777
11778   unsigned NumInScalars = N->getNumOperands();
11779   SDLoc dl(N);
11780
11781   EVT SrcVT = MVT::Other;
11782   unsigned Opcode = ISD::DELETED_NODE;
11783   unsigned NumDefs = 0;
11784
11785   for (unsigned i = 0; i != NumInScalars; ++i) {
11786     SDValue In = N->getOperand(i);
11787     unsigned Opc = In.getOpcode();
11788
11789     if (Opc == ISD::UNDEF)
11790       continue;
11791
11792     // If all scalar values are floats and converted from integers.
11793     if (Opcode == ISD::DELETED_NODE &&
11794         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11795       Opcode = Opc;
11796     }
11797
11798     if (Opc != Opcode)
11799       return SDValue();
11800
11801     EVT InVT = In.getOperand(0).getValueType();
11802
11803     // If all scalar values are typed differently, bail out. It's chosen to
11804     // simplify BUILD_VECTOR of integer types.
11805     if (SrcVT == MVT::Other)
11806       SrcVT = InVT;
11807     if (SrcVT != InVT)
11808       return SDValue();
11809     NumDefs++;
11810   }
11811
11812   // If the vector has just one element defined, it's not worth to fold it into
11813   // a vectorized one.
11814   if (NumDefs < 2)
11815     return SDValue();
11816
11817   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11818          && "Should only handle conversion from integer to float.");
11819   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11820
11821   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11822
11823   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11824     return SDValue();
11825
11826   // Just because the floating-point vector type is legal does not necessarily
11827   // mean that the corresponding integer vector type is.
11828   if (!isTypeLegal(NVT))
11829     return SDValue();
11830
11831   SmallVector<SDValue, 8> Opnds;
11832   for (unsigned i = 0; i != NumInScalars; ++i) {
11833     SDValue In = N->getOperand(i);
11834
11835     if (In.getOpcode() == ISD::UNDEF)
11836       Opnds.push_back(DAG.getUNDEF(SrcVT));
11837     else
11838       Opnds.push_back(In.getOperand(0));
11839   }
11840   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11841   AddToWorklist(BV.getNode());
11842
11843   return DAG.getNode(Opcode, dl, VT, BV);
11844 }
11845
11846 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11847   unsigned NumInScalars = N->getNumOperands();
11848   SDLoc dl(N);
11849   EVT VT = N->getValueType(0);
11850
11851   // A vector built entirely of undefs is undef.
11852   if (ISD::allOperandsUndef(N))
11853     return DAG.getUNDEF(VT);
11854
11855   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11856     return V;
11857
11858   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11859     return V;
11860
11861   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11862   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11863   // at most two distinct vectors, turn this into a shuffle node.
11864
11865   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11866   if (!isTypeLegal(VT))
11867     return SDValue();
11868
11869   // May only combine to shuffle after legalize if shuffle is legal.
11870   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11871     return SDValue();
11872
11873   SDValue VecIn1, VecIn2;
11874   bool UsesZeroVector = false;
11875   for (unsigned i = 0; i != NumInScalars; ++i) {
11876     SDValue Op = N->getOperand(i);
11877     // Ignore undef inputs.
11878     if (Op.getOpcode() == ISD::UNDEF) continue;
11879
11880     // See if we can combine this build_vector into a blend with a zero vector.
11881     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11882         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11883         (Op.getOpcode() == ISD::ConstantFP &&
11884         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11885       UsesZeroVector = true;
11886       continue;
11887     }
11888
11889     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11890     // constant index, bail out.
11891     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11892         !isa<ConstantSDNode>(Op.getOperand(1))) {
11893       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11894       break;
11895     }
11896
11897     // We allow up to two distinct input vectors.
11898     SDValue ExtractedFromVec = Op.getOperand(0);
11899     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11900       continue;
11901
11902     if (!VecIn1.getNode()) {
11903       VecIn1 = ExtractedFromVec;
11904     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11905       VecIn2 = ExtractedFromVec;
11906     } else {
11907       // Too many inputs.
11908       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11909       break;
11910     }
11911   }
11912
11913   // If everything is good, we can make a shuffle operation.
11914   if (VecIn1.getNode()) {
11915     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11916     SmallVector<int, 8> Mask;
11917     for (unsigned i = 0; i != NumInScalars; ++i) {
11918       unsigned Opcode = N->getOperand(i).getOpcode();
11919       if (Opcode == ISD::UNDEF) {
11920         Mask.push_back(-1);
11921         continue;
11922       }
11923
11924       // Operands can also be zero.
11925       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11926         assert(UsesZeroVector &&
11927                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11928                "Unexpected node found!");
11929         Mask.push_back(NumInScalars+i);
11930         continue;
11931       }
11932
11933       // If extracting from the first vector, just use the index directly.
11934       SDValue Extract = N->getOperand(i);
11935       SDValue ExtVal = Extract.getOperand(1);
11936       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11937       if (Extract.getOperand(0) == VecIn1) {
11938         Mask.push_back(ExtIndex);
11939         continue;
11940       }
11941
11942       // Otherwise, use InIdx + InputVecSize
11943       Mask.push_back(InNumElements + ExtIndex);
11944     }
11945
11946     // Avoid introducing illegal shuffles with zero.
11947     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11948       return SDValue();
11949
11950     // We can't generate a shuffle node with mismatched input and output types.
11951     // Attempt to transform a single input vector to the correct type.
11952     if ((VT != VecIn1.getValueType())) {
11953       // If the input vector type has a different base type to the output
11954       // vector type, bail out.
11955       EVT VTElemType = VT.getVectorElementType();
11956       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11957           (VecIn2.getNode() &&
11958            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11959         return SDValue();
11960
11961       // If the input vector is too small, widen it.
11962       // We only support widening of vectors which are half the size of the
11963       // output registers. For example XMM->YMM widening on X86 with AVX.
11964       EVT VecInT = VecIn1.getValueType();
11965       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11966         // If we only have one small input, widen it by adding undef values.
11967         if (!VecIn2.getNode())
11968           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11969                                DAG.getUNDEF(VecIn1.getValueType()));
11970         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11971           // If we have two small inputs of the same type, try to concat them.
11972           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11973           VecIn2 = SDValue(nullptr, 0);
11974         } else
11975           return SDValue();
11976       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11977         // If the input vector is too large, try to split it.
11978         // We don't support having two input vectors that are too large.
11979         // If the zero vector was used, we can not split the vector,
11980         // since we'd need 3 inputs.
11981         if (UsesZeroVector || VecIn2.getNode())
11982           return SDValue();
11983
11984         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11985           return SDValue();
11986
11987         // Try to replace VecIn1 with two extract_subvectors
11988         // No need to update the masks, they should still be correct.
11989         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11990           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11991         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11992           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11993       } else
11994         return SDValue();
11995     }
11996
11997     if (UsesZeroVector)
11998       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11999                                 DAG.getConstantFP(0.0, dl, VT);
12000     else
12001       // If VecIn2 is unused then change it to undef.
12002       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12003
12004     // Check that we were able to transform all incoming values to the same
12005     // type.
12006     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12007         VecIn1.getValueType() != VT)
12008           return SDValue();
12009
12010     // Return the new VECTOR_SHUFFLE node.
12011     SDValue Ops[2];
12012     Ops[0] = VecIn1;
12013     Ops[1] = VecIn2;
12014     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12015   }
12016
12017   return SDValue();
12018 }
12019
12020 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12022   EVT OpVT = N->getOperand(0).getValueType();
12023
12024   // If the operands are legal vectors, leave them alone.
12025   if (TLI.isTypeLegal(OpVT))
12026     return SDValue();
12027
12028   SDLoc DL(N);
12029   EVT VT = N->getValueType(0);
12030   SmallVector<SDValue, 8> Ops;
12031
12032   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12033   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12034
12035   // Keep track of what we encounter.
12036   bool AnyInteger = false;
12037   bool AnyFP = false;
12038   for (const SDValue &Op : N->ops()) {
12039     if (ISD::BITCAST == Op.getOpcode() &&
12040         !Op.getOperand(0).getValueType().isVector())
12041       Ops.push_back(Op.getOperand(0));
12042     else if (ISD::UNDEF == Op.getOpcode())
12043       Ops.push_back(ScalarUndef);
12044     else
12045       return SDValue();
12046
12047     // Note whether we encounter an integer or floating point scalar.
12048     // If it's neither, bail out, it could be something weird like x86mmx.
12049     EVT LastOpVT = Ops.back().getValueType();
12050     if (LastOpVT.isFloatingPoint())
12051       AnyFP = true;
12052     else if (LastOpVT.isInteger())
12053       AnyInteger = true;
12054     else
12055       return SDValue();
12056   }
12057
12058   // If any of the operands is a floating point scalar bitcast to a vector,
12059   // use floating point types throughout, and bitcast everything.  
12060   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12061   if (AnyFP) {
12062     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12063     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12064     if (AnyInteger) {
12065       for (SDValue &Op : Ops) {
12066         if (Op.getValueType() == SVT)
12067           continue;
12068         if (Op.getOpcode() == ISD::UNDEF)
12069           Op = ScalarUndef;
12070         else
12071           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12072       }
12073     }
12074   }
12075
12076   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12077                                VT.getSizeInBits() / SVT.getSizeInBits());
12078   return DAG.getNode(ISD::BITCAST, DL, VT,
12079                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12080 }
12081
12082 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12083   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12084   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12085   // inputs come from at most two distinct vectors, turn this into a shuffle
12086   // node.
12087
12088   // If we only have one input vector, we don't need to do any concatenation.
12089   if (N->getNumOperands() == 1)
12090     return N->getOperand(0);
12091
12092   // Check if all of the operands are undefs.
12093   EVT VT = N->getValueType(0);
12094   if (ISD::allOperandsUndef(N))
12095     return DAG.getUNDEF(VT);
12096
12097   // Optimize concat_vectors where all but the first of the vectors are undef.
12098   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12099         return Op.getOpcode() == ISD::UNDEF;
12100       })) {
12101     SDValue In = N->getOperand(0);
12102     assert(In.getValueType().isVector() && "Must concat vectors");
12103
12104     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12105     if (In->getOpcode() == ISD::BITCAST &&
12106         !In->getOperand(0)->getValueType(0).isVector()) {
12107       SDValue Scalar = In->getOperand(0);
12108
12109       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12110       // look through the trunc so we can still do the transform:
12111       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12112       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12113           !TLI.isTypeLegal(Scalar.getValueType()) &&
12114           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12115         Scalar = Scalar->getOperand(0);
12116
12117       EVT SclTy = Scalar->getValueType(0);
12118
12119       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12120         return SDValue();
12121
12122       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12123                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12124       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12125         return SDValue();
12126
12127       SDLoc dl = SDLoc(N);
12128       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12129       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12130     }
12131   }
12132
12133   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12134   // We have already tested above for an UNDEF only concatenation.
12135   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12136   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12137   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12138     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12139   };
12140   bool AllBuildVectorsOrUndefs =
12141       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12142   if (AllBuildVectorsOrUndefs) {
12143     SmallVector<SDValue, 8> Opnds;
12144     EVT SVT = VT.getScalarType();
12145
12146     EVT MinVT = SVT;
12147     if (!SVT.isFloatingPoint()) {
12148       // If BUILD_VECTOR are from built from integer, they may have different
12149       // operand types. Get the smallest type and truncate all operands to it.
12150       bool FoundMinVT = false;
12151       for (const SDValue &Op : N->ops())
12152         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12153           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12154           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12155           FoundMinVT = true;
12156         }
12157       assert(FoundMinVT && "Concat vector type mismatch");
12158     }
12159
12160     for (const SDValue &Op : N->ops()) {
12161       EVT OpVT = Op.getValueType();
12162       unsigned NumElts = OpVT.getVectorNumElements();
12163
12164       if (ISD::UNDEF == Op.getOpcode())
12165         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12166
12167       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12168         if (SVT.isFloatingPoint()) {
12169           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12170           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12171         } else {
12172           for (unsigned i = 0; i != NumElts; ++i)
12173             Opnds.push_back(
12174                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12175         }
12176       }
12177     }
12178
12179     assert(VT.getVectorNumElements() == Opnds.size() &&
12180            "Concat vector type mismatch");
12181     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12182   }
12183
12184   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12185   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12186     return V;
12187
12188   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12189   // nodes often generate nop CONCAT_VECTOR nodes.
12190   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12191   // place the incoming vectors at the exact same location.
12192   SDValue SingleSource = SDValue();
12193   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12194
12195   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12196     SDValue Op = N->getOperand(i);
12197
12198     if (Op.getOpcode() == ISD::UNDEF)
12199       continue;
12200
12201     // Check if this is the identity extract:
12202     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12203       return SDValue();
12204
12205     // Find the single incoming vector for the extract_subvector.
12206     if (SingleSource.getNode()) {
12207       if (Op.getOperand(0) != SingleSource)
12208         return SDValue();
12209     } else {
12210       SingleSource = Op.getOperand(0);
12211
12212       // Check the source type is the same as the type of the result.
12213       // If not, this concat may extend the vector, so we can not
12214       // optimize it away.
12215       if (SingleSource.getValueType() != N->getValueType(0))
12216         return SDValue();
12217     }
12218
12219     unsigned IdentityIndex = i * PartNumElem;
12220     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12221     // The extract index must be constant.
12222     if (!CS)
12223       return SDValue();
12224
12225     // Check that we are reading from the identity index.
12226     if (CS->getZExtValue() != IdentityIndex)
12227       return SDValue();
12228   }
12229
12230   if (SingleSource.getNode())
12231     return SingleSource;
12232
12233   return SDValue();
12234 }
12235
12236 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12237   EVT NVT = N->getValueType(0);
12238   SDValue V = N->getOperand(0);
12239
12240   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12241     // Combine:
12242     //    (extract_subvec (concat V1, V2, ...), i)
12243     // Into:
12244     //    Vi if possible
12245     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12246     // type.
12247     if (V->getOperand(0).getValueType() != NVT)
12248       return SDValue();
12249     unsigned Idx = N->getConstantOperandVal(1);
12250     unsigned NumElems = NVT.getVectorNumElements();
12251     assert((Idx % NumElems) == 0 &&
12252            "IDX in concat is not a multiple of the result vector length.");
12253     return V->getOperand(Idx / NumElems);
12254   }
12255
12256   // Skip bitcasting
12257   if (V->getOpcode() == ISD::BITCAST)
12258     V = V.getOperand(0);
12259
12260   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12261     SDLoc dl(N);
12262     // Handle only simple case where vector being inserted and vector
12263     // being extracted are of same type, and are half size of larger vectors.
12264     EVT BigVT = V->getOperand(0).getValueType();
12265     EVT SmallVT = V->getOperand(1).getValueType();
12266     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12267       return SDValue();
12268
12269     // Only handle cases where both indexes are constants with the same type.
12270     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12271     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12272
12273     if (InsIdx && ExtIdx &&
12274         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12275         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12276       // Combine:
12277       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12278       // Into:
12279       //    indices are equal or bit offsets are equal => V1
12280       //    otherwise => (extract_subvec V1, ExtIdx)
12281       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12282           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12283         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12284       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12285                          DAG.getNode(ISD::BITCAST, dl,
12286                                      N->getOperand(0).getValueType(),
12287                                      V->getOperand(0)), N->getOperand(1));
12288     }
12289   }
12290
12291   return SDValue();
12292 }
12293
12294 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12295                                                  SDValue V, SelectionDAG &DAG) {
12296   SDLoc DL(V);
12297   EVT VT = V.getValueType();
12298
12299   switch (V.getOpcode()) {
12300   default:
12301     return V;
12302
12303   case ISD::CONCAT_VECTORS: {
12304     EVT OpVT = V->getOperand(0).getValueType();
12305     int OpSize = OpVT.getVectorNumElements();
12306     SmallBitVector OpUsedElements(OpSize, false);
12307     bool FoundSimplification = false;
12308     SmallVector<SDValue, 4> NewOps;
12309     NewOps.reserve(V->getNumOperands());
12310     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12311       SDValue Op = V->getOperand(i);
12312       bool OpUsed = false;
12313       for (int j = 0; j < OpSize; ++j)
12314         if (UsedElements[i * OpSize + j]) {
12315           OpUsedElements[j] = true;
12316           OpUsed = true;
12317         }
12318       NewOps.push_back(
12319           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12320                  : DAG.getUNDEF(OpVT));
12321       FoundSimplification |= Op == NewOps.back();
12322       OpUsedElements.reset();
12323     }
12324     if (FoundSimplification)
12325       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12326     return V;
12327   }
12328
12329   case ISD::INSERT_SUBVECTOR: {
12330     SDValue BaseV = V->getOperand(0);
12331     SDValue SubV = V->getOperand(1);
12332     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12333     if (!IdxN)
12334       return V;
12335
12336     int SubSize = SubV.getValueType().getVectorNumElements();
12337     int Idx = IdxN->getZExtValue();
12338     bool SubVectorUsed = false;
12339     SmallBitVector SubUsedElements(SubSize, false);
12340     for (int i = 0; i < SubSize; ++i)
12341       if (UsedElements[i + Idx]) {
12342         SubVectorUsed = true;
12343         SubUsedElements[i] = true;
12344         UsedElements[i + Idx] = false;
12345       }
12346
12347     // Now recurse on both the base and sub vectors.
12348     SDValue SimplifiedSubV =
12349         SubVectorUsed
12350             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12351             : DAG.getUNDEF(SubV.getValueType());
12352     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12353     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12354       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12355                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12356     return V;
12357   }
12358   }
12359 }
12360
12361 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12362                                        SDValue N1, SelectionDAG &DAG) {
12363   EVT VT = SVN->getValueType(0);
12364   int NumElts = VT.getVectorNumElements();
12365   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12366   for (int M : SVN->getMask())
12367     if (M >= 0 && M < NumElts)
12368       N0UsedElements[M] = true;
12369     else if (M >= NumElts)
12370       N1UsedElements[M - NumElts] = true;
12371
12372   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12373   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12374   if (S0 == N0 && S1 == N1)
12375     return SDValue();
12376
12377   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12378 }
12379
12380 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12381 // or turn a shuffle of a single concat into simpler shuffle then concat.
12382 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12383   EVT VT = N->getValueType(0);
12384   unsigned NumElts = VT.getVectorNumElements();
12385
12386   SDValue N0 = N->getOperand(0);
12387   SDValue N1 = N->getOperand(1);
12388   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12389
12390   SmallVector<SDValue, 4> Ops;
12391   EVT ConcatVT = N0.getOperand(0).getValueType();
12392   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12393   unsigned NumConcats = NumElts / NumElemsPerConcat;
12394
12395   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12396   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12397   // half vector elements.
12398   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12399       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12400                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12401     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12402                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12403     N1 = DAG.getUNDEF(ConcatVT);
12404     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12405   }
12406
12407   // Look at every vector that's inserted. We're looking for exact
12408   // subvector-sized copies from a concatenated vector
12409   for (unsigned I = 0; I != NumConcats; ++I) {
12410     // Make sure we're dealing with a copy.
12411     unsigned Begin = I * NumElemsPerConcat;
12412     bool AllUndef = true, NoUndef = true;
12413     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12414       if (SVN->getMaskElt(J) >= 0)
12415         AllUndef = false;
12416       else
12417         NoUndef = false;
12418     }
12419
12420     if (NoUndef) {
12421       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12422         return SDValue();
12423
12424       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12425         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12426           return SDValue();
12427
12428       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12429       if (FirstElt < N0.getNumOperands())
12430         Ops.push_back(N0.getOperand(FirstElt));
12431       else
12432         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12433
12434     } else if (AllUndef) {
12435       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12436     } else { // Mixed with general masks and undefs, can't do optimization.
12437       return SDValue();
12438     }
12439   }
12440
12441   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12442 }
12443
12444 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12445   EVT VT = N->getValueType(0);
12446   unsigned NumElts = VT.getVectorNumElements();
12447
12448   SDValue N0 = N->getOperand(0);
12449   SDValue N1 = N->getOperand(1);
12450
12451   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12452
12453   // Canonicalize shuffle undef, undef -> undef
12454   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12455     return DAG.getUNDEF(VT);
12456
12457   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12458
12459   // Canonicalize shuffle v, v -> v, undef
12460   if (N0 == N1) {
12461     SmallVector<int, 8> NewMask;
12462     for (unsigned i = 0; i != NumElts; ++i) {
12463       int Idx = SVN->getMaskElt(i);
12464       if (Idx >= (int)NumElts) Idx -= NumElts;
12465       NewMask.push_back(Idx);
12466     }
12467     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12468                                 &NewMask[0]);
12469   }
12470
12471   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12472   if (N0.getOpcode() == ISD::UNDEF) {
12473     SmallVector<int, 8> NewMask;
12474     for (unsigned i = 0; i != NumElts; ++i) {
12475       int Idx = SVN->getMaskElt(i);
12476       if (Idx >= 0) {
12477         if (Idx >= (int)NumElts)
12478           Idx -= NumElts;
12479         else
12480           Idx = -1; // remove reference to lhs
12481       }
12482       NewMask.push_back(Idx);
12483     }
12484     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12485                                 &NewMask[0]);
12486   }
12487
12488   // Remove references to rhs if it is undef
12489   if (N1.getOpcode() == ISD::UNDEF) {
12490     bool Changed = false;
12491     SmallVector<int, 8> NewMask;
12492     for (unsigned i = 0; i != NumElts; ++i) {
12493       int Idx = SVN->getMaskElt(i);
12494       if (Idx >= (int)NumElts) {
12495         Idx = -1;
12496         Changed = true;
12497       }
12498       NewMask.push_back(Idx);
12499     }
12500     if (Changed)
12501       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12502   }
12503
12504   // If it is a splat, check if the argument vector is another splat or a
12505   // build_vector.
12506   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12507     SDNode *V = N0.getNode();
12508
12509     // If this is a bit convert that changes the element type of the vector but
12510     // not the number of vector elements, look through it.  Be careful not to
12511     // look though conversions that change things like v4f32 to v2f64.
12512     if (V->getOpcode() == ISD::BITCAST) {
12513       SDValue ConvInput = V->getOperand(0);
12514       if (ConvInput.getValueType().isVector() &&
12515           ConvInput.getValueType().getVectorNumElements() == NumElts)
12516         V = ConvInput.getNode();
12517     }
12518
12519     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12520       assert(V->getNumOperands() == NumElts &&
12521              "BUILD_VECTOR has wrong number of operands");
12522       SDValue Base;
12523       bool AllSame = true;
12524       for (unsigned i = 0; i != NumElts; ++i) {
12525         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12526           Base = V->getOperand(i);
12527           break;
12528         }
12529       }
12530       // Splat of <u, u, u, u>, return <u, u, u, u>
12531       if (!Base.getNode())
12532         return N0;
12533       for (unsigned i = 0; i != NumElts; ++i) {
12534         if (V->getOperand(i) != Base) {
12535           AllSame = false;
12536           break;
12537         }
12538       }
12539       // Splat of <x, x, x, x>, return <x, x, x, x>
12540       if (AllSame)
12541         return N0;
12542
12543       // Canonicalize any other splat as a build_vector.
12544       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12545       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12546       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12547                                   V->getValueType(0), Ops);
12548
12549       // We may have jumped through bitcasts, so the type of the
12550       // BUILD_VECTOR may not match the type of the shuffle.
12551       if (V->getValueType(0) != VT)
12552         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12553       return NewBV;
12554     }
12555   }
12556
12557   // There are various patterns used to build up a vector from smaller vectors,
12558   // subvectors, or elements. Scan chains of these and replace unused insertions
12559   // or components with undef.
12560   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12561     return S;
12562
12563   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12564       Level < AfterLegalizeVectorOps &&
12565       (N1.getOpcode() == ISD::UNDEF ||
12566       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12567        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12568     SDValue V = partitionShuffleOfConcats(N, DAG);
12569
12570     if (V.getNode())
12571       return V;
12572   }
12573
12574   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12575   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12576   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12577     SmallVector<SDValue, 8> Ops;
12578     for (int M : SVN->getMask()) {
12579       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12580       if (M >= 0) {
12581         int Idx = M % NumElts;
12582         SDValue &S = (M < (int)NumElts ? N0 : N1);
12583         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12584           Op = S.getOperand(Idx);
12585         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12586           if (Idx == 0)
12587             Op = S.getOperand(0);
12588         } else {
12589           // Operand can't be combined - bail out.
12590           break;
12591         }
12592       }
12593       Ops.push_back(Op);
12594     }
12595     if (Ops.size() == VT.getVectorNumElements()) {
12596       // BUILD_VECTOR requires all inputs to be of the same type, find the
12597       // maximum type and extend them all.
12598       EVT SVT = VT.getScalarType();
12599       if (SVT.isInteger())
12600         for (SDValue &Op : Ops)
12601           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12602       if (SVT != VT.getScalarType())
12603         for (SDValue &Op : Ops)
12604           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12605                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12606                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12607       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12608     }
12609   }
12610
12611   // If this shuffle only has a single input that is a bitcasted shuffle,
12612   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12613   // back to their original types.
12614   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12615       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12616       TLI.isTypeLegal(VT)) {
12617
12618     // Peek through the bitcast only if there is one user.
12619     SDValue BC0 = N0;
12620     while (BC0.getOpcode() == ISD::BITCAST) {
12621       if (!BC0.hasOneUse())
12622         break;
12623       BC0 = BC0.getOperand(0);
12624     }
12625
12626     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12627       if (Scale == 1)
12628         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12629
12630       SmallVector<int, 8> NewMask;
12631       for (int M : Mask)
12632         for (int s = 0; s != Scale; ++s)
12633           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12634       return NewMask;
12635     };
12636
12637     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12638       EVT SVT = VT.getScalarType();
12639       EVT InnerVT = BC0->getValueType(0);
12640       EVT InnerSVT = InnerVT.getScalarType();
12641
12642       // Determine which shuffle works with the smaller scalar type.
12643       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12644       EVT ScaleSVT = ScaleVT.getScalarType();
12645
12646       if (TLI.isTypeLegal(ScaleVT) &&
12647           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12648           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12649
12650         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12651         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12652
12653         // Scale the shuffle masks to the smaller scalar type.
12654         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12655         SmallVector<int, 8> InnerMask =
12656             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12657         SmallVector<int, 8> OuterMask =
12658             ScaleShuffleMask(SVN->getMask(), OuterScale);
12659
12660         // Merge the shuffle masks.
12661         SmallVector<int, 8> NewMask;
12662         for (int M : OuterMask)
12663           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12664
12665         // Test for shuffle mask legality over both commutations.
12666         SDValue SV0 = BC0->getOperand(0);
12667         SDValue SV1 = BC0->getOperand(1);
12668         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12669         if (!LegalMask) {
12670           std::swap(SV0, SV1);
12671           ShuffleVectorSDNode::commuteMask(NewMask);
12672           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12673         }
12674
12675         if (LegalMask) {
12676           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12677           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12678           return DAG.getNode(
12679               ISD::BITCAST, SDLoc(N), VT,
12680               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12681         }
12682       }
12683     }
12684   }
12685
12686   // Canonicalize shuffles according to rules:
12687   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12688   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12689   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12690   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12691       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12692       TLI.isTypeLegal(VT)) {
12693     // The incoming shuffle must be of the same type as the result of the
12694     // current shuffle.
12695     assert(N1->getOperand(0).getValueType() == VT &&
12696            "Shuffle types don't match");
12697
12698     SDValue SV0 = N1->getOperand(0);
12699     SDValue SV1 = N1->getOperand(1);
12700     bool HasSameOp0 = N0 == SV0;
12701     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12702     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12703       // Commute the operands of this shuffle so that next rule
12704       // will trigger.
12705       return DAG.getCommutedVectorShuffle(*SVN);
12706   }
12707
12708   // Try to fold according to rules:
12709   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12710   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12711   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12712   // Don't try to fold shuffles with illegal type.
12713   // Only fold if this shuffle is the only user of the other shuffle.
12714   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12715       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12716     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12717
12718     // The incoming shuffle must be of the same type as the result of the
12719     // current shuffle.
12720     assert(OtherSV->getOperand(0).getValueType() == VT &&
12721            "Shuffle types don't match");
12722
12723     SDValue SV0, SV1;
12724     SmallVector<int, 4> Mask;
12725     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12726     // operand, and SV1 as the second operand.
12727     for (unsigned i = 0; i != NumElts; ++i) {
12728       int Idx = SVN->getMaskElt(i);
12729       if (Idx < 0) {
12730         // Propagate Undef.
12731         Mask.push_back(Idx);
12732         continue;
12733       }
12734
12735       SDValue CurrentVec;
12736       if (Idx < (int)NumElts) {
12737         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12738         // shuffle mask to identify which vector is actually referenced.
12739         Idx = OtherSV->getMaskElt(Idx);
12740         if (Idx < 0) {
12741           // Propagate Undef.
12742           Mask.push_back(Idx);
12743           continue;
12744         }
12745
12746         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12747                                            : OtherSV->getOperand(1);
12748       } else {
12749         // This shuffle index references an element within N1.
12750         CurrentVec = N1;
12751       }
12752
12753       // Simple case where 'CurrentVec' is UNDEF.
12754       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12755         Mask.push_back(-1);
12756         continue;
12757       }
12758
12759       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12760       // will be the first or second operand of the combined shuffle.
12761       Idx = Idx % NumElts;
12762       if (!SV0.getNode() || SV0 == CurrentVec) {
12763         // Ok. CurrentVec is the left hand side.
12764         // Update the mask accordingly.
12765         SV0 = CurrentVec;
12766         Mask.push_back(Idx);
12767         continue;
12768       }
12769
12770       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12771       if (SV1.getNode() && SV1 != CurrentVec)
12772         return SDValue();
12773
12774       // Ok. CurrentVec is the right hand side.
12775       // Update the mask accordingly.
12776       SV1 = CurrentVec;
12777       Mask.push_back(Idx + NumElts);
12778     }
12779
12780     // Check if all indices in Mask are Undef. In case, propagate Undef.
12781     bool isUndefMask = true;
12782     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12783       isUndefMask &= Mask[i] < 0;
12784
12785     if (isUndefMask)
12786       return DAG.getUNDEF(VT);
12787
12788     if (!SV0.getNode())
12789       SV0 = DAG.getUNDEF(VT);
12790     if (!SV1.getNode())
12791       SV1 = DAG.getUNDEF(VT);
12792
12793     // Avoid introducing shuffles with illegal mask.
12794     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12795       ShuffleVectorSDNode::commuteMask(Mask);
12796
12797       if (!TLI.isShuffleMaskLegal(Mask, VT))
12798         return SDValue();
12799
12800       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12801       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12802       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12803       std::swap(SV0, SV1);
12804     }
12805
12806     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12807     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12808     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12809     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12810   }
12811
12812   return SDValue();
12813 }
12814
12815 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12816   SDValue InVal = N->getOperand(0);
12817   EVT VT = N->getValueType(0);
12818
12819   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12820   // with a VECTOR_SHUFFLE.
12821   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12822     SDValue InVec = InVal->getOperand(0);
12823     SDValue EltNo = InVal->getOperand(1);
12824
12825     // FIXME: We could support implicit truncation if the shuffle can be
12826     // scaled to a smaller vector scalar type.
12827     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12828     if (C0 && VT == InVec.getValueType() &&
12829         VT.getScalarType() == InVal.getValueType()) {
12830       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12831       int Elt = C0->getZExtValue();
12832       NewMask[0] = Elt;
12833
12834       if (TLI.isShuffleMaskLegal(NewMask, VT))
12835         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12836                                     NewMask);
12837     }
12838   }
12839
12840   return SDValue();
12841 }
12842
12843 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12844   SDValue N0 = N->getOperand(0);
12845   SDValue N2 = N->getOperand(2);
12846
12847   // If the input vector is a concatenation, and the insert replaces
12848   // one of the halves, we can optimize into a single concat_vectors.
12849   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12850       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12851     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12852     EVT VT = N->getValueType(0);
12853
12854     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12855     // (concat_vectors Z, Y)
12856     if (InsIdx == 0)
12857       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12858                          N->getOperand(1), N0.getOperand(1));
12859
12860     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12861     // (concat_vectors X, Z)
12862     if (InsIdx == VT.getVectorNumElements()/2)
12863       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12864                          N0.getOperand(0), N->getOperand(1));
12865   }
12866
12867   return SDValue();
12868 }
12869
12870 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12871   SDValue N0 = N->getOperand(0);
12872
12873   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12874   if (N0->getOpcode() == ISD::FP16_TO_FP)
12875     return N0->getOperand(0);
12876
12877   return SDValue();
12878 }
12879
12880 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12881 /// with the destination vector and a zero vector.
12882 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12883 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12884 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12885   EVT VT = N->getValueType(0);
12886   SDValue LHS = N->getOperand(0);
12887   SDValue RHS = N->getOperand(1);
12888   SDLoc dl(N);
12889
12890   // Make sure we're not running after operation legalization where it 
12891   // may have custom lowered the vector shuffles.
12892   if (LegalOperations)
12893     return SDValue();
12894
12895   if (N->getOpcode() != ISD::AND)
12896     return SDValue();
12897
12898   if (RHS.getOpcode() == ISD::BITCAST)
12899     RHS = RHS.getOperand(0);
12900
12901   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12902     SmallVector<int, 8> Indices;
12903     unsigned NumElts = RHS.getNumOperands();
12904
12905     for (unsigned i = 0; i != NumElts; ++i) {
12906       SDValue Elt = RHS.getOperand(i);
12907       if (!isa<ConstantSDNode>(Elt))
12908         return SDValue();
12909
12910       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12911         Indices.push_back(i);
12912       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12913         Indices.push_back(NumElts+i);
12914       else
12915         return SDValue();
12916     }
12917
12918     // Let's see if the target supports this vector_shuffle.
12919     EVT RVT = RHS.getValueType();
12920     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12921       return SDValue();
12922
12923     // Return the new VECTOR_SHUFFLE node.
12924     EVT EltVT = RVT.getVectorElementType();
12925     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12926                                    DAG.getConstant(0, dl, EltVT));
12927     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12928     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12929     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12930     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12931   }
12932
12933   return SDValue();
12934 }
12935
12936 /// Visit a binary vector operation, like ADD.
12937 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12938   assert(N->getValueType(0).isVector() &&
12939          "SimplifyVBinOp only works on vectors!");
12940
12941   SDValue LHS = N->getOperand(0);
12942   SDValue RHS = N->getOperand(1);
12943
12944   if (SDValue Shuffle = XformToShuffleWithZero(N))
12945     return Shuffle;
12946
12947   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12948   // this operation.
12949   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12950       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12951     // Check if both vectors are constants. If not bail out.
12952     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12953           cast<BuildVectorSDNode>(RHS)->isConstant()))
12954       return SDValue();
12955
12956     SmallVector<SDValue, 8> Ops;
12957     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12958       SDValue LHSOp = LHS.getOperand(i);
12959       SDValue RHSOp = RHS.getOperand(i);
12960
12961       // Can't fold divide by zero.
12962       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12963           N->getOpcode() == ISD::FDIV) {
12964         if ((RHSOp.getOpcode() == ISD::Constant &&
12965              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12966             (RHSOp.getOpcode() == ISD::ConstantFP &&
12967              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12968           break;
12969       }
12970
12971       EVT VT = LHSOp.getValueType();
12972       EVT RVT = RHSOp.getValueType();
12973       if (RVT != VT) {
12974         // Integer BUILD_VECTOR operands may have types larger than the element
12975         // size (e.g., when the element type is not legal).  Prior to type
12976         // legalization, the types may not match between the two BUILD_VECTORS.
12977         // Truncate one of the operands to make them match.
12978         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12979           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12980         } else {
12981           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12982           VT = RVT;
12983         }
12984       }
12985       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12986                                    LHSOp, RHSOp);
12987       if (FoldOp.getOpcode() != ISD::UNDEF &&
12988           FoldOp.getOpcode() != ISD::Constant &&
12989           FoldOp.getOpcode() != ISD::ConstantFP)
12990         break;
12991       Ops.push_back(FoldOp);
12992       AddToWorklist(FoldOp.getNode());
12993     }
12994
12995     if (Ops.size() == LHS.getNumOperands())
12996       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12997   }
12998
12999   // Type legalization might introduce new shuffles in the DAG.
13000   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13001   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13002   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13003       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13004       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13005       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13006     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13007     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13008
13009     if (SVN0->getMask().equals(SVN1->getMask())) {
13010       EVT VT = N->getValueType(0);
13011       SDValue UndefVector = LHS.getOperand(1);
13012       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13013                                      LHS.getOperand(0), RHS.getOperand(0));
13014       AddUsersToWorklist(N);
13015       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13016                                   &SVN0->getMask()[0]);
13017     }
13018   }
13019
13020   return SDValue();
13021 }
13022
13023 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13024                                     SDValue N1, SDValue N2){
13025   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13026
13027   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13028                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13029
13030   // If we got a simplified select_cc node back from SimplifySelectCC, then
13031   // break it down into a new SETCC node, and a new SELECT node, and then return
13032   // the SELECT node, since we were called with a SELECT node.
13033   if (SCC.getNode()) {
13034     // Check to see if we got a select_cc back (to turn into setcc/select).
13035     // Otherwise, just return whatever node we got back, like fabs.
13036     if (SCC.getOpcode() == ISD::SELECT_CC) {
13037       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13038                                   N0.getValueType(),
13039                                   SCC.getOperand(0), SCC.getOperand(1),
13040                                   SCC.getOperand(4));
13041       AddToWorklist(SETCC.getNode());
13042       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13043                            SCC.getOperand(2), SCC.getOperand(3));
13044     }
13045
13046     return SCC;
13047   }
13048   return SDValue();
13049 }
13050
13051 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13052 /// being selected between, see if we can simplify the select.  Callers of this
13053 /// should assume that TheSelect is deleted if this returns true.  As such, they
13054 /// should return the appropriate thing (e.g. the node) back to the top-level of
13055 /// the DAG combiner loop to avoid it being looked at.
13056 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13057                                     SDValue RHS) {
13058
13059   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13060   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13061   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13062     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13063       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13064       SDValue Sqrt = RHS;
13065       ISD::CondCode CC;
13066       SDValue CmpLHS;
13067       const ConstantFPSDNode *NegZero = nullptr;
13068
13069       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13070         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13071         CmpLHS = TheSelect->getOperand(0);
13072         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13073       } else {
13074         // SELECT or VSELECT
13075         SDValue Cmp = TheSelect->getOperand(0);
13076         if (Cmp.getOpcode() == ISD::SETCC) {
13077           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13078           CmpLHS = Cmp.getOperand(0);
13079           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13080         }
13081       }
13082       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13083           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13084           CC == ISD::SETULT || CC == ISD::SETLT)) {
13085         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13086         CombineTo(TheSelect, Sqrt);
13087         return true;
13088       }
13089     }
13090   }
13091   // Cannot simplify select with vector condition
13092   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13093
13094   // If this is a select from two identical things, try to pull the operation
13095   // through the select.
13096   if (LHS.getOpcode() != RHS.getOpcode() ||
13097       !LHS.hasOneUse() || !RHS.hasOneUse())
13098     return false;
13099
13100   // If this is a load and the token chain is identical, replace the select
13101   // of two loads with a load through a select of the address to load from.
13102   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13103   // constants have been dropped into the constant pool.
13104   if (LHS.getOpcode() == ISD::LOAD) {
13105     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13106     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13107
13108     // Token chains must be identical.
13109     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13110         // Do not let this transformation reduce the number of volatile loads.
13111         LLD->isVolatile() || RLD->isVolatile() ||
13112         // FIXME: If either is a pre/post inc/dec load,
13113         // we'd need to split out the address adjustment.
13114         LLD->isIndexed() || RLD->isIndexed() ||
13115         // If this is an EXTLOAD, the VT's must match.
13116         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13117         // If this is an EXTLOAD, the kind of extension must match.
13118         (LLD->getExtensionType() != RLD->getExtensionType() &&
13119          // The only exception is if one of the extensions is anyext.
13120          LLD->getExtensionType() != ISD::EXTLOAD &&
13121          RLD->getExtensionType() != ISD::EXTLOAD) ||
13122         // FIXME: this discards src value information.  This is
13123         // over-conservative. It would be beneficial to be able to remember
13124         // both potential memory locations.  Since we are discarding
13125         // src value info, don't do the transformation if the memory
13126         // locations are not in the default address space.
13127         LLD->getPointerInfo().getAddrSpace() != 0 ||
13128         RLD->getPointerInfo().getAddrSpace() != 0 ||
13129         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13130                                       LLD->getBasePtr().getValueType()))
13131       return false;
13132
13133     // Check that the select condition doesn't reach either load.  If so,
13134     // folding this will induce a cycle into the DAG.  If not, this is safe to
13135     // xform, so create a select of the addresses.
13136     SDValue Addr;
13137     if (TheSelect->getOpcode() == ISD::SELECT) {
13138       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13139       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13140           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13141         return false;
13142       // The loads must not depend on one another.
13143       if (LLD->isPredecessorOf(RLD) ||
13144           RLD->isPredecessorOf(LLD))
13145         return false;
13146       Addr = DAG.getSelect(SDLoc(TheSelect),
13147                            LLD->getBasePtr().getValueType(),
13148                            TheSelect->getOperand(0), LLD->getBasePtr(),
13149                            RLD->getBasePtr());
13150     } else {  // Otherwise SELECT_CC
13151       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13152       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13153
13154       if ((LLD->hasAnyUseOfValue(1) &&
13155            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13156           (RLD->hasAnyUseOfValue(1) &&
13157            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13158         return false;
13159
13160       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13161                          LLD->getBasePtr().getValueType(),
13162                          TheSelect->getOperand(0),
13163                          TheSelect->getOperand(1),
13164                          LLD->getBasePtr(), RLD->getBasePtr(),
13165                          TheSelect->getOperand(4));
13166     }
13167
13168     SDValue Load;
13169     // It is safe to replace the two loads if they have different alignments,
13170     // but the new load must be the minimum (most restrictive) alignment of the
13171     // inputs.
13172     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13173     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13174     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13175       Load = DAG.getLoad(TheSelect->getValueType(0),
13176                          SDLoc(TheSelect),
13177                          // FIXME: Discards pointer and AA info.
13178                          LLD->getChain(), Addr, MachinePointerInfo(),
13179                          LLD->isVolatile(), LLD->isNonTemporal(),
13180                          isInvariant, Alignment);
13181     } else {
13182       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13183                             RLD->getExtensionType() : LLD->getExtensionType(),
13184                             SDLoc(TheSelect),
13185                             TheSelect->getValueType(0),
13186                             // FIXME: Discards pointer and AA info.
13187                             LLD->getChain(), Addr, MachinePointerInfo(),
13188                             LLD->getMemoryVT(), LLD->isVolatile(),
13189                             LLD->isNonTemporal(), isInvariant, Alignment);
13190     }
13191
13192     // Users of the select now use the result of the load.
13193     CombineTo(TheSelect, Load);
13194
13195     // Users of the old loads now use the new load's chain.  We know the
13196     // old-load value is dead now.
13197     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13198     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13199     return true;
13200   }
13201
13202   return false;
13203 }
13204
13205 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13206 /// where 'cond' is the comparison specified by CC.
13207 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13208                                       SDValue N2, SDValue N3,
13209                                       ISD::CondCode CC, bool NotExtCompare) {
13210   // (x ? y : y) -> y.
13211   if (N2 == N3) return N2;
13212
13213   EVT VT = N2.getValueType();
13214   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13215   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13216   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13217
13218   // Determine if the condition we're dealing with is constant
13219   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13220                               N0, N1, CC, DL, false);
13221   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13222   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13223
13224   // fold select_cc true, x, y -> x
13225   if (SCCC && !SCCC->isNullValue())
13226     return N2;
13227   // fold select_cc false, x, y -> y
13228   if (SCCC && SCCC->isNullValue())
13229     return N3;
13230
13231   // Check to see if we can simplify the select into an fabs node
13232   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13233     // Allow either -0.0 or 0.0
13234     if (CFP->getValueAPF().isZero()) {
13235       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13236       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13237           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13238           N2 == N3.getOperand(0))
13239         return DAG.getNode(ISD::FABS, DL, VT, N0);
13240
13241       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13242       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13243           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13244           N2.getOperand(0) == N3)
13245         return DAG.getNode(ISD::FABS, DL, VT, N3);
13246     }
13247   }
13248
13249   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13250   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13251   // in it.  This is a win when the constant is not otherwise available because
13252   // it replaces two constant pool loads with one.  We only do this if the FP
13253   // type is known to be legal, because if it isn't, then we are before legalize
13254   // types an we want the other legalization to happen first (e.g. to avoid
13255   // messing with soft float) and if the ConstantFP is not legal, because if
13256   // it is legal, we may not need to store the FP constant in a constant pool.
13257   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13258     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13259       if (TLI.isTypeLegal(N2.getValueType()) &&
13260           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13261                TargetLowering::Legal &&
13262            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13263            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13264           // If both constants have multiple uses, then we won't need to do an
13265           // extra load, they are likely around in registers for other users.
13266           (TV->hasOneUse() || FV->hasOneUse())) {
13267         Constant *Elts[] = {
13268           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13269           const_cast<ConstantFP*>(TV->getConstantFPValue())
13270         };
13271         Type *FPTy = Elts[0]->getType();
13272         const DataLayout &TD = *TLI.getDataLayout();
13273
13274         // Create a ConstantArray of the two constants.
13275         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13276         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13277                                             TD.getPrefTypeAlignment(FPTy));
13278         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13279
13280         // Get the offsets to the 0 and 1 element of the array so that we can
13281         // select between them.
13282         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13283         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13284         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13285
13286         SDValue Cond = DAG.getSetCC(DL,
13287                                     getSetCCResultType(N0.getValueType()),
13288                                     N0, N1, CC);
13289         AddToWorklist(Cond.getNode());
13290         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13291                                           Cond, One, Zero);
13292         AddToWorklist(CstOffset.getNode());
13293         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13294                             CstOffset);
13295         AddToWorklist(CPIdx.getNode());
13296         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13297                            MachinePointerInfo::getConstantPool(), false,
13298                            false, false, Alignment);
13299       }
13300     }
13301
13302   // Check to see if we can perform the "gzip trick", transforming
13303   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13304   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13305       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13306        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13307     EVT XType = N0.getValueType();
13308     EVT AType = N2.getValueType();
13309     if (XType.bitsGE(AType)) {
13310       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13311       // single-bit constant.
13312       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13313         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13314         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13315         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13316                                        getShiftAmountTy(N0.getValueType()));
13317         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13318                                     XType, N0, ShCt);
13319         AddToWorklist(Shift.getNode());
13320
13321         if (XType.bitsGT(AType)) {
13322           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13323           AddToWorklist(Shift.getNode());
13324         }
13325
13326         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13327       }
13328
13329       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13330                                   XType, N0,
13331                                   DAG.getConstant(XType.getSizeInBits() - 1,
13332                                                   SDLoc(N0),
13333                                          getShiftAmountTy(N0.getValueType())));
13334       AddToWorklist(Shift.getNode());
13335
13336       if (XType.bitsGT(AType)) {
13337         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13338         AddToWorklist(Shift.getNode());
13339       }
13340
13341       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13342     }
13343   }
13344
13345   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13346   // where y is has a single bit set.
13347   // A plaintext description would be, we can turn the SELECT_CC into an AND
13348   // when the condition can be materialized as an all-ones register.  Any
13349   // single bit-test can be materialized as an all-ones register with
13350   // shift-left and shift-right-arith.
13351   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13352       N0->getValueType(0) == VT &&
13353       N1C && N1C->isNullValue() &&
13354       N2C && N2C->isNullValue()) {
13355     SDValue AndLHS = N0->getOperand(0);
13356     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13357     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13358       // Shift the tested bit over the sign bit.
13359       APInt AndMask = ConstAndRHS->getAPIntValue();
13360       SDValue ShlAmt =
13361         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13362                         getShiftAmountTy(AndLHS.getValueType()));
13363       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13364
13365       // Now arithmetic right shift it all the way over, so the result is either
13366       // all-ones, or zero.
13367       SDValue ShrAmt =
13368         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13369                         getShiftAmountTy(Shl.getValueType()));
13370       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13371
13372       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13373     }
13374   }
13375
13376   // fold select C, 16, 0 -> shl C, 4
13377   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13378       TLI.getBooleanContents(N0.getValueType()) ==
13379           TargetLowering::ZeroOrOneBooleanContent) {
13380
13381     // If the caller doesn't want us to simplify this into a zext of a compare,
13382     // don't do it.
13383     if (NotExtCompare && N2C->getAPIntValue() == 1)
13384       return SDValue();
13385
13386     // Get a SetCC of the condition
13387     // NOTE: Don't create a SETCC if it's not legal on this target.
13388     if (!LegalOperations ||
13389         TLI.isOperationLegal(ISD::SETCC,
13390           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13391       SDValue Temp, SCC;
13392       // cast from setcc result type to select result type
13393       if (LegalTypes) {
13394         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13395                             N0, N1, CC);
13396         if (N2.getValueType().bitsLT(SCC.getValueType()))
13397           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13398                                         N2.getValueType());
13399         else
13400           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13401                              N2.getValueType(), SCC);
13402       } else {
13403         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13404         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13405                            N2.getValueType(), SCC);
13406       }
13407
13408       AddToWorklist(SCC.getNode());
13409       AddToWorklist(Temp.getNode());
13410
13411       if (N2C->getAPIntValue() == 1)
13412         return Temp;
13413
13414       // shl setcc result by log2 n2c
13415       return DAG.getNode(
13416           ISD::SHL, DL, N2.getValueType(), Temp,
13417           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13418                           getShiftAmountTy(Temp.getValueType())));
13419     }
13420   }
13421
13422   // Check to see if this is the equivalent of setcc
13423   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13424   // otherwise, go ahead with the folds.
13425   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13426     EVT XType = N0.getValueType();
13427     if (!LegalOperations ||
13428         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13429       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13430       if (Res.getValueType() != VT)
13431         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13432       return Res;
13433     }
13434
13435     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13436     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13437         (!LegalOperations ||
13438          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13439       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13440       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13441                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13442                                          SDLoc(Ctlz),
13443                                        getShiftAmountTy(Ctlz.getValueType())));
13444     }
13445     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13446     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13447       SDLoc DL(N0);
13448       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13449                                   XType, DAG.getConstant(0, DL, XType), N0);
13450       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13451       return DAG.getNode(ISD::SRL, DL, XType,
13452                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13453                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13454                                          getShiftAmountTy(XType)));
13455     }
13456     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13457     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13458       SDLoc DL(N0);
13459       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13460                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13461                                          getShiftAmountTy(N0.getValueType())));
13462       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13463                                                                     XType));
13464     }
13465   }
13466
13467   // Check to see if this is an integer abs.
13468   // select_cc setg[te] X,  0,  X, -X ->
13469   // select_cc setgt    X, -1,  X, -X ->
13470   // select_cc setl[te] X,  0, -X,  X ->
13471   // select_cc setlt    X,  1, -X,  X ->
13472   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13473   if (N1C) {
13474     ConstantSDNode *SubC = nullptr;
13475     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13476          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13477         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13478       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13479     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13480               (N1C->isOne() && CC == ISD::SETLT)) &&
13481              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13482       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13483
13484     EVT XType = N0.getValueType();
13485     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13486       SDLoc DL(N0);
13487       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13488                                   N0,
13489                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13490                                          getShiftAmountTy(N0.getValueType())));
13491       SDValue Add = DAG.getNode(ISD::ADD, DL,
13492                                 XType, N0, Shift);
13493       AddToWorklist(Shift.getNode());
13494       AddToWorklist(Add.getNode());
13495       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13496     }
13497   }
13498
13499   return SDValue();
13500 }
13501
13502 /// This is a stub for TargetLowering::SimplifySetCC.
13503 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13504                                    SDValue N1, ISD::CondCode Cond,
13505                                    SDLoc DL, bool foldBooleans) {
13506   TargetLowering::DAGCombinerInfo
13507     DagCombineInfo(DAG, Level, false, this);
13508   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13509 }
13510
13511 /// Given an ISD::SDIV node expressing a divide by constant, return
13512 /// a DAG expression to select that will generate the same value by multiplying
13513 /// by a magic number.
13514 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13515 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13516   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13517   if (!C)
13518     return SDValue();
13519
13520   // Avoid division by zero.
13521   if (!C->getAPIntValue())
13522     return SDValue();
13523
13524   std::vector<SDNode*> Built;
13525   SDValue S =
13526       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13527
13528   for (SDNode *N : Built)
13529     AddToWorklist(N);
13530   return S;
13531 }
13532
13533 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13534 /// DAG expression that will generate the same value by right shifting.
13535 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13536   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13537   if (!C)
13538     return SDValue();
13539
13540   // Avoid division by zero.
13541   if (!C->getAPIntValue())
13542     return SDValue();
13543
13544   std::vector<SDNode *> Built;
13545   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13546
13547   for (SDNode *N : Built)
13548     AddToWorklist(N);
13549   return S;
13550 }
13551
13552 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13553 /// expression that will generate the same value by multiplying by a magic
13554 /// number.
13555 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13556 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13557   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13558   if (!C)
13559     return SDValue();
13560
13561   // Avoid division by zero.
13562   if (!C->getAPIntValue())
13563     return SDValue();
13564
13565   std::vector<SDNode*> Built;
13566   SDValue S =
13567       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13568
13569   for (SDNode *N : Built)
13570     AddToWorklist(N);
13571   return S;
13572 }
13573
13574 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13575   if (Level >= AfterLegalizeDAG)
13576     return SDValue();
13577
13578   // Expose the DAG combiner to the target combiner implementations.
13579   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13580
13581   unsigned Iterations = 0;
13582   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13583     if (Iterations) {
13584       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13585       // For the reciprocal, we need to find the zero of the function:
13586       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13587       //     =>
13588       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13589       //     does not require additional intermediate precision]
13590       EVT VT = Op.getValueType();
13591       SDLoc DL(Op);
13592       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13593
13594       AddToWorklist(Est.getNode());
13595
13596       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13597       for (unsigned i = 0; i < Iterations; ++i) {
13598         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13599         AddToWorklist(NewEst.getNode());
13600
13601         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13602         AddToWorklist(NewEst.getNode());
13603
13604         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13605         AddToWorklist(NewEst.getNode());
13606
13607         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13608         AddToWorklist(Est.getNode());
13609       }
13610     }
13611     return Est;
13612   }
13613
13614   return SDValue();
13615 }
13616
13617 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13618 /// For the reciprocal sqrt, we need to find the zero of the function:
13619 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13620 ///     =>
13621 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13622 /// As a result, we precompute A/2 prior to the iteration loop.
13623 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13624                                           unsigned Iterations) {
13625   EVT VT = Arg.getValueType();
13626   SDLoc DL(Arg);
13627   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13628
13629   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13630   // this entire sequence requires only one FP constant.
13631   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13632   AddToWorklist(HalfArg.getNode());
13633
13634   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13635   AddToWorklist(HalfArg.getNode());
13636
13637   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13638   for (unsigned i = 0; i < Iterations; ++i) {
13639     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13640     AddToWorklist(NewEst.getNode());
13641
13642     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13643     AddToWorklist(NewEst.getNode());
13644
13645     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13646     AddToWorklist(NewEst.getNode());
13647
13648     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13649     AddToWorklist(Est.getNode());
13650   }
13651   return Est;
13652 }
13653
13654 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13655 /// For the reciprocal sqrt, we need to find the zero of the function:
13656 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13657 ///     =>
13658 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13659 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13660                                           unsigned Iterations) {
13661   EVT VT = Arg.getValueType();
13662   SDLoc DL(Arg);
13663   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13664   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13665
13666   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13667   for (unsigned i = 0; i < Iterations; ++i) {
13668     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13669     AddToWorklist(HalfEst.getNode());
13670
13671     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13672     AddToWorklist(Est.getNode());
13673
13674     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13675     AddToWorklist(Est.getNode());
13676
13677     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13678     AddToWorklist(Est.getNode());
13679
13680     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13681     AddToWorklist(Est.getNode());
13682   }
13683   return Est;
13684 }
13685
13686 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13687   if (Level >= AfterLegalizeDAG)
13688     return SDValue();
13689
13690   // Expose the DAG combiner to the target combiner implementations.
13691   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13692   unsigned Iterations = 0;
13693   bool UseOneConstNR = false;
13694   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13695     AddToWorklist(Est.getNode());
13696     if (Iterations) {
13697       Est = UseOneConstNR ?
13698         BuildRsqrtNROneConst(Op, Est, Iterations) :
13699         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13700     }
13701     return Est;
13702   }
13703
13704   return SDValue();
13705 }
13706
13707 /// Return true if base is a frame index, which is known not to alias with
13708 /// anything but itself.  Provides base object and offset as results.
13709 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13710                            const GlobalValue *&GV, const void *&CV) {
13711   // Assume it is a primitive operation.
13712   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13713
13714   // If it's an adding a simple constant then integrate the offset.
13715   if (Base.getOpcode() == ISD::ADD) {
13716     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13717       Base = Base.getOperand(0);
13718       Offset += C->getZExtValue();
13719     }
13720   }
13721
13722   // Return the underlying GlobalValue, and update the Offset.  Return false
13723   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13724   // by multiple nodes with different offsets.
13725   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13726     GV = G->getGlobal();
13727     Offset += G->getOffset();
13728     return false;
13729   }
13730
13731   // Return the underlying Constant value, and update the Offset.  Return false
13732   // for ConstantSDNodes since the same constant pool entry may be represented
13733   // by multiple nodes with different offsets.
13734   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13735     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13736                                          : (const void *)C->getConstVal();
13737     Offset += C->getOffset();
13738     return false;
13739   }
13740   // If it's any of the following then it can't alias with anything but itself.
13741   return isa<FrameIndexSDNode>(Base);
13742 }
13743
13744 /// Return true if there is any possibility that the two addresses overlap.
13745 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13746   // If they are the same then they must be aliases.
13747   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13748
13749   // If they are both volatile then they cannot be reordered.
13750   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13751
13752   // Gather base node and offset information.
13753   SDValue Base1, Base2;
13754   int64_t Offset1, Offset2;
13755   const GlobalValue *GV1, *GV2;
13756   const void *CV1, *CV2;
13757   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13758                                       Base1, Offset1, GV1, CV1);
13759   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13760                                       Base2, Offset2, GV2, CV2);
13761
13762   // If they have a same base address then check to see if they overlap.
13763   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13764     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13765              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13766
13767   // It is possible for different frame indices to alias each other, mostly
13768   // when tail call optimization reuses return address slots for arguments.
13769   // To catch this case, look up the actual index of frame indices to compute
13770   // the real alias relationship.
13771   if (isFrameIndex1 && isFrameIndex2) {
13772     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13773     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13774     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13775     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13776              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13777   }
13778
13779   // Otherwise, if we know what the bases are, and they aren't identical, then
13780   // we know they cannot alias.
13781   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13782     return false;
13783
13784   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13785   // compared to the size and offset of the access, we may be able to prove they
13786   // do not alias.  This check is conservative for now to catch cases created by
13787   // splitting vector types.
13788   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13789       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13790       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13791        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13792       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13793     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13794     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13795
13796     // There is no overlap between these relatively aligned accesses of similar
13797     // size, return no alias.
13798     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13799         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13800       return false;
13801   }
13802
13803   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13804                    ? CombinerGlobalAA
13805                    : DAG.getSubtarget().useAA();
13806 #ifndef NDEBUG
13807   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13808       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13809     UseAA = false;
13810 #endif
13811   if (UseAA &&
13812       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13813     // Use alias analysis information.
13814     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13815                                  Op1->getSrcValueOffset());
13816     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13817         Op0->getSrcValueOffset() - MinOffset;
13818     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13819         Op1->getSrcValueOffset() - MinOffset;
13820     AliasAnalysis::AliasResult AAResult =
13821         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13822                                          Overlap1,
13823                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13824                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13825                                          Overlap2,
13826                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13827     if (AAResult == AliasAnalysis::NoAlias)
13828       return false;
13829   }
13830
13831   // Otherwise we have to assume they alias.
13832   return true;
13833 }
13834
13835 /// Walk up chain skipping non-aliasing memory nodes,
13836 /// looking for aliasing nodes and adding them to the Aliases vector.
13837 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13838                                    SmallVectorImpl<SDValue> &Aliases) {
13839   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13840   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13841
13842   // Get alias information for node.
13843   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13844
13845   // Starting off.
13846   Chains.push_back(OriginalChain);
13847   unsigned Depth = 0;
13848
13849   // Look at each chain and determine if it is an alias.  If so, add it to the
13850   // aliases list.  If not, then continue up the chain looking for the next
13851   // candidate.
13852   while (!Chains.empty()) {
13853     SDValue Chain = Chains.back();
13854     Chains.pop_back();
13855
13856     // For TokenFactor nodes, look at each operand and only continue up the
13857     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13858     // find more and revert to original chain since the xform is unlikely to be
13859     // profitable.
13860     //
13861     // FIXME: The depth check could be made to return the last non-aliasing
13862     // chain we found before we hit a tokenfactor rather than the original
13863     // chain.
13864     if (Depth > 6 || Aliases.size() == 2) {
13865       Aliases.clear();
13866       Aliases.push_back(OriginalChain);
13867       return;
13868     }
13869
13870     // Don't bother if we've been before.
13871     if (!Visited.insert(Chain.getNode()).second)
13872       continue;
13873
13874     switch (Chain.getOpcode()) {
13875     case ISD::EntryToken:
13876       // Entry token is ideal chain operand, but handled in FindBetterChain.
13877       break;
13878
13879     case ISD::LOAD:
13880     case ISD::STORE: {
13881       // Get alias information for Chain.
13882       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13883           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13884
13885       // If chain is alias then stop here.
13886       if (!(IsLoad && IsOpLoad) &&
13887           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13888         Aliases.push_back(Chain);
13889       } else {
13890         // Look further up the chain.
13891         Chains.push_back(Chain.getOperand(0));
13892         ++Depth;
13893       }
13894       break;
13895     }
13896
13897     case ISD::TokenFactor:
13898       // We have to check each of the operands of the token factor for "small"
13899       // token factors, so we queue them up.  Adding the operands to the queue
13900       // (stack) in reverse order maintains the original order and increases the
13901       // likelihood that getNode will find a matching token factor (CSE.)
13902       if (Chain.getNumOperands() > 16) {
13903         Aliases.push_back(Chain);
13904         break;
13905       }
13906       for (unsigned n = Chain.getNumOperands(); n;)
13907         Chains.push_back(Chain.getOperand(--n));
13908       ++Depth;
13909       break;
13910
13911     default:
13912       // For all other instructions we will just have to take what we can get.
13913       Aliases.push_back(Chain);
13914       break;
13915     }
13916   }
13917
13918   // We need to be careful here to also search for aliases through the
13919   // value operand of a store, etc. Consider the following situation:
13920   //   Token1 = ...
13921   //   L1 = load Token1, %52
13922   //   S1 = store Token1, L1, %51
13923   //   L2 = load Token1, %52+8
13924   //   S2 = store Token1, L2, %51+8
13925   //   Token2 = Token(S1, S2)
13926   //   L3 = load Token2, %53
13927   //   S3 = store Token2, L3, %52
13928   //   L4 = load Token2, %53+8
13929   //   S4 = store Token2, L4, %52+8
13930   // If we search for aliases of S3 (which loads address %52), and we look
13931   // only through the chain, then we'll miss the trivial dependence on L1
13932   // (which also loads from %52). We then might change all loads and
13933   // stores to use Token1 as their chain operand, which could result in
13934   // copying %53 into %52 before copying %52 into %51 (which should
13935   // happen first).
13936   //
13937   // The problem is, however, that searching for such data dependencies
13938   // can become expensive, and the cost is not directly related to the
13939   // chain depth. Instead, we'll rule out such configurations here by
13940   // insisting that we've visited all chain users (except for users
13941   // of the original chain, which is not necessary). When doing this,
13942   // we need to look through nodes we don't care about (otherwise, things
13943   // like register copies will interfere with trivial cases).
13944
13945   SmallVector<const SDNode *, 16> Worklist;
13946   for (const SDNode *N : Visited)
13947     if (N != OriginalChain.getNode())
13948       Worklist.push_back(N);
13949
13950   while (!Worklist.empty()) {
13951     const SDNode *M = Worklist.pop_back_val();
13952
13953     // We have already visited M, and want to make sure we've visited any uses
13954     // of M that we care about. For uses that we've not visisted, and don't
13955     // care about, queue them to the worklist.
13956
13957     for (SDNode::use_iterator UI = M->use_begin(),
13958          UIE = M->use_end(); UI != UIE; ++UI)
13959       if (UI.getUse().getValueType() == MVT::Other &&
13960           Visited.insert(*UI).second) {
13961         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13962           // We've not visited this use, and we care about it (it could have an
13963           // ordering dependency with the original node).
13964           Aliases.clear();
13965           Aliases.push_back(OriginalChain);
13966           return;
13967         }
13968
13969         // We've not visited this use, but we don't care about it. Mark it as
13970         // visited and enqueue it to the worklist.
13971         Worklist.push_back(*UI);
13972       }
13973   }
13974 }
13975
13976 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13977 /// (aliasing node.)
13978 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13979   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13980
13981   // Accumulate all the aliases to this node.
13982   GatherAllAliases(N, OldChain, Aliases);
13983
13984   // If no operands then chain to entry token.
13985   if (Aliases.size() == 0)
13986     return DAG.getEntryNode();
13987
13988   // If a single operand then chain to it.  We don't need to revisit it.
13989   if (Aliases.size() == 1)
13990     return Aliases[0];
13991
13992   // Construct a custom tailored token factor.
13993   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13994 }
13995
13996 /// This is the entry point for the file.
13997 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13998                            CodeGenOpt::Level OptLevel) {
13999   /// This is the main entry point to this class.
14000   DAGCombiner(*this, AA, OptLevel).Run(Level);
14001 }