use range-based for loop
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitMGATHER(SDNode *N);
311     SDValue visitMSCATTER(SDNode *N);
312     SDValue visitFP_TO_FP16(SDNode *N);
313
314     SDValue visitFADDForFMACombine(SDNode *N);
315     SDValue visitFSUBForFMACombine(SDNode *N);
316
317     SDValue XformToShuffleWithZero(SDNode *N);
318     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
319
320     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
321
322     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326                              SDValue N3, ISD::CondCode CC,
327                              bool NotExtCompare = false);
328     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329                           SDLoc DL, bool foldBooleans = true);
330
331     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332                            SDValue &CC) const;
333     bool isOneUseSetCC(SDValue N) const;
334
335     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
336                                          unsigned HiOp);
337     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338     SDValue CombineExtLoad(SDNode *N);
339     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340     SDValue BuildSDIV(SDNode *N);
341     SDValue BuildSDIVPow2(SDNode *N);
342     SDValue BuildUDIV(SDNode *N);
343     SDValue BuildReciprocalEstimate(SDValue Op);
344     SDValue BuildRsqrtEstimate(SDValue Op);
345     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348                                bool DemandHighBits = true);
349     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351                               SDValue InnerPos, SDValue InnerNeg,
352                               unsigned PosOpcode, unsigned NegOpcode,
353                               SDLoc DL);
354     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355     SDValue ReduceLoadWidth(SDNode *N);
356     SDValue ReduceLoadOpStoreWidth(SDNode *N);
357     SDValue TransformFPLoadStorePair(SDNode *N);
358     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
360
361     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
362
363     /// Walk up chain skipping non-aliasing memory nodes,
364     /// looking for aliasing nodes and adding them to the Aliases vector.
365     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366                           SmallVectorImpl<SDValue> &Aliases);
367
368     /// Return true if there is any possibility that the two addresses overlap.
369     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
370
371     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372     /// chain (aliasing node.)
373     SDValue FindBetterChain(SDNode *N, SDValue Chain);
374
375     /// Holds a pointer to an LSBaseSDNode as well as information on where it
376     /// is located in a sequence of memory operations connected by a chain.
377     struct MemOpLink {
378       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380       // Ptr to the mem node.
381       LSBaseSDNode *MemNode;
382       // Offset from the base ptr.
383       int64_t OffsetFromBase;
384       // What is the sequence number of this mem node.
385       // Lowest mem operand in the DAG starts at zero.
386       unsigned SequenceNum;
387     };
388
389     /// This is a helper function for MergeConsecutiveStores. When the source
390     /// elements of the consecutive stores are all constants or all extracted
391     /// vector elements, try to merge them into one larger store.
392     /// \return True if a merged store was created.
393     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394                                          EVT MemVT, unsigned NumElem,
395                                          bool IsConstantSrc, bool UseVector);
396
397     /// Merge consecutive store operations into a wide store.
398     /// This optimization uses wide integers or vectors when possible.
399     /// \return True if some memory operations were changed.
400     bool MergeConsecutiveStores(StoreSDNode *N);
401
402     /// \brief Try to transform a truncation where C is a constant:
403     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
404     ///
405     /// \p N needs to be a truncation and its first operand an AND. Other
406     /// requirements are checked by the function (e.g. that trunc is
407     /// single-use) and if missed an empty SDValue is returned.
408     SDValue distributeTruncateThroughAnd(SDNode *N);
409
410   public:
411     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414       auto *F = DAG.getMachineFunction().getFunction();
415       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416                     F->hasFnAttribute(Attribute::MinSize);
417     }
418
419     /// Runs the dag combiner on all nodes in the work list
420     void Run(CombineLevel AtLevel);
421
422     SelectionDAG &getDAG() const { return DAG; }
423
424     /// Returns a type large enough to hold any valid shift amount - before type
425     /// legalization these can be huge.
426     EVT getShiftAmountTy(EVT LHSTy) {
427       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428       if (LHSTy.isVector())
429         return LHSTy;
430       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431                         : TLI.getPointerTy();
432     }
433
434     /// This method returns true if we are running before type legalization or
435     /// if the specified VT is legal.
436     bool isTypeLegal(const EVT &VT) {
437       if (!LegalTypes) return true;
438       return TLI.isTypeLegal(VT);
439     }
440
441     /// Convenience wrapper around TargetLowering::getSetCCResultType
442     EVT getSetCCResultType(EVT VT) const {
443       return TLI.getSetCCResultType(*DAG.getContext(), VT);
444     }
445   };
446 }
447
448
449 namespace {
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453   DAGCombiner &DC;
454 public:
455   explicit WorklistRemover(DAGCombiner &dc)
456     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
457
458   void NodeDeleted(SDNode *N, SDNode *E) override {
459     DC.removeFromWorklist(N);
460   }
461 };
462 }
463
464 //===----------------------------------------------------------------------===//
465 //  TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
467
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469   ((DAGCombiner*)DC)->AddToWorklist(N);
470 }
471
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473   ((DAGCombiner*)DC)->removeFromWorklist(N);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 }
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
484 }
485
486
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 }
491
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 }
496
497 //===----------------------------------------------------------------------===//
498 // Helper Functions
499 //===----------------------------------------------------------------------===//
500
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502   removeFromWorklist(N);
503
504   // If the operands of this node are only used by the node, they will now be
505   // dead. Make sure to re-visit them and recursively delete dead nodes.
506   for (const SDValue &Op : N->ops())
507     // For an operand generating multiple values, one of the values may
508     // become dead allowing further simplification (e.g. split index
509     // arithmetic from an indexed load).
510     if (Op->hasOneUse() || Op->getNumValues() > 1)
511       AddToWorklist(Op.getNode());
512
513   DAG.DeleteNode(N);
514 }
515
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520                                const TargetLowering &TLI,
521                                const TargetOptions *Options,
522                                unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return 2;
525
526   // Don't allow anything with multiple uses.
527   if (!Op.hasOneUse()) return 0;
528
529   // Don't recurse exponentially.
530   if (Depth > 6) return 0;
531
532   switch (Op.getOpcode()) {
533   default: return false;
534   case ISD::ConstantFP:
535     // Don't invert constant FP values after legalize.  The negated constant
536     // isn't necessarily legal.
537     return LegalOperations ? 0 : 1;
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     if (!Options->UnsafeFPMath) return 0;
541
542     // After operation legalization, it might not be legal to create new FSUBs.
543     if (LegalOperations &&
544         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
545       return 0;
546
547     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549                                     Options, Depth + 1))
550       return V;
551     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553                               Depth + 1);
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // fold (fneg (fsub A, B)) -> (fsub B, A)
559     return 1;
560
561   case ISD::FMUL:
562   case ISD::FDIV:
563     if (Options->HonorSignDependentRoundingFPMath()) return 0;
564
565     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572
573   case ISD::FP_EXTEND:
574   case ISD::FP_ROUND:
575   case ISD::FSIN:
576     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
577                               Depth + 1);
578   }
579 }
580
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583                                     bool LegalOperations, unsigned Depth = 0) {
584   const TargetOptions &Options = DAG.getTarget().Options;
585   // fneg is removable even if it has multiple uses.
586   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
587
588   // Don't allow anything with multiple uses.
589   assert(Op.hasOneUse() && "Unknown reuse!");
590
591   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592   switch (Op.getOpcode()) {
593   default: llvm_unreachable("Unknown code");
594   case ISD::ConstantFP: {
595     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596     V.changeSign();
597     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598   }
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     assert(Options.UnsafeFPMath);
602
603     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
606       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                          GetNegatedExpression(Op.getOperand(0), DAG,
608                                               LegalOperations, Depth+1),
609                          Op.getOperand(1));
610     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(1), DAG,
613                                             LegalOperations, Depth+1),
614                        Op.getOperand(0));
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fsub 0, B)) -> B
620     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621       if (N0CFP->getValueAPF().isZero())
622         return Op.getOperand(1);
623
624     // fold (fneg (fsub A, B)) -> (fsub B, A)
625     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626                        Op.getOperand(1), Op.getOperand(0));
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     assert(!Options.HonorSignDependentRoundingFPMath());
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
635       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                          GetNegatedExpression(Op.getOperand(0), DAG,
637                                               LegalOperations, Depth+1),
638                          Op.getOperand(1));
639
640     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(0),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1));
645
646   case ISD::FP_EXTEND:
647   case ISD::FSIN:
648     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649                        GetNegatedExpression(Op.getOperand(0), DAG,
650                                             LegalOperations, Depth+1));
651   case ISD::FP_ROUND:
652       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653                          GetNegatedExpression(Op.getOperand(0), DAG,
654                                               LegalOperations, Depth+1),
655                          Op.getOperand(1));
656   }
657 }
658
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665                                     SDValue &CC) const {
666   if (N.getOpcode() == ISD::SETCC) {
667     LHS = N.getOperand(0);
668     RHS = N.getOperand(1);
669     CC  = N.getOperand(2);
670     return true;
671   }
672
673   if (N.getOpcode() != ISD::SELECT_CC ||
674       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676     return false;
677
678   if (TLI.getBooleanContents(N.getValueType()) ==
679       TargetLowering::UndefinedBooleanContent)
680     return false;
681
682   LHS = N.getOperand(0);
683   RHS = N.getOperand(1);
684   CC  = N.getOperand(4);
685   return true;
686 }
687
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
692   SDValue N0, N1, N2;
693   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
694     return true;
695   return false;
696 }
697
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702   if (!C)
703     return false;
704
705   APInt SplatUndef;
706   unsigned SplatBitSize;
707   bool HasAnyUndefs;
708   EVT EltVT = N->getValueType(0).getVectorElementType();
709   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710                              HasAnyUndefs) &&
711           EltVT.getSizeInBits() >= SplatBitSize);
712 }
713
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717   if (isa<ConstantSDNode>(N))
718     return N.getNode();
719   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720     return N.getNode();
721   return nullptr;
722 }
723
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MGATHER:            return visitMGATHER(N);
1388   case ISD::MLOAD:              return visitMLOAD(N);
1389   case ISD::MSCATTER:           return visitMSCATTER(N);
1390   case ISD::MSTORE:             return visitMSTORE(N);
1391   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397   SDValue RV = visit(N);
1398
1399   // If nothing happened, try a target-specific DAG combine.
1400   if (!RV.getNode()) {
1401     assert(N->getOpcode() != ISD::DELETED_NODE &&
1402            "Node was deleted but visit returned NULL!");
1403
1404     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407       // Expose the DAG combiner to the target combiner impls.
1408       TargetLowering::DAGCombinerInfo
1409         DagCombineInfo(DAG, Level, false, this);
1410
1411       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412     }
1413   }
1414
1415   // If nothing happened still, try promoting the operation.
1416   if (!RV.getNode()) {
1417     switch (N->getOpcode()) {
1418     default: break;
1419     case ISD::ADD:
1420     case ISD::SUB:
1421     case ISD::MUL:
1422     case ISD::AND:
1423     case ISD::OR:
1424     case ISD::XOR:
1425       RV = PromoteIntBinOp(SDValue(N, 0));
1426       break;
1427     case ISD::SHL:
1428     case ISD::SRA:
1429     case ISD::SRL:
1430       RV = PromoteIntShiftOp(SDValue(N, 0));
1431       break;
1432     case ISD::SIGN_EXTEND:
1433     case ISD::ZERO_EXTEND:
1434     case ISD::ANY_EXTEND:
1435       RV = PromoteExtend(SDValue(N, 0));
1436       break;
1437     case ISD::LOAD:
1438       if (PromoteLoad(SDValue(N, 0)))
1439         RV = SDValue(N, 0);
1440       break;
1441     }
1442   }
1443
1444   // If N is a commutative binary node, try commuting it to enable more
1445   // sdisel CSE.
1446   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447       N->getNumValues() == 1) {
1448     SDValue N0 = N->getOperand(0);
1449     SDValue N1 = N->getOperand(1);
1450
1451     // Constant operands are canonicalized to RHS.
1452     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453       SDValue Ops[] = {N1, N0};
1454       SDNode *CSENode;
1455       if (const BinaryWithFlagsSDNode *BinNode =
1456               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458                                       BinNode->Flags.hasNoUnsignedWrap(),
1459                                       BinNode->Flags.hasNoSignedWrap(),
1460                                       BinNode->Flags.hasExact());
1461       } else {
1462         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463       }
1464       if (CSENode)
1465         return SDValue(CSENode, 0);
1466     }
1467   }
1468
1469   return RV;
1470 }
1471
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1473 /// sd operand.
1474 static SDValue getInputChainForNode(SDNode *N) {
1475   if (unsigned NumOps = N->getNumOperands()) {
1476     if (N->getOperand(0).getValueType() == MVT::Other)
1477       return N->getOperand(0);
1478     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479       return N->getOperand(NumOps-1);
1480     for (unsigned i = 1; i < NumOps-1; ++i)
1481       if (N->getOperand(i).getValueType() == MVT::Other)
1482         return N->getOperand(i);
1483   }
1484   return SDValue();
1485 }
1486
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488   // If N has two operands, where one has an input chain equal to the other,
1489   // the 'other' chain is redundant.
1490   if (N->getNumOperands() == 2) {
1491     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492       return N->getOperand(0);
1493     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494       return N->getOperand(1);
1495   }
1496
1497   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1498   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1499   SmallPtrSet<SDNode*, 16> SeenOps;
1500   bool Changed = false;             // If we should replace this token factor.
1501
1502   // Start out with this token factor.
1503   TFs.push_back(N);
1504
1505   // Iterate through token factors.  The TFs grows when new token factors are
1506   // encountered.
1507   for (unsigned i = 0; i < TFs.size(); ++i) {
1508     SDNode *TF = TFs[i];
1509
1510     // Check each of the operands.
1511     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512       SDValue Op = TF->getOperand(i);
1513
1514       switch (Op.getOpcode()) {
1515       case ISD::EntryToken:
1516         // Entry tokens don't need to be added to the list. They are
1517         // redundant.
1518         Changed = true;
1519         break;
1520
1521       case ISD::TokenFactor:
1522         if (Op.hasOneUse() &&
1523             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524           // Queue up for processing.
1525           TFs.push_back(Op.getNode());
1526           // Clean up in case the token factor is removed.
1527           AddToWorklist(Op.getNode());
1528           Changed = true;
1529           break;
1530         }
1531         // Fall thru
1532
1533       default:
1534         // Only add if it isn't already in the list.
1535         if (SeenOps.insert(Op.getNode()).second)
1536           Ops.push_back(Op);
1537         else
1538           Changed = true;
1539         break;
1540       }
1541     }
1542   }
1543
1544   SDValue Result;
1545
1546   // If we've changed things around then replace token factor.
1547   if (Changed) {
1548     if (Ops.empty()) {
1549       // The entry token is the only possible outcome.
1550       Result = DAG.getEntryNode();
1551     } else {
1552       // New and improved token factor.
1553       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1554     }
1555
1556     // Add users to worklist if AA is enabled, since it may introduce
1557     // a lot of new chained token factors while removing memory deps.
1558     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559       : DAG.getSubtarget().useAA();
1560     return CombineTo(N, Result, UseAA /*add to worklist*/);
1561   }
1562
1563   return Result;
1564 }
1565
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568   WorklistRemover DeadNodes(*this);
1569   // Replacing results may cause a different MERGE_VALUES to suddenly
1570   // be CSE'd with N, and carry its uses with it. Iterate until no
1571   // uses remain, to ensure that the node can be safely deleted.
1572   // First add the users of this node to the work list so that they
1573   // can be tried again once they have new operands.
1574   AddUsersToWorklist(N);
1575   do {
1576     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578   } while (!N->use_empty());
1579   deleteAndRecombine(N);
1580   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1581 }
1582
1583 static bool isNullConstant(SDValue V) {
1584   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1585   return Const != nullptr && Const->isNullValue();
1586 }
1587
1588 static bool isAllOnesConstant(SDValue V) {
1589   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1590   return Const != nullptr && Const->isAllOnesValue();
1591 }
1592
1593 static bool isOneConstant(SDValue V) {
1594   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1595   return Const != nullptr && Const->isOne();
1596 }
1597
1598 SDValue DAGCombiner::visitADD(SDNode *N) {
1599   SDValue N0 = N->getOperand(0);
1600   SDValue N1 = N->getOperand(1);
1601   EVT VT = N0.getValueType();
1602
1603   // fold vector ops
1604   if (VT.isVector()) {
1605     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1606       return FoldedVOp;
1607
1608     // fold (add x, 0) -> x, vector edition
1609     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1610       return N0;
1611     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1612       return N1;
1613   }
1614
1615   // fold (add x, undef) -> undef
1616   if (N0.getOpcode() == ISD::UNDEF)
1617     return N0;
1618   if (N1.getOpcode() == ISD::UNDEF)
1619     return N1;
1620   // fold (add c1, c2) -> c1+c2
1621   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1622   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1623   if (N0C && N1C)
1624     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1625   // canonicalize constant to RHS
1626   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1627      !isConstantIntBuildVectorOrConstantInt(N1))
1628     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1629   // fold (add x, 0) -> x
1630   if (isNullConstant(N1))
1631     return N0;
1632   // fold (add Sym, c) -> Sym+c
1633   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1634     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1635         GA->getOpcode() == ISD::GlobalAddress)
1636       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1637                                   GA->getOffset() +
1638                                     (uint64_t)N1C->getSExtValue());
1639   // fold ((c1-A)+c2) -> (c1+c2)-A
1640   if (N1C && N0.getOpcode() == ISD::SUB)
1641     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1642       SDLoc DL(N);
1643       return DAG.getNode(ISD::SUB, DL, VT,
1644                          DAG.getConstant(N1C->getAPIntValue()+
1645                                          N0C->getAPIntValue(), DL, VT),
1646                          N0.getOperand(1));
1647     }
1648   // reassociate add
1649   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1650     return RADD;
1651   // fold ((0-A) + B) -> B-A
1652   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1653     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1654   // fold (A + (0-B)) -> A-B
1655   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1656     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1657   // fold (A+(B-A)) -> B
1658   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1659     return N1.getOperand(0);
1660   // fold ((B-A)+A) -> B
1661   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1662     return N0.getOperand(0);
1663   // fold (A+(B-(A+C))) to (B-C)
1664   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1665       N0 == N1.getOperand(1).getOperand(0))
1666     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1667                        N1.getOperand(1).getOperand(1));
1668   // fold (A+(B-(C+A))) to (B-C)
1669   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1670       N0 == N1.getOperand(1).getOperand(1))
1671     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1672                        N1.getOperand(1).getOperand(0));
1673   // fold (A+((B-A)+or-C)) to (B+or-C)
1674   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1675       N1.getOperand(0).getOpcode() == ISD::SUB &&
1676       N0 == N1.getOperand(0).getOperand(1))
1677     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1678                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1679
1680   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1681   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1682     SDValue N00 = N0.getOperand(0);
1683     SDValue N01 = N0.getOperand(1);
1684     SDValue N10 = N1.getOperand(0);
1685     SDValue N11 = N1.getOperand(1);
1686
1687     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1688       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1689                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1690                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1691   }
1692
1693   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1694     return SDValue(N, 0);
1695
1696   // fold (a+b) -> (a|b) iff a and b share no bits.
1697   if (VT.isInteger() && !VT.isVector()) {
1698     APInt LHSZero, LHSOne;
1699     APInt RHSZero, RHSOne;
1700     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1701
1702     if (LHSZero.getBoolValue()) {
1703       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1704
1705       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1706       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1707       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1708         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1709           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1710       }
1711     }
1712   }
1713
1714   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1715   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1716       isNullConstant(N1.getOperand(0).getOperand(0)))
1717     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1718                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1719                                    N1.getOperand(0).getOperand(1),
1720                                    N1.getOperand(1)));
1721   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1722       isNullConstant(N0.getOperand(0).getOperand(0)))
1723     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1724                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1725                                    N0.getOperand(0).getOperand(1),
1726                                    N0.getOperand(1)));
1727
1728   if (N1.getOpcode() == ISD::AND) {
1729     SDValue AndOp0 = N1.getOperand(0);
1730     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1731     unsigned DestBits = VT.getScalarType().getSizeInBits();
1732
1733     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1734     // and similar xforms where the inner op is either ~0 or 0.
1735     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1736       SDLoc DL(N);
1737       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1738     }
1739   }
1740
1741   // add (sext i1), X -> sub X, (zext i1)
1742   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1743       N0.getOperand(0).getValueType() == MVT::i1 &&
1744       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1745     SDLoc DL(N);
1746     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1747     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1748   }
1749
1750   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1751   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1752     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1753     if (TN->getVT() == MVT::i1) {
1754       SDLoc DL(N);
1755       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1756                                  DAG.getConstant(1, DL, VT));
1757       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1758     }
1759   }
1760
1761   return SDValue();
1762 }
1763
1764 SDValue DAGCombiner::visitADDC(SDNode *N) {
1765   SDValue N0 = N->getOperand(0);
1766   SDValue N1 = N->getOperand(1);
1767   EVT VT = N0.getValueType();
1768
1769   // If the flag result is dead, turn this into an ADD.
1770   if (!N->hasAnyUseOfValue(1))
1771     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1772                      DAG.getNode(ISD::CARRY_FALSE,
1773                                  SDLoc(N), MVT::Glue));
1774
1775   // canonicalize constant to RHS.
1776   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1777   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1778   if (N0C && !N1C)
1779     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1780
1781   // fold (addc x, 0) -> x + no carry out
1782   if (isNullConstant(N1))
1783     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1784                                         SDLoc(N), MVT::Glue));
1785
1786   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1787   APInt LHSZero, LHSOne;
1788   APInt RHSZero, RHSOne;
1789   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1790
1791   if (LHSZero.getBoolValue()) {
1792     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1793
1794     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1795     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1796     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1797       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1798                        DAG.getNode(ISD::CARRY_FALSE,
1799                                    SDLoc(N), MVT::Glue));
1800   }
1801
1802   return SDValue();
1803 }
1804
1805 SDValue DAGCombiner::visitADDE(SDNode *N) {
1806   SDValue N0 = N->getOperand(0);
1807   SDValue N1 = N->getOperand(1);
1808   SDValue CarryIn = N->getOperand(2);
1809
1810   // canonicalize constant to RHS
1811   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1812   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1813   if (N0C && !N1C)
1814     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1815                        N1, N0, CarryIn);
1816
1817   // fold (adde x, y, false) -> (addc x, y)
1818   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1819     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1820
1821   return SDValue();
1822 }
1823
1824 // Since it may not be valid to emit a fold to zero for vector initializers
1825 // check if we can before folding.
1826 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1827                              SelectionDAG &DAG,
1828                              bool LegalOperations, bool LegalTypes) {
1829   if (!VT.isVector())
1830     return DAG.getConstant(0, DL, VT);
1831   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1832     return DAG.getConstant(0, DL, VT);
1833   return SDValue();
1834 }
1835
1836 SDValue DAGCombiner::visitSUB(SDNode *N) {
1837   SDValue N0 = N->getOperand(0);
1838   SDValue N1 = N->getOperand(1);
1839   EVT VT = N0.getValueType();
1840
1841   // fold vector ops
1842   if (VT.isVector()) {
1843     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1844       return FoldedVOp;
1845
1846     // fold (sub x, 0) -> x, vector edition
1847     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1848       return N0;
1849   }
1850
1851   // fold (sub x, x) -> 0
1852   // FIXME: Refactor this and xor and other similar operations together.
1853   if (N0 == N1)
1854     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1855   // fold (sub c1, c2) -> c1-c2
1856   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1857   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1858   if (N0C && N1C)
1859     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1860   // fold (sub x, c) -> (add x, -c)
1861   if (N1C) {
1862     SDLoc DL(N);
1863     return DAG.getNode(ISD::ADD, DL, VT, N0,
1864                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1865   }
1866   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1867   if (isAllOnesConstant(N0))
1868     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1869   // fold A-(A-B) -> B
1870   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1871     return N1.getOperand(1);
1872   // fold (A+B)-A -> B
1873   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1874     return N0.getOperand(1);
1875   // fold (A+B)-B -> A
1876   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1877     return N0.getOperand(0);
1878   // fold C2-(A+C1) -> (C2-C1)-A
1879   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1880     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1881   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1882     SDLoc DL(N);
1883     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1884                                    DL, VT);
1885     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1886                        N1.getOperand(0));
1887   }
1888   // fold ((A+(B+or-C))-B) -> A+or-C
1889   if (N0.getOpcode() == ISD::ADD &&
1890       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1891        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1892       N0.getOperand(1).getOperand(0) == N1)
1893     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1894                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1895   // fold ((A+(C+B))-B) -> A+C
1896   if (N0.getOpcode() == ISD::ADD &&
1897       N0.getOperand(1).getOpcode() == ISD::ADD &&
1898       N0.getOperand(1).getOperand(1) == N1)
1899     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1900                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1901   // fold ((A-(B-C))-C) -> A-B
1902   if (N0.getOpcode() == ISD::SUB &&
1903       N0.getOperand(1).getOpcode() == ISD::SUB &&
1904       N0.getOperand(1).getOperand(1) == N1)
1905     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1907
1908   // If either operand of a sub is undef, the result is undef
1909   if (N0.getOpcode() == ISD::UNDEF)
1910     return N0;
1911   if (N1.getOpcode() == ISD::UNDEF)
1912     return N1;
1913
1914   // If the relocation model supports it, consider symbol offsets.
1915   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1916     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1917       // fold (sub Sym, c) -> Sym-c
1918       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1919         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1920                                     GA->getOffset() -
1921                                       (uint64_t)N1C->getSExtValue());
1922       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1923       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1924         if (GA->getGlobal() == GB->getGlobal())
1925           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1926                                  SDLoc(N), VT);
1927     }
1928
1929   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1930   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1931     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1932     if (TN->getVT() == MVT::i1) {
1933       SDLoc DL(N);
1934       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1935                                  DAG.getConstant(1, DL, VT));
1936       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1937     }
1938   }
1939
1940   return SDValue();
1941 }
1942
1943 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1944   SDValue N0 = N->getOperand(0);
1945   SDValue N1 = N->getOperand(1);
1946   EVT VT = N0.getValueType();
1947
1948   // If the flag result is dead, turn this into an SUB.
1949   if (!N->hasAnyUseOfValue(1))
1950     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1951                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1952                                  MVT::Glue));
1953
1954   // fold (subc x, x) -> 0 + no borrow
1955   if (N0 == N1) {
1956     SDLoc DL(N);
1957     return CombineTo(N, DAG.getConstant(0, DL, VT),
1958                      DAG.getNode(ISD::CARRY_FALSE, DL,
1959                                  MVT::Glue));
1960   }
1961
1962   // fold (subc x, 0) -> x + no borrow
1963   if (isNullConstant(N1))
1964     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1965                                         MVT::Glue));
1966
1967   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1968   if (isAllOnesConstant(N0))
1969     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1970                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1971                                  MVT::Glue));
1972
1973   return SDValue();
1974 }
1975
1976 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1977   SDValue N0 = N->getOperand(0);
1978   SDValue N1 = N->getOperand(1);
1979   SDValue CarryIn = N->getOperand(2);
1980
1981   // fold (sube x, y, false) -> (subc x, y)
1982   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1983     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1984
1985   return SDValue();
1986 }
1987
1988 SDValue DAGCombiner::visitMUL(SDNode *N) {
1989   SDValue N0 = N->getOperand(0);
1990   SDValue N1 = N->getOperand(1);
1991   EVT VT = N0.getValueType();
1992
1993   // fold (mul x, undef) -> 0
1994   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1995     return DAG.getConstant(0, SDLoc(N), VT);
1996
1997   bool N0IsConst = false;
1998   bool N1IsConst = false;
1999   APInt ConstValue0, ConstValue1;
2000   // fold vector ops
2001   if (VT.isVector()) {
2002     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2003       return FoldedVOp;
2004
2005     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2006     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2007   } else {
2008     N0IsConst = isa<ConstantSDNode>(N0);
2009     if (N0IsConst)
2010       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2011     N1IsConst = isa<ConstantSDNode>(N1);
2012     if (N1IsConst)
2013       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2014   }
2015
2016   // fold (mul c1, c2) -> c1*c2
2017   if (N0IsConst && N1IsConst)
2018     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2019                                       N0.getNode(), N1.getNode());
2020
2021   // canonicalize constant to RHS (vector doesn't have to splat)
2022   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2023      !isConstantIntBuildVectorOrConstantInt(N1))
2024     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2025   // fold (mul x, 0) -> 0
2026   if (N1IsConst && ConstValue1 == 0)
2027     return N1;
2028   // We require a splat of the entire scalar bit width for non-contiguous
2029   // bit patterns.
2030   bool IsFullSplat =
2031     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2032   // fold (mul x, 1) -> x
2033   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2034     return N0;
2035   // fold (mul x, -1) -> 0-x
2036   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2037     SDLoc DL(N);
2038     return DAG.getNode(ISD::SUB, DL, VT,
2039                        DAG.getConstant(0, DL, VT), N0);
2040   }
2041   // fold (mul x, (1 << c)) -> x << c
2042   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2043     SDLoc DL(N);
2044     return DAG.getNode(ISD::SHL, DL, VT, N0,
2045                        DAG.getConstant(ConstValue1.logBase2(), DL,
2046                                        getShiftAmountTy(N0.getValueType())));
2047   }
2048   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2049   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2050     unsigned Log2Val = (-ConstValue1).logBase2();
2051     SDLoc DL(N);
2052     // FIXME: If the input is something that is easily negated (e.g. a
2053     // single-use add), we should put the negate there.
2054     return DAG.getNode(ISD::SUB, DL, VT,
2055                        DAG.getConstant(0, DL, VT),
2056                        DAG.getNode(ISD::SHL, DL, VT, N0,
2057                             DAG.getConstant(Log2Val, DL,
2058                                       getShiftAmountTy(N0.getValueType()))));
2059   }
2060
2061   APInt Val;
2062   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2063   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2064       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2065                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2066     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2067                              N1, N0.getOperand(1));
2068     AddToWorklist(C3.getNode());
2069     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2070                        N0.getOperand(0), C3);
2071   }
2072
2073   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2074   // use.
2075   {
2076     SDValue Sh(nullptr,0), Y(nullptr,0);
2077     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2078     if (N0.getOpcode() == ISD::SHL &&
2079         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2080                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2081         N0.getNode()->hasOneUse()) {
2082       Sh = N0; Y = N1;
2083     } else if (N1.getOpcode() == ISD::SHL &&
2084                isa<ConstantSDNode>(N1.getOperand(1)) &&
2085                N1.getNode()->hasOneUse()) {
2086       Sh = N1; Y = N0;
2087     }
2088
2089     if (Sh.getNode()) {
2090       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2091                                 Sh.getOperand(0), Y);
2092       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2093                          Mul, Sh.getOperand(1));
2094     }
2095   }
2096
2097   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2098   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2099       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2100                      isa<ConstantSDNode>(N0.getOperand(1))))
2101     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2102                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2103                                    N0.getOperand(0), N1),
2104                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2105                                    N0.getOperand(1), N1));
2106
2107   // reassociate mul
2108   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2109     return RMUL;
2110
2111   return SDValue();
2112 }
2113
2114 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2115   SDValue N0 = N->getOperand(0);
2116   SDValue N1 = N->getOperand(1);
2117   EVT VT = N->getValueType(0);
2118
2119   // fold vector ops
2120   if (VT.isVector())
2121     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2122       return FoldedVOp;
2123
2124   // fold (sdiv c1, c2) -> c1/c2
2125   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2126   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2127   if (N0C && N1C && !N1C->isNullValue())
2128     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2129   // fold (sdiv X, 1) -> X
2130   if (N1C && N1C->isOne())
2131     return N0;
2132   // fold (sdiv X, -1) -> 0-X
2133   if (N1C && N1C->isAllOnesValue()) {
2134     SDLoc DL(N);
2135     return DAG.getNode(ISD::SUB, DL, VT,
2136                        DAG.getConstant(0, DL, VT), N0);
2137   }
2138   // If we know the sign bits of both operands are zero, strength reduce to a
2139   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2140   if (!VT.isVector()) {
2141     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2142       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2143                          N0, N1);
2144   }
2145
2146   // fold (sdiv X, pow2) -> simple ops after legalize
2147   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2148                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2149     // If dividing by powers of two is cheap, then don't perform the following
2150     // fold.
2151     if (TLI.isPow2SDivCheap())
2152       return SDValue();
2153
2154     // Target-specific implementation of sdiv x, pow2.
2155     SDValue Res = BuildSDIVPow2(N);
2156     if (Res.getNode())
2157       return Res;
2158
2159     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2160     SDLoc DL(N);
2161
2162     // Splat the sign bit into the register
2163     SDValue SGN =
2164         DAG.getNode(ISD::SRA, DL, VT, N0,
2165                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2166                                     getShiftAmountTy(N0.getValueType())));
2167     AddToWorklist(SGN.getNode());
2168
2169     // Add (N0 < 0) ? abs2 - 1 : 0;
2170     SDValue SRL =
2171         DAG.getNode(ISD::SRL, DL, VT, SGN,
2172                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2173                                     getShiftAmountTy(SGN.getValueType())));
2174     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2175     AddToWorklist(SRL.getNode());
2176     AddToWorklist(ADD.getNode());    // Divide by pow2
2177     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2178                   DAG.getConstant(lg2, DL,
2179                                   getShiftAmountTy(ADD.getValueType())));
2180
2181     // If we're dividing by a positive value, we're done.  Otherwise, we must
2182     // negate the result.
2183     if (N1C->getAPIntValue().isNonNegative())
2184       return SRA;
2185
2186     AddToWorklist(SRA.getNode());
2187     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2188   }
2189
2190   // If integer divide is expensive and we satisfy the requirements, emit an
2191   // alternate sequence.
2192   if (N1C && !TLI.isIntDivCheap()) {
2193     SDValue Op = BuildSDIV(N);
2194     if (Op.getNode()) return Op;
2195   }
2196
2197   // undef / X -> 0
2198   if (N0.getOpcode() == ISD::UNDEF)
2199     return DAG.getConstant(0, SDLoc(N), VT);
2200   // X / undef -> undef
2201   if (N1.getOpcode() == ISD::UNDEF)
2202     return N1;
2203
2204   return SDValue();
2205 }
2206
2207 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2208   SDValue N0 = N->getOperand(0);
2209   SDValue N1 = N->getOperand(1);
2210   EVT VT = N->getValueType(0);
2211
2212   // fold vector ops
2213   if (VT.isVector())
2214     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2215       return FoldedVOp;
2216
2217   // fold (udiv c1, c2) -> c1/c2
2218   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2219   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2220   if (N0C && N1C && !N1C->isNullValue())
2221     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2222   // fold (udiv x, (1 << c)) -> x >>u c
2223   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2224     SDLoc DL(N);
2225     return DAG.getNode(ISD::SRL, DL, VT, N0,
2226                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2227                                        getShiftAmountTy(N0.getValueType())));
2228   }
2229   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2230   if (N1.getOpcode() == ISD::SHL) {
2231     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2232       if (SHC->getAPIntValue().isPowerOf2()) {
2233         EVT ADDVT = N1.getOperand(1).getValueType();
2234         SDLoc DL(N);
2235         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2236                                   N1.getOperand(1),
2237                                   DAG.getConstant(SHC->getAPIntValue()
2238                                                                   .logBase2(),
2239                                                   DL, ADDVT));
2240         AddToWorklist(Add.getNode());
2241         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2242       }
2243     }
2244   }
2245   // fold (udiv x, c) -> alternate
2246   if (N1C && !TLI.isIntDivCheap()) {
2247     SDValue Op = BuildUDIV(N);
2248     if (Op.getNode()) return Op;
2249   }
2250
2251   // undef / X -> 0
2252   if (N0.getOpcode() == ISD::UNDEF)
2253     return DAG.getConstant(0, SDLoc(N), VT);
2254   // X / undef -> undef
2255   if (N1.getOpcode() == ISD::UNDEF)
2256     return N1;
2257
2258   return SDValue();
2259 }
2260
2261 SDValue DAGCombiner::visitSREM(SDNode *N) {
2262   SDValue N0 = N->getOperand(0);
2263   SDValue N1 = N->getOperand(1);
2264   EVT VT = N->getValueType(0);
2265
2266   // fold (srem c1, c2) -> c1%c2
2267   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2268   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2269   if (N0C && N1C && !N1C->isNullValue())
2270     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2271   // If we know the sign bits of both operands are zero, strength reduce to a
2272   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2273   if (!VT.isVector()) {
2274     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2275       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2276   }
2277
2278   // If X/C can be simplified by the division-by-constant logic, lower
2279   // X%C to the equivalent of X-X/C*C.
2280   if (N1C && !N1C->isNullValue()) {
2281     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2282     AddToWorklist(Div.getNode());
2283     SDValue OptimizedDiv = combine(Div.getNode());
2284     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2285       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2286                                 OptimizedDiv, N1);
2287       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2288       AddToWorklist(Mul.getNode());
2289       return Sub;
2290     }
2291   }
2292
2293   // undef % X -> 0
2294   if (N0.getOpcode() == ISD::UNDEF)
2295     return DAG.getConstant(0, SDLoc(N), VT);
2296   // X % undef -> undef
2297   if (N1.getOpcode() == ISD::UNDEF)
2298     return N1;
2299
2300   return SDValue();
2301 }
2302
2303 SDValue DAGCombiner::visitUREM(SDNode *N) {
2304   SDValue N0 = N->getOperand(0);
2305   SDValue N1 = N->getOperand(1);
2306   EVT VT = N->getValueType(0);
2307
2308   // fold (urem c1, c2) -> c1%c2
2309   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2310   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2311   if (N0C && N1C && !N1C->isNullValue())
2312     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2313   // fold (urem x, pow2) -> (and x, pow2-1)
2314   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2315     SDLoc DL(N);
2316     return DAG.getNode(ISD::AND, DL, VT, N0,
2317                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2318   }
2319   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2320   if (N1.getOpcode() == ISD::SHL) {
2321     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2322       if (SHC->getAPIntValue().isPowerOf2()) {
2323         SDLoc DL(N);
2324         SDValue Add =
2325           DAG.getNode(ISD::ADD, DL, VT, N1,
2326                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2327                                  VT));
2328         AddToWorklist(Add.getNode());
2329         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2330       }
2331     }
2332   }
2333
2334   // If X/C can be simplified by the division-by-constant logic, lower
2335   // X%C to the equivalent of X-X/C*C.
2336   if (N1C && !N1C->isNullValue()) {
2337     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2338     AddToWorklist(Div.getNode());
2339     SDValue OptimizedDiv = combine(Div.getNode());
2340     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2341       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2342                                 OptimizedDiv, N1);
2343       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2344       AddToWorklist(Mul.getNode());
2345       return Sub;
2346     }
2347   }
2348
2349   // undef % X -> 0
2350   if (N0.getOpcode() == ISD::UNDEF)
2351     return DAG.getConstant(0, SDLoc(N), VT);
2352   // X % undef -> undef
2353   if (N1.getOpcode() == ISD::UNDEF)
2354     return N1;
2355
2356   return SDValue();
2357 }
2358
2359 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2360   SDValue N0 = N->getOperand(0);
2361   SDValue N1 = N->getOperand(1);
2362   EVT VT = N->getValueType(0);
2363   SDLoc DL(N);
2364
2365   // fold (mulhs x, 0) -> 0
2366   if (isNullConstant(N1))
2367     return N1;
2368   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2369   if (isOneConstant(N1)) {
2370     SDLoc DL(N);
2371     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2372                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2373                                        DL,
2374                                        getShiftAmountTy(N0.getValueType())));
2375   }
2376   // fold (mulhs x, undef) -> 0
2377   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2378     return DAG.getConstant(0, SDLoc(N), VT);
2379
2380   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2381   // plus a shift.
2382   if (VT.isSimple() && !VT.isVector()) {
2383     MVT Simple = VT.getSimpleVT();
2384     unsigned SimpleSize = Simple.getSizeInBits();
2385     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2386     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2387       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2388       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2389       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2390       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2391             DAG.getConstant(SimpleSize, DL,
2392                             getShiftAmountTy(N1.getValueType())));
2393       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2394     }
2395   }
2396
2397   return SDValue();
2398 }
2399
2400 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2401   SDValue N0 = N->getOperand(0);
2402   SDValue N1 = N->getOperand(1);
2403   EVT VT = N->getValueType(0);
2404   SDLoc DL(N);
2405
2406   // fold (mulhu x, 0) -> 0
2407   if (isNullConstant(N1))
2408     return N1;
2409   // fold (mulhu x, 1) -> 0
2410   if (isOneConstant(N1))
2411     return DAG.getConstant(0, DL, N0.getValueType());
2412   // fold (mulhu x, undef) -> 0
2413   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2414     return DAG.getConstant(0, DL, VT);
2415
2416   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2417   // plus a shift.
2418   if (VT.isSimple() && !VT.isVector()) {
2419     MVT Simple = VT.getSimpleVT();
2420     unsigned SimpleSize = Simple.getSizeInBits();
2421     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2424       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2425       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2426       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2427             DAG.getConstant(SimpleSize, DL,
2428                             getShiftAmountTy(N1.getValueType())));
2429       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2430     }
2431   }
2432
2433   return SDValue();
2434 }
2435
2436 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2437 /// give the opcodes for the two computations that are being performed. Return
2438 /// true if a simplification was made.
2439 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2440                                                 unsigned HiOp) {
2441   // If the high half is not needed, just compute the low half.
2442   bool HiExists = N->hasAnyUseOfValue(1);
2443   if (!HiExists &&
2444       (!LegalOperations ||
2445        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2446     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2447     return CombineTo(N, Res, Res);
2448   }
2449
2450   // If the low half is not needed, just compute the high half.
2451   bool LoExists = N->hasAnyUseOfValue(0);
2452   if (!LoExists &&
2453       (!LegalOperations ||
2454        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2455     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2456     return CombineTo(N, Res, Res);
2457   }
2458
2459   // If both halves are used, return as it is.
2460   if (LoExists && HiExists)
2461     return SDValue();
2462
2463   // If the two computed results can be simplified separately, separate them.
2464   if (LoExists) {
2465     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2466     AddToWorklist(Lo.getNode());
2467     SDValue LoOpt = combine(Lo.getNode());
2468     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2469         (!LegalOperations ||
2470          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2471       return CombineTo(N, LoOpt, LoOpt);
2472   }
2473
2474   if (HiExists) {
2475     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2476     AddToWorklist(Hi.getNode());
2477     SDValue HiOpt = combine(Hi.getNode());
2478     if (HiOpt.getNode() && HiOpt != Hi &&
2479         (!LegalOperations ||
2480          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2481       return CombineTo(N, HiOpt, HiOpt);
2482   }
2483
2484   return SDValue();
2485 }
2486
2487 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2488   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2489   if (Res.getNode()) return Res;
2490
2491   EVT VT = N->getValueType(0);
2492   SDLoc DL(N);
2493
2494   // If the type is twice as wide is legal, transform the mulhu to a wider
2495   // multiply plus a shift.
2496   if (VT.isSimple() && !VT.isVector()) {
2497     MVT Simple = VT.getSimpleVT();
2498     unsigned SimpleSize = Simple.getSizeInBits();
2499     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2500     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2501       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2502       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2503       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2504       // Compute the high part as N1.
2505       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2506             DAG.getConstant(SimpleSize, DL,
2507                             getShiftAmountTy(Lo.getValueType())));
2508       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2509       // Compute the low part as N0.
2510       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2511       return CombineTo(N, Lo, Hi);
2512     }
2513   }
2514
2515   return SDValue();
2516 }
2517
2518 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2519   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2520   if (Res.getNode()) return Res;
2521
2522   EVT VT = N->getValueType(0);
2523   SDLoc DL(N);
2524
2525   // If the type is twice as wide is legal, transform the mulhu to a wider
2526   // multiply plus a shift.
2527   if (VT.isSimple() && !VT.isVector()) {
2528     MVT Simple = VT.getSimpleVT();
2529     unsigned SimpleSize = Simple.getSizeInBits();
2530     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2531     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2532       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2533       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2534       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2535       // Compute the high part as N1.
2536       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2537             DAG.getConstant(SimpleSize, DL,
2538                             getShiftAmountTy(Lo.getValueType())));
2539       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2540       // Compute the low part as N0.
2541       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2542       return CombineTo(N, Lo, Hi);
2543     }
2544   }
2545
2546   return SDValue();
2547 }
2548
2549 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2550   // (smulo x, 2) -> (saddo x, x)
2551   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2552     if (C2->getAPIntValue() == 2)
2553       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2554                          N->getOperand(0), N->getOperand(0));
2555
2556   return SDValue();
2557 }
2558
2559 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2560   // (umulo x, 2) -> (uaddo x, x)
2561   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2562     if (C2->getAPIntValue() == 2)
2563       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2564                          N->getOperand(0), N->getOperand(0));
2565
2566   return SDValue();
2567 }
2568
2569 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2570   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2571   if (Res.getNode()) return Res;
2572
2573   return SDValue();
2574 }
2575
2576 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2577   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2578   if (Res.getNode()) return Res;
2579
2580   return SDValue();
2581 }
2582
2583 /// If this is a binary operator with two operands of the same opcode, try to
2584 /// simplify it.
2585 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2586   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2587   EVT VT = N0.getValueType();
2588   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2589
2590   // Bail early if none of these transforms apply.
2591   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2592
2593   // For each of OP in AND/OR/XOR:
2594   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2595   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2596   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2597   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2598   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2599   //
2600   // do not sink logical op inside of a vector extend, since it may combine
2601   // into a vsetcc.
2602   EVT Op0VT = N0.getOperand(0).getValueType();
2603   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2604        N0.getOpcode() == ISD::SIGN_EXTEND ||
2605        N0.getOpcode() == ISD::BSWAP ||
2606        // Avoid infinite looping with PromoteIntBinOp.
2607        (N0.getOpcode() == ISD::ANY_EXTEND &&
2608         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2609        (N0.getOpcode() == ISD::TRUNCATE &&
2610         (!TLI.isZExtFree(VT, Op0VT) ||
2611          !TLI.isTruncateFree(Op0VT, VT)) &&
2612         TLI.isTypeLegal(Op0VT))) &&
2613       !VT.isVector() &&
2614       Op0VT == N1.getOperand(0).getValueType() &&
2615       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2616     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2617                                  N0.getOperand(0).getValueType(),
2618                                  N0.getOperand(0), N1.getOperand(0));
2619     AddToWorklist(ORNode.getNode());
2620     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2621   }
2622
2623   // For each of OP in SHL/SRL/SRA/AND...
2624   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2625   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2626   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2627   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2628        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2629       N0.getOperand(1) == N1.getOperand(1)) {
2630     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2631                                  N0.getOperand(0).getValueType(),
2632                                  N0.getOperand(0), N1.getOperand(0));
2633     AddToWorklist(ORNode.getNode());
2634     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2635                        ORNode, N0.getOperand(1));
2636   }
2637
2638   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2639   // Only perform this optimization after type legalization and before
2640   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2641   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2642   // we don't want to undo this promotion.
2643   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2644   // on scalars.
2645   if ((N0.getOpcode() == ISD::BITCAST ||
2646        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2647       Level == AfterLegalizeTypes) {
2648     SDValue In0 = N0.getOperand(0);
2649     SDValue In1 = N1.getOperand(0);
2650     EVT In0Ty = In0.getValueType();
2651     EVT In1Ty = In1.getValueType();
2652     SDLoc DL(N);
2653     // If both incoming values are integers, and the original types are the
2654     // same.
2655     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2656       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2657       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2658       AddToWorklist(Op.getNode());
2659       return BC;
2660     }
2661   }
2662
2663   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2664   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2665   // If both shuffles use the same mask, and both shuffle within a single
2666   // vector, then it is worthwhile to move the swizzle after the operation.
2667   // The type-legalizer generates this pattern when loading illegal
2668   // vector types from memory. In many cases this allows additional shuffle
2669   // optimizations.
2670   // There are other cases where moving the shuffle after the xor/and/or
2671   // is profitable even if shuffles don't perform a swizzle.
2672   // If both shuffles use the same mask, and both shuffles have the same first
2673   // or second operand, then it might still be profitable to move the shuffle
2674   // after the xor/and/or operation.
2675   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2676     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2677     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2678
2679     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2680            "Inputs to shuffles are not the same type");
2681
2682     // Check that both shuffles use the same mask. The masks are known to be of
2683     // the same length because the result vector type is the same.
2684     // Check also that shuffles have only one use to avoid introducing extra
2685     // instructions.
2686     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2687         SVN0->getMask().equals(SVN1->getMask())) {
2688       SDValue ShOp = N0->getOperand(1);
2689
2690       // Don't try to fold this node if it requires introducing a
2691       // build vector of all zeros that might be illegal at this stage.
2692       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2693         if (!LegalTypes)
2694           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2695         else
2696           ShOp = SDValue();
2697       }
2698
2699       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2700       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2701       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2702       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2703         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2704                                       N0->getOperand(0), N1->getOperand(0));
2705         AddToWorklist(NewNode.getNode());
2706         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2707                                     &SVN0->getMask()[0]);
2708       }
2709
2710       // Don't try to fold this node if it requires introducing a
2711       // build vector of all zeros that might be illegal at this stage.
2712       ShOp = N0->getOperand(0);
2713       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2714         if (!LegalTypes)
2715           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2716         else
2717           ShOp = SDValue();
2718       }
2719
2720       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2721       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2722       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2723       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2724         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2725                                       N0->getOperand(1), N1->getOperand(1));
2726         AddToWorklist(NewNode.getNode());
2727         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2728                                     &SVN0->getMask()[0]);
2729       }
2730     }
2731   }
2732
2733   return SDValue();
2734 }
2735
2736 /// This contains all DAGCombine rules which reduce two values combined by
2737 /// an And operation to a single value. This makes them reusable in the context
2738 /// of visitSELECT(). Rules involving constants are not included as
2739 /// visitSELECT() already handles those cases.
2740 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2741                                   SDNode *LocReference) {
2742   EVT VT = N1.getValueType();
2743
2744   // fold (and x, undef) -> 0
2745   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2746     return DAG.getConstant(0, SDLoc(LocReference), VT);
2747   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2748   SDValue LL, LR, RL, RR, CC0, CC1;
2749   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2750     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2751     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2752
2753     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2754         LL.getValueType().isInteger()) {
2755       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2756       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2757         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2758                                      LR.getValueType(), LL, RL);
2759         AddToWorklist(ORNode.getNode());
2760         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2761       }
2762       if (isAllOnesConstant(LR)) {
2763         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2764         if (Op1 == ISD::SETEQ) {
2765           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2766                                         LR.getValueType(), LL, RL);
2767           AddToWorklist(ANDNode.getNode());
2768           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2769         }
2770         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2771         if (Op1 == ISD::SETGT) {
2772           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2773                                        LR.getValueType(), LL, RL);
2774           AddToWorklist(ORNode.getNode());
2775           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2776         }
2777       }
2778     }
2779     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2780     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2781         Op0 == Op1 && LL.getValueType().isInteger() &&
2782       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2783                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2784       SDLoc DL(N0);
2785       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2786                                     LL, DAG.getConstant(1, DL,
2787                                                         LL.getValueType()));
2788       AddToWorklist(ADDNode.getNode());
2789       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2790                           DAG.getConstant(2, DL, LL.getValueType()),
2791                           ISD::SETUGE);
2792     }
2793     // canonicalize equivalent to ll == rl
2794     if (LL == RR && LR == RL) {
2795       Op1 = ISD::getSetCCSwappedOperands(Op1);
2796       std::swap(RL, RR);
2797     }
2798     if (LL == RL && LR == RR) {
2799       bool isInteger = LL.getValueType().isInteger();
2800       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2801       if (Result != ISD::SETCC_INVALID &&
2802           (!LegalOperations ||
2803            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2804             TLI.isOperationLegal(ISD::SETCC,
2805                             getSetCCResultType(N0.getSimpleValueType())))))
2806         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2807                             LL, LR, Result);
2808     }
2809   }
2810
2811   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2812       VT.getSizeInBits() <= 64) {
2813     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2814       APInt ADDC = ADDI->getAPIntValue();
2815       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2816         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2817         // immediate for an add, but it is legal if its top c2 bits are set,
2818         // transform the ADD so the immediate doesn't need to be materialized
2819         // in a register.
2820         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2821           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2822                                              SRLI->getZExtValue());
2823           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2824             ADDC |= Mask;
2825             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2826               SDLoc DL(N0);
2827               SDValue NewAdd =
2828                 DAG.getNode(ISD::ADD, DL, VT,
2829                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2830               CombineTo(N0.getNode(), NewAdd);
2831               // Return N so it doesn't get rechecked!
2832               return SDValue(LocReference, 0);
2833             }
2834           }
2835         }
2836       }
2837     }
2838   }
2839
2840   return SDValue();
2841 }
2842
2843 SDValue DAGCombiner::visitAND(SDNode *N) {
2844   SDValue N0 = N->getOperand(0);
2845   SDValue N1 = N->getOperand(1);
2846   EVT VT = N1.getValueType();
2847
2848   // fold vector ops
2849   if (VT.isVector()) {
2850     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2851       return FoldedVOp;
2852
2853     // fold (and x, 0) -> 0, vector edition
2854     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2855       // do not return N0, because undef node may exist in N0
2856       return DAG.getConstant(
2857           APInt::getNullValue(
2858               N0.getValueType().getScalarType().getSizeInBits()),
2859           SDLoc(N), N0.getValueType());
2860     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2861       // do not return N1, because undef node may exist in N1
2862       return DAG.getConstant(
2863           APInt::getNullValue(
2864               N1.getValueType().getScalarType().getSizeInBits()),
2865           SDLoc(N), N1.getValueType());
2866
2867     // fold (and x, -1) -> x, vector edition
2868     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2869       return N1;
2870     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2871       return N0;
2872   }
2873
2874   // fold (and c1, c2) -> c1&c2
2875   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2876   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2877   if (N0C && N1C)
2878     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2879   // canonicalize constant to RHS
2880   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2881      !isConstantIntBuildVectorOrConstantInt(N1))
2882     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2883   // fold (and x, -1) -> x
2884   if (isAllOnesConstant(N1))
2885     return N0;
2886   // if (and x, c) is known to be zero, return 0
2887   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2888   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2889                                    APInt::getAllOnesValue(BitWidth)))
2890     return DAG.getConstant(0, SDLoc(N), VT);
2891   // reassociate and
2892   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2893     return RAND;
2894   // fold (and (or x, C), D) -> D if (C & D) == D
2895   if (N1C && N0.getOpcode() == ISD::OR)
2896     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2897       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2898         return N1;
2899   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2900   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2901     SDValue N0Op0 = N0.getOperand(0);
2902     APInt Mask = ~N1C->getAPIntValue();
2903     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2904     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2905       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2906                                  N0.getValueType(), N0Op0);
2907
2908       // Replace uses of the AND with uses of the Zero extend node.
2909       CombineTo(N, Zext);
2910
2911       // We actually want to replace all uses of the any_extend with the
2912       // zero_extend, to avoid duplicating things.  This will later cause this
2913       // AND to be folded.
2914       CombineTo(N0.getNode(), Zext);
2915       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2916     }
2917   }
2918   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2919   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2920   // already be zero by virtue of the width of the base type of the load.
2921   //
2922   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2923   // more cases.
2924   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2925        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2926       N0.getOpcode() == ISD::LOAD) {
2927     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2928                                          N0 : N0.getOperand(0) );
2929
2930     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2931     // This can be a pure constant or a vector splat, in which case we treat the
2932     // vector as a scalar and use the splat value.
2933     APInt Constant = APInt::getNullValue(1);
2934     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2935       Constant = C->getAPIntValue();
2936     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2937       APInt SplatValue, SplatUndef;
2938       unsigned SplatBitSize;
2939       bool HasAnyUndefs;
2940       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2941                                              SplatBitSize, HasAnyUndefs);
2942       if (IsSplat) {
2943         // Undef bits can contribute to a possible optimisation if set, so
2944         // set them.
2945         SplatValue |= SplatUndef;
2946
2947         // The splat value may be something like "0x00FFFFFF", which means 0 for
2948         // the first vector value and FF for the rest, repeating. We need a mask
2949         // that will apply equally to all members of the vector, so AND all the
2950         // lanes of the constant together.
2951         EVT VT = Vector->getValueType(0);
2952         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2953
2954         // If the splat value has been compressed to a bitlength lower
2955         // than the size of the vector lane, we need to re-expand it to
2956         // the lane size.
2957         if (BitWidth > SplatBitSize)
2958           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2959                SplatBitSize < BitWidth;
2960                SplatBitSize = SplatBitSize * 2)
2961             SplatValue |= SplatValue.shl(SplatBitSize);
2962
2963         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2964         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2965         if (SplatBitSize % BitWidth == 0) {
2966           Constant = APInt::getAllOnesValue(BitWidth);
2967           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2968             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2969         }
2970       }
2971     }
2972
2973     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2974     // actually legal and isn't going to get expanded, else this is a false
2975     // optimisation.
2976     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2977                                                     Load->getValueType(0),
2978                                                     Load->getMemoryVT());
2979
2980     // Resize the constant to the same size as the original memory access before
2981     // extension. If it is still the AllOnesValue then this AND is completely
2982     // unneeded.
2983     Constant =
2984       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2985
2986     bool B;
2987     switch (Load->getExtensionType()) {
2988     default: B = false; break;
2989     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2990     case ISD::ZEXTLOAD:
2991     case ISD::NON_EXTLOAD: B = true; break;
2992     }
2993
2994     if (B && Constant.isAllOnesValue()) {
2995       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2996       // preserve semantics once we get rid of the AND.
2997       SDValue NewLoad(Load, 0);
2998       if (Load->getExtensionType() == ISD::EXTLOAD) {
2999         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3000                               Load->getValueType(0), SDLoc(Load),
3001                               Load->getChain(), Load->getBasePtr(),
3002                               Load->getOffset(), Load->getMemoryVT(),
3003                               Load->getMemOperand());
3004         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3005         if (Load->getNumValues() == 3) {
3006           // PRE/POST_INC loads have 3 values.
3007           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3008                            NewLoad.getValue(2) };
3009           CombineTo(Load, To, 3, true);
3010         } else {
3011           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3012         }
3013       }
3014
3015       // Fold the AND away, taking care not to fold to the old load node if we
3016       // replaced it.
3017       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3018
3019       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3020     }
3021   }
3022
3023   // fold (and (load x), 255) -> (zextload x, i8)
3024   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3025   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3026   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3027               (N0.getOpcode() == ISD::ANY_EXTEND &&
3028                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3029     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3030     LoadSDNode *LN0 = HasAnyExt
3031       ? cast<LoadSDNode>(N0.getOperand(0))
3032       : cast<LoadSDNode>(N0);
3033     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3034         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3035       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3036       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3037         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3038         EVT LoadedVT = LN0->getMemoryVT();
3039         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3040
3041         if (ExtVT == LoadedVT &&
3042             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3043                                                     ExtVT))) {
3044
3045           SDValue NewLoad =
3046             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3047                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3048                            LN0->getMemOperand());
3049           AddToWorklist(N);
3050           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3051           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3052         }
3053
3054         // Do not change the width of a volatile load.
3055         // Do not generate loads of non-round integer types since these can
3056         // be expensive (and would be wrong if the type is not byte sized).
3057         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3058             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3059                                                     ExtVT))) {
3060           EVT PtrType = LN0->getOperand(1).getValueType();
3061
3062           unsigned Alignment = LN0->getAlignment();
3063           SDValue NewPtr = LN0->getBasePtr();
3064
3065           // For big endian targets, we need to add an offset to the pointer
3066           // to load the correct bytes.  For little endian systems, we merely
3067           // need to read fewer bytes from the same pointer.
3068           if (TLI.isBigEndian()) {
3069             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3070             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3071             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3072             SDLoc DL(LN0);
3073             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3074                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3075             Alignment = MinAlign(Alignment, PtrOff);
3076           }
3077
3078           AddToWorklist(NewPtr.getNode());
3079
3080           SDValue Load =
3081             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3082                            LN0->getChain(), NewPtr,
3083                            LN0->getPointerInfo(),
3084                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3085                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3086           AddToWorklist(N);
3087           CombineTo(LN0, Load, Load.getValue(1));
3088           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3089         }
3090       }
3091     }
3092   }
3093
3094   if (SDValue Combined = visitANDLike(N0, N1, N))
3095     return Combined;
3096
3097   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3098   if (N0.getOpcode() == N1.getOpcode()) {
3099     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3100     if (Tmp.getNode()) return Tmp;
3101   }
3102
3103   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3104   // fold (and (sra)) -> (and (srl)) when possible.
3105   if (!VT.isVector() &&
3106       SimplifyDemandedBits(SDValue(N, 0)))
3107     return SDValue(N, 0);
3108
3109   // fold (zext_inreg (extload x)) -> (zextload x)
3110   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3111     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3112     EVT MemVT = LN0->getMemoryVT();
3113     // If we zero all the possible extended bits, then we can turn this into
3114     // a zextload if we are running before legalize or the operation is legal.
3115     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3116     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3117                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3118         ((!LegalOperations && !LN0->isVolatile()) ||
3119          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3120       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3121                                        LN0->getChain(), LN0->getBasePtr(),
3122                                        MemVT, LN0->getMemOperand());
3123       AddToWorklist(N);
3124       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3125       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3126     }
3127   }
3128   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3129   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3130       N0.hasOneUse()) {
3131     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3132     EVT MemVT = LN0->getMemoryVT();
3133     // If we zero all the possible extended bits, then we can turn this into
3134     // a zextload if we are running before legalize or the operation is legal.
3135     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3136     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3137                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3138         ((!LegalOperations && !LN0->isVolatile()) ||
3139          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3140       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3141                                        LN0->getChain(), LN0->getBasePtr(),
3142                                        MemVT, LN0->getMemOperand());
3143       AddToWorklist(N);
3144       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3145       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3146     }
3147   }
3148   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3149   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3150     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3151                                        N0.getOperand(1), false);
3152     if (BSwap.getNode())
3153       return BSwap;
3154   }
3155
3156   return SDValue();
3157 }
3158
3159 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3160 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3161                                         bool DemandHighBits) {
3162   if (!LegalOperations)
3163     return SDValue();
3164
3165   EVT VT = N->getValueType(0);
3166   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3167     return SDValue();
3168   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3169     return SDValue();
3170
3171   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3172   bool LookPassAnd0 = false;
3173   bool LookPassAnd1 = false;
3174   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3175       std::swap(N0, N1);
3176   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3177       std::swap(N0, N1);
3178   if (N0.getOpcode() == ISD::AND) {
3179     if (!N0.getNode()->hasOneUse())
3180       return SDValue();
3181     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3182     if (!N01C || N01C->getZExtValue() != 0xFF00)
3183       return SDValue();
3184     N0 = N0.getOperand(0);
3185     LookPassAnd0 = true;
3186   }
3187
3188   if (N1.getOpcode() == ISD::AND) {
3189     if (!N1.getNode()->hasOneUse())
3190       return SDValue();
3191     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3192     if (!N11C || N11C->getZExtValue() != 0xFF)
3193       return SDValue();
3194     N1 = N1.getOperand(0);
3195     LookPassAnd1 = true;
3196   }
3197
3198   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3199     std::swap(N0, N1);
3200   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3201     return SDValue();
3202   if (!N0.getNode()->hasOneUse() ||
3203       !N1.getNode()->hasOneUse())
3204     return SDValue();
3205
3206   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3208   if (!N01C || !N11C)
3209     return SDValue();
3210   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3211     return SDValue();
3212
3213   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3214   SDValue N00 = N0->getOperand(0);
3215   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3216     if (!N00.getNode()->hasOneUse())
3217       return SDValue();
3218     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3219     if (!N001C || N001C->getZExtValue() != 0xFF)
3220       return SDValue();
3221     N00 = N00.getOperand(0);
3222     LookPassAnd0 = true;
3223   }
3224
3225   SDValue N10 = N1->getOperand(0);
3226   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3227     if (!N10.getNode()->hasOneUse())
3228       return SDValue();
3229     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3230     if (!N101C || N101C->getZExtValue() != 0xFF00)
3231       return SDValue();
3232     N10 = N10.getOperand(0);
3233     LookPassAnd1 = true;
3234   }
3235
3236   if (N00 != N10)
3237     return SDValue();
3238
3239   // Make sure everything beyond the low halfword gets set to zero since the SRL
3240   // 16 will clear the top bits.
3241   unsigned OpSizeInBits = VT.getSizeInBits();
3242   if (DemandHighBits && OpSizeInBits > 16) {
3243     // If the left-shift isn't masked out then the only way this is a bswap is
3244     // if all bits beyond the low 8 are 0. In that case the entire pattern
3245     // reduces to a left shift anyway: leave it for other parts of the combiner.
3246     if (!LookPassAnd0)
3247       return SDValue();
3248
3249     // However, if the right shift isn't masked out then it might be because
3250     // it's not needed. See if we can spot that too.
3251     if (!LookPassAnd1 &&
3252         !DAG.MaskedValueIsZero(
3253             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3254       return SDValue();
3255   }
3256
3257   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3258   if (OpSizeInBits > 16) {
3259     SDLoc DL(N);
3260     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3261                       DAG.getConstant(OpSizeInBits - 16, DL,
3262                                       getShiftAmountTy(VT)));
3263   }
3264   return Res;
3265 }
3266
3267 /// Return true if the specified node is an element that makes up a 32-bit
3268 /// packed halfword byteswap.
3269 /// ((x & 0x000000ff) << 8) |
3270 /// ((x & 0x0000ff00) >> 8) |
3271 /// ((x & 0x00ff0000) << 8) |
3272 /// ((x & 0xff000000) >> 8)
3273 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3274   if (!N.getNode()->hasOneUse())
3275     return false;
3276
3277   unsigned Opc = N.getOpcode();
3278   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3279     return false;
3280
3281   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3282   if (!N1C)
3283     return false;
3284
3285   unsigned Num;
3286   switch (N1C->getZExtValue()) {
3287   default:
3288     return false;
3289   case 0xFF:       Num = 0; break;
3290   case 0xFF00:     Num = 1; break;
3291   case 0xFF0000:   Num = 2; break;
3292   case 0xFF000000: Num = 3; break;
3293   }
3294
3295   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3296   SDValue N0 = N.getOperand(0);
3297   if (Opc == ISD::AND) {
3298     if (Num == 0 || Num == 2) {
3299       // (x >> 8) & 0xff
3300       // (x >> 8) & 0xff0000
3301       if (N0.getOpcode() != ISD::SRL)
3302         return false;
3303       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3304       if (!C || C->getZExtValue() != 8)
3305         return false;
3306     } else {
3307       // (x << 8) & 0xff00
3308       // (x << 8) & 0xff000000
3309       if (N0.getOpcode() != ISD::SHL)
3310         return false;
3311       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3312       if (!C || C->getZExtValue() != 8)
3313         return false;
3314     }
3315   } else if (Opc == ISD::SHL) {
3316     // (x & 0xff) << 8
3317     // (x & 0xff0000) << 8
3318     if (Num != 0 && Num != 2)
3319       return false;
3320     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3321     if (!C || C->getZExtValue() != 8)
3322       return false;
3323   } else { // Opc == ISD::SRL
3324     // (x & 0xff00) >> 8
3325     // (x & 0xff000000) >> 8
3326     if (Num != 1 && Num != 3)
3327       return false;
3328     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3329     if (!C || C->getZExtValue() != 8)
3330       return false;
3331   }
3332
3333   if (Parts[Num])
3334     return false;
3335
3336   Parts[Num] = N0.getOperand(0).getNode();
3337   return true;
3338 }
3339
3340 /// Match a 32-bit packed halfword bswap. That is
3341 /// ((x & 0x000000ff) << 8) |
3342 /// ((x & 0x0000ff00) >> 8) |
3343 /// ((x & 0x00ff0000) << 8) |
3344 /// ((x & 0xff000000) >> 8)
3345 /// => (rotl (bswap x), 16)
3346 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3347   if (!LegalOperations)
3348     return SDValue();
3349
3350   EVT VT = N->getValueType(0);
3351   if (VT != MVT::i32)
3352     return SDValue();
3353   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3354     return SDValue();
3355
3356   // Look for either
3357   // (or (or (and), (and)), (or (and), (and)))
3358   // (or (or (or (and), (and)), (and)), (and))
3359   if (N0.getOpcode() != ISD::OR)
3360     return SDValue();
3361   SDValue N00 = N0.getOperand(0);
3362   SDValue N01 = N0.getOperand(1);
3363   SDNode *Parts[4] = {};
3364
3365   if (N1.getOpcode() == ISD::OR &&
3366       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3367     // (or (or (and), (and)), (or (and), (and)))
3368     SDValue N000 = N00.getOperand(0);
3369     if (!isBSwapHWordElement(N000, Parts))
3370       return SDValue();
3371
3372     SDValue N001 = N00.getOperand(1);
3373     if (!isBSwapHWordElement(N001, Parts))
3374       return SDValue();
3375     SDValue N010 = N01.getOperand(0);
3376     if (!isBSwapHWordElement(N010, Parts))
3377       return SDValue();
3378     SDValue N011 = N01.getOperand(1);
3379     if (!isBSwapHWordElement(N011, Parts))
3380       return SDValue();
3381   } else {
3382     // (or (or (or (and), (and)), (and)), (and))
3383     if (!isBSwapHWordElement(N1, Parts))
3384       return SDValue();
3385     if (!isBSwapHWordElement(N01, Parts))
3386       return SDValue();
3387     if (N00.getOpcode() != ISD::OR)
3388       return SDValue();
3389     SDValue N000 = N00.getOperand(0);
3390     if (!isBSwapHWordElement(N000, Parts))
3391       return SDValue();
3392     SDValue N001 = N00.getOperand(1);
3393     if (!isBSwapHWordElement(N001, Parts))
3394       return SDValue();
3395   }
3396
3397   // Make sure the parts are all coming from the same node.
3398   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3399     return SDValue();
3400
3401   SDLoc DL(N);
3402   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3403                               SDValue(Parts[0], 0));
3404
3405   // Result of the bswap should be rotated by 16. If it's not legal, then
3406   // do  (x << 16) | (x >> 16).
3407   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3408   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3409     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3410   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3411     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3412   return DAG.getNode(ISD::OR, DL, VT,
3413                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3414                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3415 }
3416
3417 /// This contains all DAGCombine rules which reduce two values combined by
3418 /// an Or operation to a single value \see visitANDLike().
3419 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3420   EVT VT = N1.getValueType();
3421   // fold (or x, undef) -> -1
3422   if (!LegalOperations &&
3423       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3424     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3425     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3426                            SDLoc(LocReference), VT);
3427   }
3428   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3429   SDValue LL, LR, RL, RR, CC0, CC1;
3430   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3431     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3432     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3433
3434     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3435       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3436       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3437       if (isNullConstant(LR) && (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 (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3446         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3447                                       LR.getValueType(), LL, RL);
3448         AddToWorklist(ANDNode.getNode());
3449         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3450       }
3451     }
3452     // canonicalize equivalent to ll == rl
3453     if (LL == RR && LR == RL) {
3454       Op1 = ISD::getSetCCSwappedOperands(Op1);
3455       std::swap(RL, RR);
3456     }
3457     if (LL == RL && LR == RR) {
3458       bool isInteger = LL.getValueType().isInteger();
3459       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3460       if (Result != ISD::SETCC_INVALID &&
3461           (!LegalOperations ||
3462            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3463             TLI.isOperationLegal(ISD::SETCC,
3464               getSetCCResultType(N0.getValueType())))))
3465         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3466                             LL, LR, Result);
3467     }
3468   }
3469
3470   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3471   if (N0.getOpcode() == ISD::AND &&
3472       N1.getOpcode() == ISD::AND &&
3473       N0.getOperand(1).getOpcode() == ISD::Constant &&
3474       N1.getOperand(1).getOpcode() == ISD::Constant &&
3475       // Don't increase # computations.
3476       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3477     // We can only do this xform if we know that bits from X that are set in C2
3478     // but not in C1 are already zero.  Likewise for Y.
3479     const APInt &LHSMask =
3480       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3481     const APInt &RHSMask =
3482       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3483
3484     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3485         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3486       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3487                               N0.getOperand(0), N1.getOperand(0));
3488       SDLoc DL(LocReference);
3489       return DAG.getNode(ISD::AND, DL, VT, X,
3490                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3491     }
3492   }
3493
3494   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3495   if (N0.getOpcode() == ISD::AND &&
3496       N1.getOpcode() == ISD::AND &&
3497       N0.getOperand(0) == N1.getOperand(0) &&
3498       // Don't increase # computations.
3499       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3500     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3501                             N0.getOperand(1), N1.getOperand(1));
3502     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3503   }
3504
3505   return SDValue();
3506 }
3507
3508 SDValue DAGCombiner::visitOR(SDNode *N) {
3509   SDValue N0 = N->getOperand(0);
3510   SDValue N1 = N->getOperand(1);
3511   EVT VT = N1.getValueType();
3512
3513   // fold vector ops
3514   if (VT.isVector()) {
3515     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3516       return FoldedVOp;
3517
3518     // fold (or x, 0) -> x, vector edition
3519     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3520       return N1;
3521     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3522       return N0;
3523
3524     // fold (or x, -1) -> -1, vector edition
3525     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3526       // do not return N0, because undef node may exist in N0
3527       return DAG.getConstant(
3528           APInt::getAllOnesValue(
3529               N0.getValueType().getScalarType().getSizeInBits()),
3530           SDLoc(N), N0.getValueType());
3531     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3532       // do not return N1, because undef node may exist in N1
3533       return DAG.getConstant(
3534           APInt::getAllOnesValue(
3535               N1.getValueType().getScalarType().getSizeInBits()),
3536           SDLoc(N), N1.getValueType());
3537
3538     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3539     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3540     // Do this only if the resulting shuffle is legal.
3541     if (isa<ShuffleVectorSDNode>(N0) &&
3542         isa<ShuffleVectorSDNode>(N1) &&
3543         // Avoid folding a node with illegal type.
3544         TLI.isTypeLegal(VT) &&
3545         N0->getOperand(1) == N1->getOperand(1) &&
3546         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3547       bool CanFold = true;
3548       unsigned NumElts = VT.getVectorNumElements();
3549       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3550       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3551       // We construct two shuffle masks:
3552       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3553       // and N1 as the second operand.
3554       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3555       // and N0 as the second operand.
3556       // We do this because OR is commutable and therefore there might be
3557       // two ways to fold this node into a shuffle.
3558       SmallVector<int,4> Mask1;
3559       SmallVector<int,4> Mask2;
3560
3561       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3562         int M0 = SV0->getMaskElt(i);
3563         int M1 = SV1->getMaskElt(i);
3564
3565         // Both shuffle indexes are undef. Propagate Undef.
3566         if (M0 < 0 && M1 < 0) {
3567           Mask1.push_back(M0);
3568           Mask2.push_back(M0);
3569           continue;
3570         }
3571
3572         if (M0 < 0 || M1 < 0 ||
3573             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3574             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3575           CanFold = false;
3576           break;
3577         }
3578
3579         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3580         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3581       }
3582
3583       if (CanFold) {
3584         // Fold this sequence only if the resulting shuffle is 'legal'.
3585         if (TLI.isShuffleMaskLegal(Mask1, VT))
3586           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3587                                       N1->getOperand(0), &Mask1[0]);
3588         if (TLI.isShuffleMaskLegal(Mask2, VT))
3589           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3590                                       N0->getOperand(0), &Mask2[0]);
3591       }
3592     }
3593   }
3594
3595   // fold (or c1, c2) -> c1|c2
3596   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3597   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3598   if (N0C && N1C)
3599     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3600   // canonicalize constant to RHS
3601   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3602      !isConstantIntBuildVectorOrConstantInt(N1))
3603     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3604   // fold (or x, 0) -> x
3605   if (isNullConstant(N1))
3606     return N0;
3607   // fold (or x, -1) -> -1
3608   if (isAllOnesConstant(N1))
3609     return N1;
3610   // fold (or x, c) -> c iff (x & ~c) == 0
3611   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3612     return N1;
3613
3614   if (SDValue Combined = visitORLike(N0, N1, N))
3615     return Combined;
3616
3617   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3618   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3619   if (BSwap.getNode())
3620     return BSwap;
3621   BSwap = MatchBSwapHWordLow(N, N0, N1);
3622   if (BSwap.getNode())
3623     return BSwap;
3624
3625   // reassociate or
3626   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3627     return ROR;
3628   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3629   // iff (c1 & c2) == 0.
3630   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3631              isa<ConstantSDNode>(N0.getOperand(1))) {
3632     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3633     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3634       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3635                                                    N1C, C1))
3636         return DAG.getNode(
3637             ISD::AND, SDLoc(N), VT,
3638             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3639       return SDValue();
3640     }
3641   }
3642   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3643   if (N0.getOpcode() == N1.getOpcode()) {
3644     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3645     if (Tmp.getNode()) return Tmp;
3646   }
3647
3648   // See if this is some rotate idiom.
3649   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3650     return SDValue(Rot, 0);
3651
3652   // Simplify the operands using demanded-bits information.
3653   if (!VT.isVector() &&
3654       SimplifyDemandedBits(SDValue(N, 0)))
3655     return SDValue(N, 0);
3656
3657   return SDValue();
3658 }
3659
3660 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3661 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3662   if (Op.getOpcode() == ISD::AND) {
3663     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3664       Mask = Op.getOperand(1);
3665       Op = Op.getOperand(0);
3666     } else {
3667       return false;
3668     }
3669   }
3670
3671   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3672     Shift = Op;
3673     return true;
3674   }
3675
3676   return false;
3677 }
3678
3679 // Return true if we can prove that, whenever Neg and Pos are both in the
3680 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3681 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3682 //
3683 //     (or (shift1 X, Neg), (shift2 X, Pos))
3684 //
3685 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3686 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3687 // to consider shift amounts with defined behavior.
3688 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3689   // If OpSize is a power of 2 then:
3690   //
3691   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3692   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3693   //
3694   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3695   // for the stronger condition:
3696   //
3697   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3698   //
3699   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3700   // we can just replace Neg with Neg' for the rest of the function.
3701   //
3702   // In other cases we check for the even stronger condition:
3703   //
3704   //     Neg == OpSize - Pos                                    [B]
3705   //
3706   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3707   // behavior if Pos == 0 (and consequently Neg == OpSize).
3708   //
3709   // We could actually use [A] whenever OpSize is a power of 2, but the
3710   // only extra cases that it would match are those uninteresting ones
3711   // where Neg and Pos are never in range at the same time.  E.g. for
3712   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3713   // as well as (sub 32, Pos), but:
3714   //
3715   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3716   //
3717   // always invokes undefined behavior for 32-bit X.
3718   //
3719   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3720   unsigned MaskLoBits = 0;
3721   if (Neg.getOpcode() == ISD::AND &&
3722       isPowerOf2_64(OpSize) &&
3723       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3724       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3725     Neg = Neg.getOperand(0);
3726     MaskLoBits = Log2_64(OpSize);
3727   }
3728
3729   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3730   if (Neg.getOpcode() != ISD::SUB)
3731     return 0;
3732   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3733   if (!NegC)
3734     return 0;
3735   SDValue NegOp1 = Neg.getOperand(1);
3736
3737   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3738   // Pos'.  The truncation is redundant for the purpose of the equality.
3739   if (MaskLoBits &&
3740       Pos.getOpcode() == ISD::AND &&
3741       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3742       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3743     Pos = Pos.getOperand(0);
3744
3745   // The condition we need is now:
3746   //
3747   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3748   //
3749   // If NegOp1 == Pos then we need:
3750   //
3751   //              OpSize & Mask == NegC & Mask
3752   //
3753   // (because "x & Mask" is a truncation and distributes through subtraction).
3754   APInt Width;
3755   if (Pos == NegOp1)
3756     Width = NegC->getAPIntValue();
3757   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3758   // Then the condition we want to prove becomes:
3759   //
3760   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3761   //
3762   // which, again because "x & Mask" is a truncation, becomes:
3763   //
3764   //                NegC & Mask == (OpSize - PosC) & Mask
3765   //              OpSize & Mask == (NegC + PosC) & Mask
3766   else if (Pos.getOpcode() == ISD::ADD &&
3767            Pos.getOperand(0) == NegOp1 &&
3768            Pos.getOperand(1).getOpcode() == ISD::Constant)
3769     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3770              NegC->getAPIntValue());
3771   else
3772     return false;
3773
3774   // Now we just need to check that OpSize & Mask == Width & Mask.
3775   if (MaskLoBits)
3776     // Opsize & Mask is 0 since Mask is Opsize - 1.
3777     return Width.getLoBits(MaskLoBits) == 0;
3778   return Width == OpSize;
3779 }
3780
3781 // A subroutine of MatchRotate used once we have found an OR of two opposite
3782 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3783 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3784 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3785 // Neg with outer conversions stripped away.
3786 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3787                                        SDValue Neg, SDValue InnerPos,
3788                                        SDValue InnerNeg, unsigned PosOpcode,
3789                                        unsigned NegOpcode, SDLoc DL) {
3790   // fold (or (shl x, (*ext y)),
3791   //          (srl x, (*ext (sub 32, y)))) ->
3792   //   (rotl x, y) or (rotr x, (sub 32, y))
3793   //
3794   // fold (or (shl x, (*ext (sub 32, y))),
3795   //          (srl x, (*ext y))) ->
3796   //   (rotr x, y) or (rotl x, (sub 32, y))
3797   EVT VT = Shifted.getValueType();
3798   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3799     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3800     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3801                        HasPos ? Pos : Neg).getNode();
3802   }
3803
3804   return nullptr;
3805 }
3806
3807 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3808 // idioms for rotate, and if the target supports rotation instructions, generate
3809 // a rot[lr].
3810 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3811   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3812   EVT VT = LHS.getValueType();
3813   if (!TLI.isTypeLegal(VT)) return nullptr;
3814
3815   // The target must have at least one rotate flavor.
3816   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3817   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3818   if (!HasROTL && !HasROTR) return nullptr;
3819
3820   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3821   SDValue LHSShift;   // The shift.
3822   SDValue LHSMask;    // AND value if any.
3823   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3824     return nullptr; // Not part of a rotate.
3825
3826   SDValue RHSShift;   // The shift.
3827   SDValue RHSMask;    // AND value if any.
3828   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3829     return nullptr; // Not part of a rotate.
3830
3831   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3832     return nullptr;   // Not shifting the same value.
3833
3834   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3835     return nullptr;   // Shifts must disagree.
3836
3837   // Canonicalize shl to left side in a shl/srl pair.
3838   if (RHSShift.getOpcode() == ISD::SHL) {
3839     std::swap(LHS, RHS);
3840     std::swap(LHSShift, RHSShift);
3841     std::swap(LHSMask , RHSMask );
3842   }
3843
3844   unsigned OpSizeInBits = VT.getSizeInBits();
3845   SDValue LHSShiftArg = LHSShift.getOperand(0);
3846   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3847   SDValue RHSShiftArg = RHSShift.getOperand(0);
3848   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3849
3850   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3851   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3852   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3853       RHSShiftAmt.getOpcode() == ISD::Constant) {
3854     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3855     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3856     if ((LShVal + RShVal) != OpSizeInBits)
3857       return nullptr;
3858
3859     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3860                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3861
3862     // If there is an AND of either shifted operand, apply it to the result.
3863     if (LHSMask.getNode() || RHSMask.getNode()) {
3864       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3865
3866       if (LHSMask.getNode()) {
3867         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3868         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3869       }
3870       if (RHSMask.getNode()) {
3871         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3872         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3873       }
3874
3875       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3876     }
3877
3878     return Rot.getNode();
3879   }
3880
3881   // If there is a mask here, and we have a variable shift, we can't be sure
3882   // that we're masking out the right stuff.
3883   if (LHSMask.getNode() || RHSMask.getNode())
3884     return nullptr;
3885
3886   // If the shift amount is sign/zext/any-extended just peel it off.
3887   SDValue LExtOp0 = LHSShiftAmt;
3888   SDValue RExtOp0 = RHSShiftAmt;
3889   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3890        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3891        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3892        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3893       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3894        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3895        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3896        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3897     LExtOp0 = LHSShiftAmt.getOperand(0);
3898     RExtOp0 = RHSShiftAmt.getOperand(0);
3899   }
3900
3901   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3902                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3903   if (TryL)
3904     return TryL;
3905
3906   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3907                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3908   if (TryR)
3909     return TryR;
3910
3911   return nullptr;
3912 }
3913
3914 SDValue DAGCombiner::visitXOR(SDNode *N) {
3915   SDValue N0 = N->getOperand(0);
3916   SDValue N1 = N->getOperand(1);
3917   EVT VT = N0.getValueType();
3918
3919   // fold vector ops
3920   if (VT.isVector()) {
3921     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3922       return FoldedVOp;
3923
3924     // fold (xor x, 0) -> x, vector edition
3925     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3926       return N1;
3927     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3928       return N0;
3929   }
3930
3931   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3932   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3933     return DAG.getConstant(0, SDLoc(N), VT);
3934   // fold (xor x, undef) -> undef
3935   if (N0.getOpcode() == ISD::UNDEF)
3936     return N0;
3937   if (N1.getOpcode() == ISD::UNDEF)
3938     return N1;
3939   // fold (xor c1, c2) -> c1^c2
3940   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3941   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3942   if (N0C && N1C)
3943     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3944   // canonicalize constant to RHS
3945   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3946      !isConstantIntBuildVectorOrConstantInt(N1))
3947     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3948   // fold (xor x, 0) -> x
3949   if (isNullConstant(N1))
3950     return N0;
3951   // reassociate xor
3952   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3953     return RXOR;
3954
3955   // fold !(x cc y) -> (x !cc y)
3956   SDValue LHS, RHS, CC;
3957   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3958     bool isInt = LHS.getValueType().isInteger();
3959     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3960                                                isInt);
3961
3962     if (!LegalOperations ||
3963         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3964       switch (N0.getOpcode()) {
3965       default:
3966         llvm_unreachable("Unhandled SetCC Equivalent!");
3967       case ISD::SETCC:
3968         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3969       case ISD::SELECT_CC:
3970         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3971                                N0.getOperand(3), NotCC);
3972       }
3973     }
3974   }
3975
3976   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3977   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
3978       N0.getNode()->hasOneUse() &&
3979       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3980     SDValue V = N0.getOperand(0);
3981     SDLoc DL(N0);
3982     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3983                     DAG.getConstant(1, DL, V.getValueType()));
3984     AddToWorklist(V.getNode());
3985     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3986   }
3987
3988   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3989   if (isOneConstant(N1) && VT == MVT::i1 &&
3990       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3991     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3992     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3993       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3994       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3995       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3996       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3997       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3998     }
3999   }
4000   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4001   if (isAllOnesConstant(N1) &&
4002       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4003     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4004     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4005       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4006       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4007       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4008       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4009       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4010     }
4011   }
4012   // fold (xor (and x, y), y) -> (and (not x), y)
4013   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4014       N0->getOperand(1) == N1) {
4015     SDValue X = N0->getOperand(0);
4016     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4017     AddToWorklist(NotX.getNode());
4018     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4019   }
4020   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4021   if (N1C && N0.getOpcode() == ISD::XOR) {
4022     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4023     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4024     if (N00C) {
4025       SDLoc DL(N);
4026       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4027                          DAG.getConstant(N1C->getAPIntValue() ^
4028                                          N00C->getAPIntValue(), DL, VT));
4029     }
4030     if (N01C) {
4031       SDLoc DL(N);
4032       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4033                          DAG.getConstant(N1C->getAPIntValue() ^
4034                                          N01C->getAPIntValue(), DL, VT));
4035     }
4036   }
4037   // fold (xor x, x) -> 0
4038   if (N0 == N1)
4039     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4040
4041   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4042   // Here is a concrete example of this equivalence:
4043   // i16   x ==  14
4044   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4045   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4046   //
4047   // =>
4048   //
4049   // i16     ~1      == 0b1111111111111110
4050   // i16 rol(~1, 14) == 0b1011111111111111
4051   //
4052   // Some additional tips to help conceptualize this transform:
4053   // - Try to see the operation as placing a single zero in a value of all ones.
4054   // - There exists no value for x which would allow the result to contain zero.
4055   // - Values of x larger than the bitwidth are undefined and do not require a
4056   //   consistent result.
4057   // - Pushing the zero left requires shifting one bits in from the right.
4058   // A rotate left of ~1 is a nice way of achieving the desired result.
4059   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4060       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4061     SDLoc DL(N);
4062     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4063                        N0.getOperand(1));
4064   }
4065
4066   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4067   if (N0.getOpcode() == N1.getOpcode()) {
4068     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4069     if (Tmp.getNode()) return Tmp;
4070   }
4071
4072   // Simplify the expression using non-local knowledge.
4073   if (!VT.isVector() &&
4074       SimplifyDemandedBits(SDValue(N, 0)))
4075     return SDValue(N, 0);
4076
4077   return SDValue();
4078 }
4079
4080 /// Handle transforms common to the three shifts, when the shift amount is a
4081 /// constant.
4082 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4083   // We can't and shouldn't fold opaque constants.
4084   if (Amt->isOpaque())
4085     return SDValue();
4086
4087   SDNode *LHS = N->getOperand(0).getNode();
4088   if (!LHS->hasOneUse()) return SDValue();
4089
4090   // We want to pull some binops through shifts, so that we have (and (shift))
4091   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4092   // thing happens with address calculations, so it's important to canonicalize
4093   // it.
4094   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4095
4096   switch (LHS->getOpcode()) {
4097   default: return SDValue();
4098   case ISD::OR:
4099   case ISD::XOR:
4100     HighBitSet = false; // We can only transform sra if the high bit is clear.
4101     break;
4102   case ISD::AND:
4103     HighBitSet = true;  // We can only transform sra if the high bit is set.
4104     break;
4105   case ISD::ADD:
4106     if (N->getOpcode() != ISD::SHL)
4107       return SDValue(); // only shl(add) not sr[al](add).
4108     HighBitSet = false; // We can only transform sra if the high bit is clear.
4109     break;
4110   }
4111
4112   // We require the RHS of the binop to be a constant and not opaque as well.
4113   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4114   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4115
4116   // FIXME: disable this unless the input to the binop is a shift by a constant.
4117   // If it is not a shift, it pessimizes some common cases like:
4118   //
4119   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4120   //    int bar(int *X, int i) { return X[i & 255]; }
4121   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4122   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4123        BinOpLHSVal->getOpcode() != ISD::SRA &&
4124        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4125       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4126     return SDValue();
4127
4128   EVT VT = N->getValueType(0);
4129
4130   // If this is a signed shift right, and the high bit is modified by the
4131   // logical operation, do not perform the transformation. The highBitSet
4132   // boolean indicates the value of the high bit of the constant which would
4133   // cause it to be modified for this operation.
4134   if (N->getOpcode() == ISD::SRA) {
4135     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4136     if (BinOpRHSSignSet != HighBitSet)
4137       return SDValue();
4138   }
4139
4140   if (!TLI.isDesirableToCommuteWithShift(LHS))
4141     return SDValue();
4142
4143   // Fold the constants, shifting the binop RHS by the shift amount.
4144   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4145                                N->getValueType(0),
4146                                LHS->getOperand(1), N->getOperand(1));
4147   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4148
4149   // Create the new shift.
4150   SDValue NewShift = DAG.getNode(N->getOpcode(),
4151                                  SDLoc(LHS->getOperand(0)),
4152                                  VT, LHS->getOperand(0), N->getOperand(1));
4153
4154   // Create the new binop.
4155   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4156 }
4157
4158 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4159   assert(N->getOpcode() == ISD::TRUNCATE);
4160   assert(N->getOperand(0).getOpcode() == ISD::AND);
4161
4162   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4163   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4164     SDValue N01 = N->getOperand(0).getOperand(1);
4165
4166     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4167       EVT TruncVT = N->getValueType(0);
4168       SDValue N00 = N->getOperand(0).getOperand(0);
4169       APInt TruncC = N01C->getAPIntValue();
4170       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4171       SDLoc DL(N);
4172
4173       return DAG.getNode(ISD::AND, DL, TruncVT,
4174                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4175                          DAG.getConstant(TruncC, DL, TruncVT));
4176     }
4177   }
4178
4179   return SDValue();
4180 }
4181
4182 SDValue DAGCombiner::visitRotate(SDNode *N) {
4183   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4184   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4185       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4186     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4187     if (NewOp1.getNode())
4188       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4189                          N->getOperand(0), NewOp1);
4190   }
4191   return SDValue();
4192 }
4193
4194 SDValue DAGCombiner::visitSHL(SDNode *N) {
4195   SDValue N0 = N->getOperand(0);
4196   SDValue N1 = N->getOperand(1);
4197   EVT VT = N0.getValueType();
4198   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4199
4200   // fold vector ops
4201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202   if (VT.isVector()) {
4203     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4204       return FoldedVOp;
4205
4206     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4207     // If setcc produces all-one true value then:
4208     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4209     if (N1CV && N1CV->isConstant()) {
4210       if (N0.getOpcode() == ISD::AND) {
4211         SDValue N00 = N0->getOperand(0);
4212         SDValue N01 = N0->getOperand(1);
4213         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4214
4215         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4216             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4217                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4218           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219                                                      N01CV, N1CV))
4220             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4221         }
4222       } else {
4223         N1C = isConstOrConstSplat(N1);
4224       }
4225     }
4226   }
4227
4228   // fold (shl c1, c2) -> c1<<c2
4229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230   if (N0C && N1C)
4231     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4232   // fold (shl 0, x) -> 0
4233   if (isNullConstant(N0))
4234     return N0;
4235   // fold (shl x, c >= size(x)) -> undef
4236   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4237     return DAG.getUNDEF(VT);
4238   // fold (shl x, 0) -> x
4239   if (N1C && N1C->isNullValue())
4240     return N0;
4241   // fold (shl undef, x) -> 0
4242   if (N0.getOpcode() == ISD::UNDEF)
4243     return DAG.getConstant(0, SDLoc(N), VT);
4244   // if (shl x, c) is known to be zero, return 0
4245   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4246                             APInt::getAllOnesValue(OpSizeInBits)))
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4249   if (N1.getOpcode() == ISD::TRUNCATE &&
4250       N1.getOperand(0).getOpcode() == ISD::AND) {
4251     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4252     if (NewOp1.getNode())
4253       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4254   }
4255
4256   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4257     return SDValue(N, 0);
4258
4259   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4260   if (N1C && N0.getOpcode() == ISD::SHL) {
4261     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4262       uint64_t c1 = N0C1->getZExtValue();
4263       uint64_t c2 = N1C->getZExtValue();
4264       SDLoc DL(N);
4265       if (c1 + c2 >= OpSizeInBits)
4266         return DAG.getConstant(0, DL, VT);
4267       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4268                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4269     }
4270   }
4271
4272   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4273   // For this to be valid, the second form must not preserve any of the bits
4274   // that are shifted out by the inner shift in the first form.  This means
4275   // the outer shift size must be >= the number of bits added by the ext.
4276   // As a corollary, we don't care what kind of ext it is.
4277   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4278               N0.getOpcode() == ISD::ANY_EXTEND ||
4279               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4280       N0.getOperand(0).getOpcode() == ISD::SHL) {
4281     SDValue N0Op0 = N0.getOperand(0);
4282     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4283       uint64_t c1 = N0Op0C1->getZExtValue();
4284       uint64_t c2 = N1C->getZExtValue();
4285       EVT InnerShiftVT = N0Op0.getValueType();
4286       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4287       if (c2 >= OpSizeInBits - InnerShiftSize) {
4288         SDLoc DL(N0);
4289         if (c1 + c2 >= OpSizeInBits)
4290           return DAG.getConstant(0, DL, VT);
4291         return DAG.getNode(ISD::SHL, DL, VT,
4292                            DAG.getNode(N0.getOpcode(), DL, VT,
4293                                        N0Op0->getOperand(0)),
4294                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4295       }
4296     }
4297   }
4298
4299   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4300   // Only fold this if the inner zext has no other uses to avoid increasing
4301   // the total number of instructions.
4302   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4303       N0.getOperand(0).getOpcode() == ISD::SRL) {
4304     SDValue N0Op0 = N0.getOperand(0);
4305     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4306       uint64_t c1 = N0Op0C1->getZExtValue();
4307       if (c1 < VT.getScalarSizeInBits()) {
4308         uint64_t c2 = N1C->getZExtValue();
4309         if (c1 == c2) {
4310           SDValue NewOp0 = N0.getOperand(0);
4311           EVT CountVT = NewOp0.getOperand(1).getValueType();
4312           SDLoc DL(N);
4313           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314                                        NewOp0,
4315                                        DAG.getConstant(c2, DL, CountVT));
4316           AddToWorklist(NewSHL.getNode());
4317           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4318         }
4319       }
4320     }
4321   }
4322
4323   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4324   //                               (and (srl x, (sub c1, c2), MASK)
4325   // Only fold this if the inner shift has no other uses -- if it does, folding
4326   // this will increase the total number of instructions.
4327   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4328     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329       uint64_t c1 = N0C1->getZExtValue();
4330       if (c1 < OpSizeInBits) {
4331         uint64_t c2 = N1C->getZExtValue();
4332         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4333         SDValue Shift;
4334         if (c2 > c1) {
4335           Mask = Mask.shl(c2 - c1);
4336           SDLoc DL(N);
4337           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4338                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4339         } else {
4340           Mask = Mask.lshr(c1 - c2);
4341           SDLoc DL(N);
4342           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4343                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4344         }
4345         SDLoc DL(N0);
4346         return DAG.getNode(ISD::AND, DL, VT, Shift,
4347                            DAG.getConstant(Mask, DL, VT));
4348       }
4349     }
4350   }
4351   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4352   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4353     unsigned BitSize = VT.getScalarSizeInBits();
4354     SDLoc DL(N);
4355     SDValue HiBitsMask =
4356       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4357                                             BitSize - N1C->getZExtValue()),
4358                       DL, VT);
4359     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4360                        HiBitsMask);
4361   }
4362
4363   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4364   // Variant of version done on multiply, except mul by a power of 2 is turned
4365   // into a shift.
4366   APInt Val;
4367   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4368       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4369        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4370     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4371     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4372     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4373   }
4374
4375   if (N1C) {
4376     SDValue NewSHL = visitShiftByConstant(N, N1C);
4377     if (NewSHL.getNode())
4378       return NewSHL;
4379   }
4380
4381   return SDValue();
4382 }
4383
4384 SDValue DAGCombiner::visitSRA(SDNode *N) {
4385   SDValue N0 = N->getOperand(0);
4386   SDValue N1 = N->getOperand(1);
4387   EVT VT = N0.getValueType();
4388   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4389
4390   // fold vector ops
4391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4392   if (VT.isVector()) {
4393     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4394       return FoldedVOp;
4395
4396     N1C = isConstOrConstSplat(N1);
4397   }
4398
4399   // fold (sra c1, c2) -> (sra c1, c2)
4400   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4401   if (N0C && N1C)
4402     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4403   // fold (sra 0, x) -> 0
4404   if (isNullConstant(N0))
4405     return N0;
4406   // fold (sra -1, x) -> -1
4407   if (isAllOnesConstant(N0))
4408     return N0;
4409   // fold (sra x, (setge c, size(x))) -> undef
4410   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4411     return DAG.getUNDEF(VT);
4412   // fold (sra x, 0) -> x
4413   if (N1C && N1C->isNullValue())
4414     return N0;
4415   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416   // sext_inreg.
4417   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4418     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4419     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420     if (VT.isVector())
4421       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4422                                ExtVT, VT.getVectorNumElements());
4423     if ((!LegalOperations ||
4424          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4425       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4426                          N0.getOperand(0), DAG.getValueType(ExtVT));
4427   }
4428
4429   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4430   if (N1C && N0.getOpcode() == ISD::SRA) {
4431     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4432       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4433       if (Sum >= OpSizeInBits)
4434         Sum = OpSizeInBits - 1;
4435       SDLoc DL(N);
4436       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4437                          DAG.getConstant(Sum, DL, N1.getValueType()));
4438     }
4439   }
4440
4441   // fold (sra (shl X, m), (sub result_size, n))
4442   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4443   // result_size - n != m.
4444   // If truncate is free for the target sext(shl) is likely to result in better
4445   // code.
4446   if (N0.getOpcode() == ISD::SHL && N1C) {
4447     // Get the two constanst of the shifts, CN0 = m, CN = n.
4448     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449     if (N01C) {
4450       LLVMContext &Ctx = *DAG.getContext();
4451       // Determine what the truncate's result bitsize and type would be.
4452       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4453
4454       if (VT.isVector())
4455         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456
4457       // Determine the residual right-shift amount.
4458       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4459
4460       // If the shift is not a no-op (in which case this should be just a sign
4461       // extend already), the truncated to type is legal, sign_extend is legal
4462       // on that type, and the truncate to that type is both legal and free,
4463       // perform the transform.
4464       if ((ShiftAmt > 0) &&
4465           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4466           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4467           TLI.isTruncateFree(VT, TruncVT)) {
4468
4469         SDLoc DL(N);
4470         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4471             getShiftAmountTy(N0.getOperand(0).getValueType()));
4472         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4473                                     N0.getOperand(0), Amt);
4474         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475                                     Shift);
4476         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4477                            N->getValueType(0), Trunc);
4478       }
4479     }
4480   }
4481
4482   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4483   if (N1.getOpcode() == ISD::TRUNCATE &&
4484       N1.getOperand(0).getOpcode() == ISD::AND) {
4485     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486     if (NewOp1.getNode())
4487       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4488   }
4489
4490   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4491   //      if c1 is equal to the number of bits the trunc removes
4492   if (N0.getOpcode() == ISD::TRUNCATE &&
4493       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4494        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4495       N0.getOperand(0).hasOneUse() &&
4496       N0.getOperand(0).getOperand(1).hasOneUse() &&
4497       N1C) {
4498     SDValue N0Op0 = N0.getOperand(0);
4499     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4500       unsigned LargeShiftVal = LargeShift->getZExtValue();
4501       EVT LargeVT = N0Op0.getValueType();
4502
4503       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4504         SDLoc DL(N);
4505         SDValue Amt =
4506           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4507                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4508         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4509                                   N0Op0.getOperand(0), Amt);
4510         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4511       }
4512     }
4513   }
4514
4515   // Simplify, based on bits shifted out of the LHS.
4516   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4517     return SDValue(N, 0);
4518
4519
4520   // If the sign bit is known to be zero, switch this to a SRL.
4521   if (DAG.SignBitIsZero(N0))
4522     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4523
4524   if (N1C) {
4525     SDValue NewSRA = visitShiftByConstant(N, N1C);
4526     if (NewSRA.getNode())
4527       return NewSRA;
4528   }
4529
4530   return SDValue();
4531 }
4532
4533 SDValue DAGCombiner::visitSRL(SDNode *N) {
4534   SDValue N0 = N->getOperand(0);
4535   SDValue N1 = N->getOperand(1);
4536   EVT VT = N0.getValueType();
4537   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4538
4539   // fold vector ops
4540   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4541   if (VT.isVector()) {
4542     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4543       return FoldedVOp;
4544
4545     N1C = isConstOrConstSplat(N1);
4546   }
4547
4548   // fold (srl c1, c2) -> c1 >>u c2
4549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4550   if (N0C && N1C)
4551     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4552   // fold (srl 0, x) -> 0
4553   if (isNullConstant(N0))
4554     return N0;
4555   // fold (srl x, c >= size(x)) -> undef
4556   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4557     return DAG.getUNDEF(VT);
4558   // fold (srl x, 0) -> x
4559   if (N1C && N1C->isNullValue())
4560     return N0;
4561   // if (srl x, c) is known to be zero, return 0
4562   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4563                                    APInt::getAllOnesValue(OpSizeInBits)))
4564     return DAG.getConstant(0, SDLoc(N), VT);
4565
4566   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4567   if (N1C && N0.getOpcode() == ISD::SRL) {
4568     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4569       uint64_t c1 = N01C->getZExtValue();
4570       uint64_t c2 = N1C->getZExtValue();
4571       SDLoc DL(N);
4572       if (c1 + c2 >= OpSizeInBits)
4573         return DAG.getConstant(0, DL, VT);
4574       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4575                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4576     }
4577   }
4578
4579   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4580   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4581       N0.getOperand(0).getOpcode() == ISD::SRL &&
4582       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4583     uint64_t c1 =
4584       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4585     uint64_t c2 = N1C->getZExtValue();
4586     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4587     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4588     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4589     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4590     if (c1 + OpSizeInBits == InnerShiftSize) {
4591       SDLoc DL(N0);
4592       if (c1 + c2 >= InnerShiftSize)
4593         return DAG.getConstant(0, DL, VT);
4594       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4595                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4596                                      N0.getOperand(0)->getOperand(0),
4597                                      DAG.getConstant(c1 + c2, DL,
4598                                                      ShiftCountVT)));
4599     }
4600   }
4601
4602   // fold (srl (shl x, c), c) -> (and x, cst2)
4603   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4604     unsigned BitSize = N0.getScalarValueSizeInBits();
4605     if (BitSize <= 64) {
4606       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4607       SDLoc DL(N);
4608       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4609                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4610     }
4611   }
4612
4613   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4614   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4615     // Shifting in all undef bits?
4616     EVT SmallVT = N0.getOperand(0).getValueType();
4617     unsigned BitSize = SmallVT.getScalarSizeInBits();
4618     if (N1C->getZExtValue() >= BitSize)
4619       return DAG.getUNDEF(VT);
4620
4621     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4622       uint64_t ShiftAmt = N1C->getZExtValue();
4623       SDLoc DL0(N0);
4624       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4625                                        N0.getOperand(0),
4626                           DAG.getConstant(ShiftAmt, DL0,
4627                                           getShiftAmountTy(SmallVT)));
4628       AddToWorklist(SmallShift.getNode());
4629       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4630       SDLoc DL(N);
4631       return DAG.getNode(ISD::AND, DL, VT,
4632                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4633                          DAG.getConstant(Mask, DL, VT));
4634     }
4635   }
4636
4637   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4638   // bit, which is unmodified by sra.
4639   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4640     if (N0.getOpcode() == ISD::SRA)
4641       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4642   }
4643
4644   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4645   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4646       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4647     APInt KnownZero, KnownOne;
4648     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4649
4650     // If any of the input bits are KnownOne, then the input couldn't be all
4651     // zeros, thus the result of the srl will always be zero.
4652     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4653
4654     // If all of the bits input the to ctlz node are known to be zero, then
4655     // the result of the ctlz is "32" and the result of the shift is one.
4656     APInt UnknownBits = ~KnownZero;
4657     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4658
4659     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4660     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4661       // Okay, we know that only that the single bit specified by UnknownBits
4662       // could be set on input to the CTLZ node. If this bit is set, the SRL
4663       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4664       // to an SRL/XOR pair, which is likely to simplify more.
4665       unsigned ShAmt = UnknownBits.countTrailingZeros();
4666       SDValue Op = N0.getOperand(0);
4667
4668       if (ShAmt) {
4669         SDLoc DL(N0);
4670         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4671                   DAG.getConstant(ShAmt, DL,
4672                                   getShiftAmountTy(Op.getValueType())));
4673         AddToWorklist(Op.getNode());
4674       }
4675
4676       SDLoc DL(N);
4677       return DAG.getNode(ISD::XOR, DL, VT,
4678                          Op, DAG.getConstant(1, DL, VT));
4679     }
4680   }
4681
4682   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4683   if (N1.getOpcode() == ISD::TRUNCATE &&
4684       N1.getOperand(0).getOpcode() == ISD::AND) {
4685     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4686     if (NewOp1.getNode())
4687       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4688   }
4689
4690   // fold operands of srl based on knowledge that the low bits are not
4691   // demanded.
4692   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693     return SDValue(N, 0);
4694
4695   if (N1C) {
4696     SDValue NewSRL = visitShiftByConstant(N, N1C);
4697     if (NewSRL.getNode())
4698       return NewSRL;
4699   }
4700
4701   // Attempt to convert a srl of a load into a narrower zero-extending load.
4702   SDValue NarrowLoad = ReduceLoadWidth(N);
4703   if (NarrowLoad.getNode())
4704     return NarrowLoad;
4705
4706   // Here is a common situation. We want to optimize:
4707   //
4708   //   %a = ...
4709   //   %b = and i32 %a, 2
4710   //   %c = srl i32 %b, 1
4711   //   brcond i32 %c ...
4712   //
4713   // into
4714   //
4715   //   %a = ...
4716   //   %b = and %a, 2
4717   //   %c = setcc eq %b, 0
4718   //   brcond %c ...
4719   //
4720   // However when after the source operand of SRL is optimized into AND, the SRL
4721   // itself may not be optimized further. Look for it and add the BRCOND into
4722   // the worklist.
4723   if (N->hasOneUse()) {
4724     SDNode *Use = *N->use_begin();
4725     if (Use->getOpcode() == ISD::BRCOND)
4726       AddToWorklist(Use);
4727     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4728       // Also look pass the truncate.
4729       Use = *Use->use_begin();
4730       if (Use->getOpcode() == ISD::BRCOND)
4731         AddToWorklist(Use);
4732     }
4733   }
4734
4735   return SDValue();
4736 }
4737
4738 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4739   SDValue N0 = N->getOperand(0);
4740   EVT VT = N->getValueType(0);
4741
4742   // fold (ctlz c1) -> c2
4743   if (isa<ConstantSDNode>(N0))
4744     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4745   return SDValue();
4746 }
4747
4748 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4749   SDValue N0 = N->getOperand(0);
4750   EVT VT = N->getValueType(0);
4751
4752   // fold (ctlz_zero_undef c1) -> c2
4753   if (isa<ConstantSDNode>(N0))
4754     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4755   return SDValue();
4756 }
4757
4758 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4759   SDValue N0 = N->getOperand(0);
4760   EVT VT = N->getValueType(0);
4761
4762   // fold (cttz c1) -> c2
4763   if (isa<ConstantSDNode>(N0))
4764     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4765   return SDValue();
4766 }
4767
4768 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4769   SDValue N0 = N->getOperand(0);
4770   EVT VT = N->getValueType(0);
4771
4772   // fold (cttz_zero_undef c1) -> c2
4773   if (isa<ConstantSDNode>(N0))
4774     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4775   return SDValue();
4776 }
4777
4778 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4779   SDValue N0 = N->getOperand(0);
4780   EVT VT = N->getValueType(0);
4781
4782   // fold (ctpop c1) -> c2
4783   if (isa<ConstantSDNode>(N0))
4784     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4785   return SDValue();
4786 }
4787
4788
4789 /// \brief Generate Min/Max node
4790 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4791                                    SDValue True, SDValue False,
4792                                    ISD::CondCode CC, const TargetLowering &TLI,
4793                                    SelectionDAG &DAG) {
4794   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4795     return SDValue();
4796
4797   switch (CC) {
4798   case ISD::SETOLT:
4799   case ISD::SETOLE:
4800   case ISD::SETLT:
4801   case ISD::SETLE:
4802   case ISD::SETULT:
4803   case ISD::SETULE: {
4804     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4805     if (TLI.isOperationLegal(Opcode, VT))
4806       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4807     return SDValue();
4808   }
4809   case ISD::SETOGT:
4810   case ISD::SETOGE:
4811   case ISD::SETGT:
4812   case ISD::SETGE:
4813   case ISD::SETUGT:
4814   case ISD::SETUGE: {
4815     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4816     if (TLI.isOperationLegal(Opcode, VT))
4817       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4818     return SDValue();
4819   }
4820   default:
4821     return SDValue();
4822   }
4823 }
4824
4825 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4826   SDValue N0 = N->getOperand(0);
4827   SDValue N1 = N->getOperand(1);
4828   SDValue N2 = N->getOperand(2);
4829   EVT VT = N->getValueType(0);
4830   EVT VT0 = N0.getValueType();
4831
4832   // fold (select C, X, X) -> X
4833   if (N1 == N2)
4834     return N1;
4835   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4836     // fold (select true, X, Y) -> X
4837     // fold (select false, X, Y) -> Y
4838     return !N0C->isNullValue() ? N1 : N2;
4839   }
4840   // fold (select C, 1, X) -> (or C, X)
4841   if (VT == MVT::i1 && isOneConstant(N1))
4842     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4843   // fold (select C, 0, 1) -> (xor C, 1)
4844   // We can't do this reliably if integer based booleans have different contents
4845   // to floating point based booleans. This is because we can't tell whether we
4846   // have an integer-based boolean or a floating-point-based boolean unless we
4847   // can find the SETCC that produced it and inspect its operands. This is
4848   // fairly easy if C is the SETCC node, but it can potentially be
4849   // undiscoverable (or not reasonably discoverable). For example, it could be
4850   // in another basic block or it could require searching a complicated
4851   // expression.
4852   if (VT.isInteger() &&
4853       (VT0 == MVT::i1 || (VT0.isInteger() &&
4854                           TLI.getBooleanContents(false, false) ==
4855                               TLI.getBooleanContents(false, true) &&
4856                           TLI.getBooleanContents(false, false) ==
4857                               TargetLowering::ZeroOrOneBooleanContent)) &&
4858       isNullConstant(N1) && isOneConstant(N2)) {
4859     SDValue XORNode;
4860     if (VT == VT0) {
4861       SDLoc DL(N);
4862       return DAG.getNode(ISD::XOR, DL, VT0,
4863                          N0, DAG.getConstant(1, DL, VT0));
4864     }
4865     SDLoc DL0(N0);
4866     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4867                           N0, DAG.getConstant(1, DL0, VT0));
4868     AddToWorklist(XORNode.getNode());
4869     if (VT.bitsGT(VT0))
4870       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4871     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4872   }
4873   // fold (select C, 0, X) -> (and (not C), X)
4874   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4875     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4876     AddToWorklist(NOTNode.getNode());
4877     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4878   }
4879   // fold (select C, X, 1) -> (or (not C), X)
4880   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4881     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4882     AddToWorklist(NOTNode.getNode());
4883     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4884   }
4885   // fold (select C, X, 0) -> (and C, X)
4886   if (VT == MVT::i1 && isNullConstant(N2))
4887     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4888   // fold (select X, X, Y) -> (or X, Y)
4889   // fold (select X, 1, Y) -> (or X, Y)
4890   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4891     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4892   // fold (select X, Y, X) -> (and X, Y)
4893   // fold (select X, Y, 0) -> (and X, Y)
4894   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4895     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4896
4897   // If we can fold this based on the true/false value, do so.
4898   if (SimplifySelectOps(N, N1, N2))
4899     return SDValue(N, 0);  // Don't revisit N.
4900
4901   // fold selects based on a setcc into other things, such as min/max/abs
4902   if (N0.getOpcode() == ISD::SETCC) {
4903     // select x, y (fcmp lt x, y) -> fminnum x, y
4904     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4905     //
4906     // This is OK if we don't care about what happens if either operand is a
4907     // NaN.
4908     //
4909
4910     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4911     // no signed zeros as well as no nans.
4912     const TargetOptions &Options = DAG.getTarget().Options;
4913     if (Options.UnsafeFPMath &&
4914         VT.isFloatingPoint() && N0.hasOneUse() &&
4915         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4916       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4917
4918       SDValue FMinMax =
4919           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4920                               N1, N2, CC, TLI, DAG);
4921       if (FMinMax)
4922         return FMinMax;
4923     }
4924
4925     if ((!LegalOperations &&
4926          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4927         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4928       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4929                          N0.getOperand(0), N0.getOperand(1),
4930                          N1, N2, N0.getOperand(2));
4931     return SimplifySelect(SDLoc(N), N0, N1, N2);
4932   }
4933
4934   if (VT0 == MVT::i1) {
4935     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4936       // select (and Cond0, Cond1), X, Y
4937       //   -> select Cond0, (select Cond1, X, Y), Y
4938       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4939         SDValue Cond0 = N0->getOperand(0);
4940         SDValue Cond1 = N0->getOperand(1);
4941         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4942                                           N1.getValueType(), Cond1, N1, N2);
4943         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4944                            InnerSelect, N2);
4945       }
4946       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4947       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4948         SDValue Cond0 = N0->getOperand(0);
4949         SDValue Cond1 = N0->getOperand(1);
4950         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4951                                           N1.getValueType(), Cond1, N1, N2);
4952         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4953                            InnerSelect);
4954       }
4955     }
4956
4957     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4958     if (N1->getOpcode() == ISD::SELECT) {
4959       SDValue N1_0 = N1->getOperand(0);
4960       SDValue N1_1 = N1->getOperand(1);
4961       SDValue N1_2 = N1->getOperand(2);
4962       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4963         // Create the actual and node if we can generate good code for it.
4964         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4965           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4966                                     N0, N1_0);
4967           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4968                              N1_1, N2);
4969         }
4970         // Otherwise see if we can optimize the "and" to a better pattern.
4971         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4972           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4973                              N1_1, N2);
4974       }
4975     }
4976     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4977     if (N2->getOpcode() == ISD::SELECT) {
4978       SDValue N2_0 = N2->getOperand(0);
4979       SDValue N2_1 = N2->getOperand(1);
4980       SDValue N2_2 = N2->getOperand(2);
4981       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4982         // Create the actual or node if we can generate good code for it.
4983         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4984           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4985                                    N0, N2_0);
4986           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4987                              N1, N2_2);
4988         }
4989         // Otherwise see if we can optimize to a better pattern.
4990         if (SDValue Combined = visitORLike(N0, N2_0, N))
4991           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4992                              N1, N2_2);
4993       }
4994     }
4995   }
4996
4997   return SDValue();
4998 }
4999
5000 static
5001 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5002   SDLoc DL(N);
5003   EVT LoVT, HiVT;
5004   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5005
5006   // Split the inputs.
5007   SDValue Lo, Hi, LL, LH, RL, RH;
5008   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5009   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5010
5011   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5012   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5013
5014   return std::make_pair(Lo, Hi);
5015 }
5016
5017 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5018 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5019 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5020   SDLoc dl(N);
5021   SDValue Cond = N->getOperand(0);
5022   SDValue LHS = N->getOperand(1);
5023   SDValue RHS = N->getOperand(2);
5024   EVT VT = N->getValueType(0);
5025   int NumElems = VT.getVectorNumElements();
5026   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5027          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5028          Cond.getOpcode() == ISD::BUILD_VECTOR);
5029
5030   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5031   // binary ones here.
5032   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5033     return SDValue();
5034
5035   // We're sure we have an even number of elements due to the
5036   // concat_vectors we have as arguments to vselect.
5037   // Skip BV elements until we find one that's not an UNDEF
5038   // After we find an UNDEF element, keep looping until we get to half the
5039   // length of the BV and see if all the non-undef nodes are the same.
5040   ConstantSDNode *BottomHalf = nullptr;
5041   for (int i = 0; i < NumElems / 2; ++i) {
5042     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5043       continue;
5044
5045     if (BottomHalf == nullptr)
5046       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5047     else if (Cond->getOperand(i).getNode() != BottomHalf)
5048       return SDValue();
5049   }
5050
5051   // Do the same for the second half of the BuildVector
5052   ConstantSDNode *TopHalf = nullptr;
5053   for (int i = NumElems / 2; i < NumElems; ++i) {
5054     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5055       continue;
5056
5057     if (TopHalf == nullptr)
5058       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5059     else if (Cond->getOperand(i).getNode() != TopHalf)
5060       return SDValue();
5061   }
5062
5063   assert(TopHalf && BottomHalf &&
5064          "One half of the selector was all UNDEFs and the other was all the "
5065          "same value. This should have been addressed before this function.");
5066   return DAG.getNode(
5067       ISD::CONCAT_VECTORS, dl, VT,
5068       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5069       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5070 }
5071
5072 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5073
5074   if (Level >= AfterLegalizeTypes)
5075     return SDValue();
5076
5077   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5078   SDValue Mask = MSC->getMask();
5079   SDValue Data  = MSC->getValue();
5080   SDLoc DL(N);
5081
5082   // If the MSCATTER data type requires splitting and the mask is provided by a
5083   // SETCC, then split both nodes and its operands before legalization. This
5084   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5085   // and enables future optimizations (e.g. min/max pattern matching on X86).
5086   if (Mask.getOpcode() != ISD::SETCC)
5087     return SDValue();
5088
5089   // Check if any splitting is required.
5090   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5091       TargetLowering::TypeSplitVector)
5092     return SDValue();
5093   SDValue MaskLo, MaskHi, Lo, Hi;
5094   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5095
5096   EVT LoVT, HiVT;
5097   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5098
5099   SDValue Chain = MSC->getChain();
5100
5101   EVT MemoryVT = MSC->getMemoryVT();
5102   unsigned Alignment = MSC->getOriginalAlignment();
5103
5104   EVT LoMemVT, HiMemVT;
5105   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5106
5107   SDValue DataLo, DataHi;
5108   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5109
5110   SDValue BasePtr = MSC->getBasePtr();
5111   SDValue IndexLo, IndexHi;
5112   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5113
5114   MachineMemOperand *MMO = DAG.getMachineFunction().
5115     getMachineMemOperand(MSC->getPointerInfo(), 
5116                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5117                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5118
5119   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5120   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5121                             DL, OpsLo, MMO);
5122
5123   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5124   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5125                             DL, OpsHi, MMO);
5126
5127   AddToWorklist(Lo.getNode());
5128   AddToWorklist(Hi.getNode());
5129
5130   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5131 }
5132
5133 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5134
5135   if (Level >= AfterLegalizeTypes)
5136     return SDValue();
5137
5138   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5139   SDValue Mask = MST->getMask();
5140   SDValue Data  = MST->getValue();
5141   SDLoc DL(N);
5142
5143   // If the MSTORE data type requires splitting and the mask is provided by a
5144   // SETCC, then split both nodes and its operands before legalization. This
5145   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5146   // and enables future optimizations (e.g. min/max pattern matching on X86).
5147   if (Mask.getOpcode() == ISD::SETCC) {
5148
5149     // Check if any splitting is required.
5150     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5151         TargetLowering::TypeSplitVector)
5152       return SDValue();
5153
5154     SDValue MaskLo, MaskHi, Lo, Hi;
5155     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5156
5157     EVT LoVT, HiVT;
5158     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5159
5160     SDValue Chain = MST->getChain();
5161     SDValue Ptr   = MST->getBasePtr();
5162
5163     EVT MemoryVT = MST->getMemoryVT();
5164     unsigned Alignment = MST->getOriginalAlignment();
5165
5166     // if Alignment is equal to the vector size,
5167     // take the half of it for the second part
5168     unsigned SecondHalfAlignment =
5169       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5170          Alignment/2 : Alignment;
5171
5172     EVT LoMemVT, HiMemVT;
5173     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5174
5175     SDValue DataLo, DataHi;
5176     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5177
5178     MachineMemOperand *MMO = DAG.getMachineFunction().
5179       getMachineMemOperand(MST->getPointerInfo(),
5180                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5181                            Alignment, MST->getAAInfo(), MST->getRanges());
5182
5183     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5184                             MST->isTruncatingStore());
5185
5186     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5187     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5188                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5189
5190     MMO = DAG.getMachineFunction().
5191       getMachineMemOperand(MST->getPointerInfo(),
5192                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5193                            SecondHalfAlignment, MST->getAAInfo(),
5194                            MST->getRanges());
5195
5196     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5197                             MST->isTruncatingStore());
5198
5199     AddToWorklist(Lo.getNode());
5200     AddToWorklist(Hi.getNode());
5201
5202     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5203   }
5204   return SDValue();
5205 }
5206
5207 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5208
5209   if (Level >= AfterLegalizeTypes)
5210     return SDValue();
5211
5212   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5213   SDValue Mask = MGT->getMask();
5214   SDLoc DL(N);
5215
5216   // If the MGATHER result requires splitting and the mask is provided by a
5217   // SETCC, then split both nodes and its operands before legalization. This
5218   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5219   // and enables future optimizations (e.g. min/max pattern matching on X86).
5220
5221   if (Mask.getOpcode() != ISD::SETCC)
5222     return SDValue();
5223
5224   EVT VT = N->getValueType(0);
5225
5226   // Check if any splitting is required.
5227   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5228       TargetLowering::TypeSplitVector)
5229     return SDValue();
5230
5231   SDValue MaskLo, MaskHi, Lo, Hi;
5232   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5233
5234   SDValue Src0 = MGT->getValue();
5235   SDValue Src0Lo, Src0Hi;
5236   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5237
5238   EVT LoVT, HiVT;
5239   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5240
5241   SDValue Chain = MGT->getChain();
5242   EVT MemoryVT = MGT->getMemoryVT();
5243   unsigned Alignment = MGT->getOriginalAlignment();
5244
5245   EVT LoMemVT, HiMemVT;
5246   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5247
5248   SDValue BasePtr = MGT->getBasePtr();
5249   SDValue Index = MGT->getIndex();
5250   SDValue IndexLo, IndexHi;
5251   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5252
5253   MachineMemOperand *MMO = DAG.getMachineFunction().
5254     getMachineMemOperand(MGT->getPointerInfo(), 
5255                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5256                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5257
5258   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5259   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5260                             MMO);
5261
5262   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5263   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5264                             MMO);
5265
5266   AddToWorklist(Lo.getNode());
5267   AddToWorklist(Hi.getNode());
5268
5269   // Build a factor node to remember that this load is independent of the
5270   // other one.
5271   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5272                       Hi.getValue(1));
5273
5274   // Legalized the chain result - switch anything that used the old chain to
5275   // use the new one.
5276   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5277
5278   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5279
5280   SDValue RetOps[] = { GatherRes, Chain };
5281   return DAG.getMergeValues(RetOps, DL);
5282 }
5283
5284 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5285
5286   if (Level >= AfterLegalizeTypes)
5287     return SDValue();
5288
5289   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5290   SDValue Mask = MLD->getMask();
5291   SDLoc DL(N);
5292
5293   // If the MLOAD result requires splitting and the mask is provided by a
5294   // SETCC, then split both nodes and its operands before legalization. This
5295   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5296   // and enables future optimizations (e.g. min/max pattern matching on X86).
5297
5298   if (Mask.getOpcode() == ISD::SETCC) {
5299     EVT VT = N->getValueType(0);
5300
5301     // Check if any splitting is required.
5302     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5303         TargetLowering::TypeSplitVector)
5304       return SDValue();
5305
5306     SDValue MaskLo, MaskHi, Lo, Hi;
5307     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5308
5309     SDValue Src0 = MLD->getSrc0();
5310     SDValue Src0Lo, Src0Hi;
5311     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5312
5313     EVT LoVT, HiVT;
5314     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5315
5316     SDValue Chain = MLD->getChain();
5317     SDValue Ptr   = MLD->getBasePtr();
5318     EVT MemoryVT = MLD->getMemoryVT();
5319     unsigned Alignment = MLD->getOriginalAlignment();
5320
5321     // if Alignment is equal to the vector size,
5322     // take the half of it for the second part
5323     unsigned SecondHalfAlignment =
5324       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5325          Alignment/2 : Alignment;
5326
5327     EVT LoMemVT, HiMemVT;
5328     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5329
5330     MachineMemOperand *MMO = DAG.getMachineFunction().
5331     getMachineMemOperand(MLD->getPointerInfo(),
5332                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5333                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5334
5335     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5336                            ISD::NON_EXTLOAD);
5337
5338     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5339     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5340                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5341
5342     MMO = DAG.getMachineFunction().
5343     getMachineMemOperand(MLD->getPointerInfo(),
5344                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5345                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5346
5347     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5348                            ISD::NON_EXTLOAD);
5349
5350     AddToWorklist(Lo.getNode());
5351     AddToWorklist(Hi.getNode());
5352
5353     // Build a factor node to remember that this load is independent of the
5354     // other one.
5355     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5356                         Hi.getValue(1));
5357
5358     // Legalized the chain result - switch anything that used the old chain to
5359     // use the new one.
5360     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5361
5362     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5363
5364     SDValue RetOps[] = { LoadRes, Chain };
5365     return DAG.getMergeValues(RetOps, DL);
5366   }
5367   return SDValue();
5368 }
5369
5370 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5371   SDValue N0 = N->getOperand(0);
5372   SDValue N1 = N->getOperand(1);
5373   SDValue N2 = N->getOperand(2);
5374   SDLoc DL(N);
5375
5376   // Canonicalize integer abs.
5377   // vselect (setg[te] X,  0),  X, -X ->
5378   // vselect (setgt    X, -1),  X, -X ->
5379   // vselect (setl[te] X,  0), -X,  X ->
5380   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5381   if (N0.getOpcode() == ISD::SETCC) {
5382     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5383     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5384     bool isAbs = false;
5385     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5386
5387     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5388          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5389         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5390       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5391     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5392              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5393       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5394
5395     if (isAbs) {
5396       EVT VT = LHS.getValueType();
5397       SDValue Shift = DAG.getNode(
5398           ISD::SRA, DL, VT, LHS,
5399           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5400       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5401       AddToWorklist(Shift.getNode());
5402       AddToWorklist(Add.getNode());
5403       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5404     }
5405   }
5406
5407   if (SimplifySelectOps(N, N1, N2))
5408     return SDValue(N, 0);  // Don't revisit N.
5409
5410   // If the VSELECT result requires splitting and the mask is provided by a
5411   // SETCC, then split both nodes and its operands before legalization. This
5412   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5413   // and enables future optimizations (e.g. min/max pattern matching on X86).
5414   if (N0.getOpcode() == ISD::SETCC) {
5415     EVT VT = N->getValueType(0);
5416
5417     // Check if any splitting is required.
5418     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5419         TargetLowering::TypeSplitVector)
5420       return SDValue();
5421
5422     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5423     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5424     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5425     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5426
5427     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5428     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5429
5430     // Add the new VSELECT nodes to the work list in case they need to be split
5431     // again.
5432     AddToWorklist(Lo.getNode());
5433     AddToWorklist(Hi.getNode());
5434
5435     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5436   }
5437
5438   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5439   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5440     return N1;
5441   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5442   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5443     return N2;
5444
5445   // The ConvertSelectToConcatVector function is assuming both the above
5446   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5447   // and addressed.
5448   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5449       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5450       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5451     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5452     if (CV.getNode())
5453       return CV;
5454   }
5455
5456   return SDValue();
5457 }
5458
5459 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5460   SDValue N0 = N->getOperand(0);
5461   SDValue N1 = N->getOperand(1);
5462   SDValue N2 = N->getOperand(2);
5463   SDValue N3 = N->getOperand(3);
5464   SDValue N4 = N->getOperand(4);
5465   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5466
5467   // fold select_cc lhs, rhs, x, x, cc -> x
5468   if (N2 == N3)
5469     return N2;
5470
5471   // Determine if the condition we're dealing with is constant
5472   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5473                               N0, N1, CC, SDLoc(N), false);
5474   if (SCC.getNode()) {
5475     AddToWorklist(SCC.getNode());
5476
5477     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5478       if (!SCCC->isNullValue())
5479         return N2;    // cond always true -> true val
5480       else
5481         return N3;    // cond always false -> false val
5482     } else if (SCC->getOpcode() == ISD::UNDEF) {
5483       // When the condition is UNDEF, just return the first operand. This is
5484       // coherent the DAG creation, no setcc node is created in this case
5485       return N2;
5486     } else if (SCC.getOpcode() == ISD::SETCC) {
5487       // Fold to a simpler select_cc
5488       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5489                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5490                          SCC.getOperand(2));
5491     }
5492   }
5493
5494   // If we can fold this based on the true/false value, do so.
5495   if (SimplifySelectOps(N, N2, N3))
5496     return SDValue(N, 0);  // Don't revisit N.
5497
5498   // fold select_cc into other things, such as min/max/abs
5499   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5500 }
5501
5502 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5503   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5504                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5505                        SDLoc(N));
5506 }
5507
5508 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5509 // dag node into a ConstantSDNode or a build_vector of constants.
5510 // This function is called by the DAGCombiner when visiting sext/zext/aext
5511 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5512 // Vector extends are not folded if operations are legal; this is to
5513 // avoid introducing illegal build_vector dag nodes.
5514 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5515                                          SelectionDAG &DAG, bool LegalTypes,
5516                                          bool LegalOperations) {
5517   unsigned Opcode = N->getOpcode();
5518   SDValue N0 = N->getOperand(0);
5519   EVT VT = N->getValueType(0);
5520
5521   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5522          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5523
5524   // fold (sext c1) -> c1
5525   // fold (zext c1) -> c1
5526   // fold (aext c1) -> c1
5527   if (isa<ConstantSDNode>(N0))
5528     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5529
5530   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5531   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5532   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5533   EVT SVT = VT.getScalarType();
5534   if (!(VT.isVector() &&
5535       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5536       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5537     return nullptr;
5538
5539   // We can fold this node into a build_vector.
5540   unsigned VTBits = SVT.getSizeInBits();
5541   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5542   unsigned ShAmt = VTBits - EVTBits;
5543   SmallVector<SDValue, 8> Elts;
5544   unsigned NumElts = N0->getNumOperands();
5545   SDLoc DL(N);
5546
5547   for (unsigned i=0; i != NumElts; ++i) {
5548     SDValue Op = N0->getOperand(i);
5549     if (Op->getOpcode() == ISD::UNDEF) {
5550       Elts.push_back(DAG.getUNDEF(SVT));
5551       continue;
5552     }
5553
5554     SDLoc DL(Op);
5555     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5556     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5557     if (Opcode == ISD::SIGN_EXTEND)
5558       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5559                                      DL, SVT));
5560     else
5561       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5562                                      DL, SVT));
5563   }
5564
5565   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5566 }
5567
5568 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5569 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5570 // transformation. Returns true if extension are possible and the above
5571 // mentioned transformation is profitable.
5572 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5573                                     unsigned ExtOpc,
5574                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5575                                     const TargetLowering &TLI) {
5576   bool HasCopyToRegUses = false;
5577   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5578   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5579                             UE = N0.getNode()->use_end();
5580        UI != UE; ++UI) {
5581     SDNode *User = *UI;
5582     if (User == N)
5583       continue;
5584     if (UI.getUse().getResNo() != N0.getResNo())
5585       continue;
5586     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5587     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5588       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5589       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5590         // Sign bits will be lost after a zext.
5591         return false;
5592       bool Add = false;
5593       for (unsigned i = 0; i != 2; ++i) {
5594         SDValue UseOp = User->getOperand(i);
5595         if (UseOp == N0)
5596           continue;
5597         if (!isa<ConstantSDNode>(UseOp))
5598           return false;
5599         Add = true;
5600       }
5601       if (Add)
5602         ExtendNodes.push_back(User);
5603       continue;
5604     }
5605     // If truncates aren't free and there are users we can't
5606     // extend, it isn't worthwhile.
5607     if (!isTruncFree)
5608       return false;
5609     // Remember if this value is live-out.
5610     if (User->getOpcode() == ISD::CopyToReg)
5611       HasCopyToRegUses = true;
5612   }
5613
5614   if (HasCopyToRegUses) {
5615     bool BothLiveOut = false;
5616     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5617          UI != UE; ++UI) {
5618       SDUse &Use = UI.getUse();
5619       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5620         BothLiveOut = true;
5621         break;
5622       }
5623     }
5624     if (BothLiveOut)
5625       // Both unextended and extended values are live out. There had better be
5626       // a good reason for the transformation.
5627       return ExtendNodes.size();
5628   }
5629   return true;
5630 }
5631
5632 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5633                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5634                                   ISD::NodeType ExtType) {
5635   // Extend SetCC uses if necessary.
5636   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5637     SDNode *SetCC = SetCCs[i];
5638     SmallVector<SDValue, 4> Ops;
5639
5640     for (unsigned j = 0; j != 2; ++j) {
5641       SDValue SOp = SetCC->getOperand(j);
5642       if (SOp == Trunc)
5643         Ops.push_back(ExtLoad);
5644       else
5645         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5646     }
5647
5648     Ops.push_back(SetCC->getOperand(2));
5649     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5650   }
5651 }
5652
5653 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5654 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5655   SDValue N0 = N->getOperand(0);
5656   EVT DstVT = N->getValueType(0);
5657   EVT SrcVT = N0.getValueType();
5658
5659   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5660           N->getOpcode() == ISD::ZERO_EXTEND) &&
5661          "Unexpected node type (not an extend)!");
5662
5663   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5664   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5665   //   (v8i32 (sext (v8i16 (load x))))
5666   // into:
5667   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5668   //                          (v4i32 (sextload (x + 16)))))
5669   // Where uses of the original load, i.e.:
5670   //   (v8i16 (load x))
5671   // are replaced with:
5672   //   (v8i16 (truncate
5673   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5674   //                            (v4i32 (sextload (x + 16)))))))
5675   //
5676   // This combine is only applicable to illegal, but splittable, vectors.
5677   // All legal types, and illegal non-vector types, are handled elsewhere.
5678   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5679   //
5680   if (N0->getOpcode() != ISD::LOAD)
5681     return SDValue();
5682
5683   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5684
5685   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5686       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5687       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5688     return SDValue();
5689
5690   SmallVector<SDNode *, 4> SetCCs;
5691   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5692     return SDValue();
5693
5694   ISD::LoadExtType ExtType =
5695       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5696
5697   // Try to split the vector types to get down to legal types.
5698   EVT SplitSrcVT = SrcVT;
5699   EVT SplitDstVT = DstVT;
5700   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5701          SplitSrcVT.getVectorNumElements() > 1) {
5702     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5703     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5704   }
5705
5706   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5707     return SDValue();
5708
5709   SDLoc DL(N);
5710   const unsigned NumSplits =
5711       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5712   const unsigned Stride = SplitSrcVT.getStoreSize();
5713   SmallVector<SDValue, 4> Loads;
5714   SmallVector<SDValue, 4> Chains;
5715
5716   SDValue BasePtr = LN0->getBasePtr();
5717   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5718     const unsigned Offset = Idx * Stride;
5719     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5720
5721     SDValue SplitLoad = DAG.getExtLoad(
5722         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5723         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5724         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5725         Align, LN0->getAAInfo());
5726
5727     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5728                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5729
5730     Loads.push_back(SplitLoad.getValue(0));
5731     Chains.push_back(SplitLoad.getValue(1));
5732   }
5733
5734   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5735   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5736
5737   CombineTo(N, NewValue);
5738
5739   // Replace uses of the original load (before extension)
5740   // with a truncate of the concatenated sextloaded vectors.
5741   SDValue Trunc =
5742       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5743   CombineTo(N0.getNode(), Trunc, NewChain);
5744   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5745                   (ISD::NodeType)N->getOpcode());
5746   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5747 }
5748
5749 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5750   SDValue N0 = N->getOperand(0);
5751   EVT VT = N->getValueType(0);
5752
5753   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5754                                               LegalOperations))
5755     return SDValue(Res, 0);
5756
5757   // fold (sext (sext x)) -> (sext x)
5758   // fold (sext (aext x)) -> (sext x)
5759   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5760     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5761                        N0.getOperand(0));
5762
5763   if (N0.getOpcode() == ISD::TRUNCATE) {
5764     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5765     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5766     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5767     if (NarrowLoad.getNode()) {
5768       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5769       if (NarrowLoad.getNode() != N0.getNode()) {
5770         CombineTo(N0.getNode(), NarrowLoad);
5771         // CombineTo deleted the truncate, if needed, but not what's under it.
5772         AddToWorklist(oye);
5773       }
5774       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5775     }
5776
5777     // See if the value being truncated is already sign extended.  If so, just
5778     // eliminate the trunc/sext pair.
5779     SDValue Op = N0.getOperand(0);
5780     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5781     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5782     unsigned DestBits = VT.getScalarType().getSizeInBits();
5783     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5784
5785     if (OpBits == DestBits) {
5786       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5787       // bits, it is already ready.
5788       if (NumSignBits > DestBits-MidBits)
5789         return Op;
5790     } else if (OpBits < DestBits) {
5791       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5792       // bits, just sext from i32.
5793       if (NumSignBits > OpBits-MidBits)
5794         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5795     } else {
5796       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5797       // bits, just truncate to i32.
5798       if (NumSignBits > OpBits-MidBits)
5799         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5800     }
5801
5802     // fold (sext (truncate x)) -> (sextinreg x).
5803     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5804                                                  N0.getValueType())) {
5805       if (OpBits < DestBits)
5806         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5807       else if (OpBits > DestBits)
5808         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5809       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5810                          DAG.getValueType(N0.getValueType()));
5811     }
5812   }
5813
5814   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5815   // Only generate vector extloads when 1) they're legal, and 2) they are
5816   // deemed desirable by the target.
5817   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5818       ((!LegalOperations && !VT.isVector() &&
5819         !cast<LoadSDNode>(N0)->isVolatile()) ||
5820        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5821     bool DoXform = true;
5822     SmallVector<SDNode*, 4> SetCCs;
5823     if (!N0.hasOneUse())
5824       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5825     if (VT.isVector())
5826       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5827     if (DoXform) {
5828       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5829       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5830                                        LN0->getChain(),
5831                                        LN0->getBasePtr(), N0.getValueType(),
5832                                        LN0->getMemOperand());
5833       CombineTo(N, ExtLoad);
5834       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5835                                   N0.getValueType(), ExtLoad);
5836       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5837       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5838                       ISD::SIGN_EXTEND);
5839       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5840     }
5841   }
5842
5843   // fold (sext (load x)) to multiple smaller sextloads.
5844   // Only on illegal but splittable vectors.
5845   if (SDValue ExtLoad = CombineExtLoad(N))
5846     return ExtLoad;
5847
5848   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5849   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5850   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5851       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5852     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5853     EVT MemVT = LN0->getMemoryVT();
5854     if ((!LegalOperations && !LN0->isVolatile()) ||
5855         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5856       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5857                                        LN0->getChain(),
5858                                        LN0->getBasePtr(), MemVT,
5859                                        LN0->getMemOperand());
5860       CombineTo(N, ExtLoad);
5861       CombineTo(N0.getNode(),
5862                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5863                             N0.getValueType(), ExtLoad),
5864                 ExtLoad.getValue(1));
5865       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5866     }
5867   }
5868
5869   // fold (sext (and/or/xor (load x), cst)) ->
5870   //      (and/or/xor (sextload x), (sext cst))
5871   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5872        N0.getOpcode() == ISD::XOR) &&
5873       isa<LoadSDNode>(N0.getOperand(0)) &&
5874       N0.getOperand(1).getOpcode() == ISD::Constant &&
5875       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5876       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5877     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5878     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5879       bool DoXform = true;
5880       SmallVector<SDNode*, 4> SetCCs;
5881       if (!N0.hasOneUse())
5882         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5883                                           SetCCs, TLI);
5884       if (DoXform) {
5885         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5886                                          LN0->getChain(), LN0->getBasePtr(),
5887                                          LN0->getMemoryVT(),
5888                                          LN0->getMemOperand());
5889         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5890         Mask = Mask.sext(VT.getSizeInBits());
5891         SDLoc DL(N);
5892         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5893                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5894         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5895                                     SDLoc(N0.getOperand(0)),
5896                                     N0.getOperand(0).getValueType(), ExtLoad);
5897         CombineTo(N, And);
5898         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5899         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5900                         ISD::SIGN_EXTEND);
5901         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5902       }
5903     }
5904   }
5905
5906   if (N0.getOpcode() == ISD::SETCC) {
5907     EVT N0VT = N0.getOperand(0).getValueType();
5908     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5909     // Only do this before legalize for now.
5910     if (VT.isVector() && !LegalOperations &&
5911         TLI.getBooleanContents(N0VT) ==
5912             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5913       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5914       // of the same size as the compared operands. Only optimize sext(setcc())
5915       // if this is the case.
5916       EVT SVT = getSetCCResultType(N0VT);
5917
5918       // We know that the # elements of the results is the same as the
5919       // # elements of the compare (and the # elements of the compare result
5920       // for that matter).  Check to see that they are the same size.  If so,
5921       // we know that the element size of the sext'd result matches the
5922       // element size of the compare operands.
5923       if (VT.getSizeInBits() == SVT.getSizeInBits())
5924         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5925                              N0.getOperand(1),
5926                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5927
5928       // If the desired elements are smaller or larger than the source
5929       // elements we can use a matching integer vector type and then
5930       // truncate/sign extend
5931       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5932       if (SVT == MatchingVectorType) {
5933         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5934                                N0.getOperand(0), N0.getOperand(1),
5935                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5936         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5937       }
5938     }
5939
5940     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5941     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5942     SDLoc DL(N);
5943     SDValue NegOne =
5944       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5945     SDValue SCC =
5946       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5947                        NegOne, DAG.getConstant(0, DL, VT),
5948                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5949     if (SCC.getNode()) return SCC;
5950
5951     if (!VT.isVector()) {
5952       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5953       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5954         SDLoc DL(N);
5955         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5956         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5957                                      N0.getOperand(0), N0.getOperand(1), CC);
5958         return DAG.getSelect(DL, VT, SetCC,
5959                              NegOne, DAG.getConstant(0, DL, VT));
5960       }
5961     }
5962   }
5963
5964   // fold (sext x) -> (zext x) if the sign bit is known zero.
5965   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5966       DAG.SignBitIsZero(N0))
5967     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5968
5969   return SDValue();
5970 }
5971
5972 // isTruncateOf - If N is a truncate of some other value, return true, record
5973 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5974 // This function computes KnownZero to avoid a duplicated call to
5975 // computeKnownBits in the caller.
5976 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5977                          APInt &KnownZero) {
5978   APInt KnownOne;
5979   if (N->getOpcode() == ISD::TRUNCATE) {
5980     Op = N->getOperand(0);
5981     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5982     return true;
5983   }
5984
5985   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5986       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5987     return false;
5988
5989   SDValue Op0 = N->getOperand(0);
5990   SDValue Op1 = N->getOperand(1);
5991   assert(Op0.getValueType() == Op1.getValueType());
5992
5993   if (isNullConstant(Op0))
5994     Op = Op1;
5995   else if (isNullConstant(Op1))
5996     Op = Op0;
5997   else
5998     return false;
5999
6000   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6001
6002   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6003     return false;
6004
6005   return true;
6006 }
6007
6008 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6009   SDValue N0 = N->getOperand(0);
6010   EVT VT = N->getValueType(0);
6011
6012   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6013                                               LegalOperations))
6014     return SDValue(Res, 0);
6015
6016   // fold (zext (zext x)) -> (zext x)
6017   // fold (zext (aext x)) -> (zext x)
6018   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6019     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6020                        N0.getOperand(0));
6021
6022   // fold (zext (truncate x)) -> (zext x) or
6023   //      (zext (truncate x)) -> (truncate x)
6024   // This is valid when the truncated bits of x are already zero.
6025   // FIXME: We should extend this to work for vectors too.
6026   SDValue Op;
6027   APInt KnownZero;
6028   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6029     APInt TruncatedBits =
6030       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6031       APInt(Op.getValueSizeInBits(), 0) :
6032       APInt::getBitsSet(Op.getValueSizeInBits(),
6033                         N0.getValueSizeInBits(),
6034                         std::min(Op.getValueSizeInBits(),
6035                                  VT.getSizeInBits()));
6036     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6037       if (VT.bitsGT(Op.getValueType()))
6038         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6039       if (VT.bitsLT(Op.getValueType()))
6040         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6041
6042       return Op;
6043     }
6044   }
6045
6046   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6047   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6048   if (N0.getOpcode() == ISD::TRUNCATE) {
6049     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6050     if (NarrowLoad.getNode()) {
6051       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6052       if (NarrowLoad.getNode() != N0.getNode()) {
6053         CombineTo(N0.getNode(), NarrowLoad);
6054         // CombineTo deleted the truncate, if needed, but not what's under it.
6055         AddToWorklist(oye);
6056       }
6057       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6058     }
6059   }
6060
6061   // fold (zext (truncate x)) -> (and x, mask)
6062   if (N0.getOpcode() == ISD::TRUNCATE &&
6063       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6064
6065     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6066     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6067     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6068     if (NarrowLoad.getNode()) {
6069       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6070       if (NarrowLoad.getNode() != N0.getNode()) {
6071         CombineTo(N0.getNode(), NarrowLoad);
6072         // CombineTo deleted the truncate, if needed, but not what's under it.
6073         AddToWorklist(oye);
6074       }
6075       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6076     }
6077
6078     SDValue Op = N0.getOperand(0);
6079     if (Op.getValueType().bitsLT(VT)) {
6080       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6081       AddToWorklist(Op.getNode());
6082     } else if (Op.getValueType().bitsGT(VT)) {
6083       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6084       AddToWorklist(Op.getNode());
6085     }
6086     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6087                                   N0.getValueType().getScalarType());
6088   }
6089
6090   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6091   // if either of the casts is not free.
6092   if (N0.getOpcode() == ISD::AND &&
6093       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6094       N0.getOperand(1).getOpcode() == ISD::Constant &&
6095       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6096                            N0.getValueType()) ||
6097        !TLI.isZExtFree(N0.getValueType(), VT))) {
6098     SDValue X = N0.getOperand(0).getOperand(0);
6099     if (X.getValueType().bitsLT(VT)) {
6100       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6101     } else if (X.getValueType().bitsGT(VT)) {
6102       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6103     }
6104     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6105     Mask = Mask.zext(VT.getSizeInBits());
6106     SDLoc DL(N);
6107     return DAG.getNode(ISD::AND, DL, VT,
6108                        X, DAG.getConstant(Mask, DL, VT));
6109   }
6110
6111   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6112   // Only generate vector extloads when 1) they're legal, and 2) they are
6113   // deemed desirable by the target.
6114   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6115       ((!LegalOperations && !VT.isVector() &&
6116         !cast<LoadSDNode>(N0)->isVolatile()) ||
6117        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6118     bool DoXform = true;
6119     SmallVector<SDNode*, 4> SetCCs;
6120     if (!N0.hasOneUse())
6121       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6122     if (VT.isVector())
6123       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6124     if (DoXform) {
6125       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6126       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6127                                        LN0->getChain(),
6128                                        LN0->getBasePtr(), N0.getValueType(),
6129                                        LN0->getMemOperand());
6130       CombineTo(N, ExtLoad);
6131       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6132                                   N0.getValueType(), ExtLoad);
6133       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6134
6135       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6136                       ISD::ZERO_EXTEND);
6137       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6138     }
6139   }
6140
6141   // fold (zext (load x)) to multiple smaller zextloads.
6142   // Only on illegal but splittable vectors.
6143   if (SDValue ExtLoad = CombineExtLoad(N))
6144     return ExtLoad;
6145
6146   // fold (zext (and/or/xor (load x), cst)) ->
6147   //      (and/or/xor (zextload x), (zext cst))
6148   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6149        N0.getOpcode() == ISD::XOR) &&
6150       isa<LoadSDNode>(N0.getOperand(0)) &&
6151       N0.getOperand(1).getOpcode() == ISD::Constant &&
6152       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6153       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6154     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6155     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6156       bool DoXform = true;
6157       SmallVector<SDNode*, 4> SetCCs;
6158       if (!N0.hasOneUse())
6159         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6160                                           SetCCs, TLI);
6161       if (DoXform) {
6162         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6163                                          LN0->getChain(), LN0->getBasePtr(),
6164                                          LN0->getMemoryVT(),
6165                                          LN0->getMemOperand());
6166         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6167         Mask = Mask.zext(VT.getSizeInBits());
6168         SDLoc DL(N);
6169         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6170                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6171         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6172                                     SDLoc(N0.getOperand(0)),
6173                                     N0.getOperand(0).getValueType(), ExtLoad);
6174         CombineTo(N, And);
6175         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6176         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6177                         ISD::ZERO_EXTEND);
6178         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6179       }
6180     }
6181   }
6182
6183   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6184   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6185   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6186       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6187     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6188     EVT MemVT = LN0->getMemoryVT();
6189     if ((!LegalOperations && !LN0->isVolatile()) ||
6190         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6191       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6192                                        LN0->getChain(),
6193                                        LN0->getBasePtr(), MemVT,
6194                                        LN0->getMemOperand());
6195       CombineTo(N, ExtLoad);
6196       CombineTo(N0.getNode(),
6197                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6198                             ExtLoad),
6199                 ExtLoad.getValue(1));
6200       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6201     }
6202   }
6203
6204   if (N0.getOpcode() == ISD::SETCC) {
6205     if (!LegalOperations && VT.isVector() &&
6206         N0.getValueType().getVectorElementType() == MVT::i1) {
6207       EVT N0VT = N0.getOperand(0).getValueType();
6208       if (getSetCCResultType(N0VT) == N0.getValueType())
6209         return SDValue();
6210
6211       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6212       // Only do this before legalize for now.
6213       EVT EltVT = VT.getVectorElementType();
6214       SDLoc DL(N);
6215       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6216                                     DAG.getConstant(1, DL, EltVT));
6217       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6218         // We know that the # elements of the results is the same as the
6219         // # elements of the compare (and the # elements of the compare result
6220         // for that matter).  Check to see that they are the same size.  If so,
6221         // we know that the element size of the sext'd result matches the
6222         // element size of the compare operands.
6223         return DAG.getNode(ISD::AND, DL, VT,
6224                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6225                                          N0.getOperand(1),
6226                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6227                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6228                                        OneOps));
6229
6230       // If the desired elements are smaller or larger than the source
6231       // elements we can use a matching integer vector type and then
6232       // truncate/sign extend
6233       EVT MatchingElementType =
6234         EVT::getIntegerVT(*DAG.getContext(),
6235                           N0VT.getScalarType().getSizeInBits());
6236       EVT MatchingVectorType =
6237         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6238                          N0VT.getVectorNumElements());
6239       SDValue VsetCC =
6240         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6241                       N0.getOperand(1),
6242                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6243       return DAG.getNode(ISD::AND, DL, VT,
6244                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6245                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6246     }
6247
6248     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6249     SDLoc DL(N);
6250     SDValue SCC =
6251       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6252                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6253                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6254     if (SCC.getNode()) return SCC;
6255   }
6256
6257   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6258   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6259       isa<ConstantSDNode>(N0.getOperand(1)) &&
6260       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6261       N0.hasOneUse()) {
6262     SDValue ShAmt = N0.getOperand(1);
6263     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6264     if (N0.getOpcode() == ISD::SHL) {
6265       SDValue InnerZExt = N0.getOperand(0);
6266       // If the original shl may be shifting out bits, do not perform this
6267       // transformation.
6268       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6269         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6270       if (ShAmtVal > KnownZeroBits)
6271         return SDValue();
6272     }
6273
6274     SDLoc DL(N);
6275
6276     // Ensure that the shift amount is wide enough for the shifted value.
6277     if (VT.getSizeInBits() >= 256)
6278       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6279
6280     return DAG.getNode(N0.getOpcode(), DL, VT,
6281                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6282                        ShAmt);
6283   }
6284
6285   return SDValue();
6286 }
6287
6288 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6289   SDValue N0 = N->getOperand(0);
6290   EVT VT = N->getValueType(0);
6291
6292   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6293                                               LegalOperations))
6294     return SDValue(Res, 0);
6295
6296   // fold (aext (aext x)) -> (aext x)
6297   // fold (aext (zext x)) -> (zext x)
6298   // fold (aext (sext x)) -> (sext x)
6299   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6300       N0.getOpcode() == ISD::ZERO_EXTEND ||
6301       N0.getOpcode() == ISD::SIGN_EXTEND)
6302     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6303
6304   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6305   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6306   if (N0.getOpcode() == ISD::TRUNCATE) {
6307     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6308     if (NarrowLoad.getNode()) {
6309       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6310       if (NarrowLoad.getNode() != N0.getNode()) {
6311         CombineTo(N0.getNode(), NarrowLoad);
6312         // CombineTo deleted the truncate, if needed, but not what's under it.
6313         AddToWorklist(oye);
6314       }
6315       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6316     }
6317   }
6318
6319   // fold (aext (truncate x))
6320   if (N0.getOpcode() == ISD::TRUNCATE) {
6321     SDValue TruncOp = N0.getOperand(0);
6322     if (TruncOp.getValueType() == VT)
6323       return TruncOp; // x iff x size == zext size.
6324     if (TruncOp.getValueType().bitsGT(VT))
6325       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6326     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6327   }
6328
6329   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6330   // if the trunc is not free.
6331   if (N0.getOpcode() == ISD::AND &&
6332       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6333       N0.getOperand(1).getOpcode() == ISD::Constant &&
6334       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6335                           N0.getValueType())) {
6336     SDValue X = N0.getOperand(0).getOperand(0);
6337     if (X.getValueType().bitsLT(VT)) {
6338       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6339     } else if (X.getValueType().bitsGT(VT)) {
6340       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6341     }
6342     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6343     Mask = Mask.zext(VT.getSizeInBits());
6344     SDLoc DL(N);
6345     return DAG.getNode(ISD::AND, DL, VT,
6346                        X, DAG.getConstant(Mask, DL, VT));
6347   }
6348
6349   // fold (aext (load x)) -> (aext (truncate (extload x)))
6350   // None of the supported targets knows how to perform load and any_ext
6351   // on vectors in one instruction.  We only perform this transformation on
6352   // scalars.
6353   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6354       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6355       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6356     bool DoXform = true;
6357     SmallVector<SDNode*, 4> SetCCs;
6358     if (!N0.hasOneUse())
6359       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6360     if (DoXform) {
6361       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6362       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6363                                        LN0->getChain(),
6364                                        LN0->getBasePtr(), N0.getValueType(),
6365                                        LN0->getMemOperand());
6366       CombineTo(N, ExtLoad);
6367       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6368                                   N0.getValueType(), ExtLoad);
6369       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6370       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6371                       ISD::ANY_EXTEND);
6372       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6373     }
6374   }
6375
6376   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6377   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6378   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6379   if (N0.getOpcode() == ISD::LOAD &&
6380       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6381       N0.hasOneUse()) {
6382     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6383     ISD::LoadExtType ExtType = LN0->getExtensionType();
6384     EVT MemVT = LN0->getMemoryVT();
6385     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6386       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6387                                        VT, LN0->getChain(), LN0->getBasePtr(),
6388                                        MemVT, LN0->getMemOperand());
6389       CombineTo(N, ExtLoad);
6390       CombineTo(N0.getNode(),
6391                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6392                             N0.getValueType(), ExtLoad),
6393                 ExtLoad.getValue(1));
6394       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6395     }
6396   }
6397
6398   if (N0.getOpcode() == ISD::SETCC) {
6399     // For vectors:
6400     // aext(setcc) -> vsetcc
6401     // aext(setcc) -> truncate(vsetcc)
6402     // aext(setcc) -> aext(vsetcc)
6403     // Only do this before legalize for now.
6404     if (VT.isVector() && !LegalOperations) {
6405       EVT N0VT = N0.getOperand(0).getValueType();
6406         // We know that the # elements of the results is the same as the
6407         // # elements of the compare (and the # elements of the compare result
6408         // for that matter).  Check to see that they are the same size.  If so,
6409         // we know that the element size of the sext'd result matches the
6410         // element size of the compare operands.
6411       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6412         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6413                              N0.getOperand(1),
6414                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6415       // If the desired elements are smaller or larger than the source
6416       // elements we can use a matching integer vector type and then
6417       // truncate/any extend
6418       else {
6419         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6420         SDValue VsetCC =
6421           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6422                         N0.getOperand(1),
6423                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6424         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6425       }
6426     }
6427
6428     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6429     SDLoc DL(N);
6430     SDValue SCC =
6431       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6432                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6433                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6434     if (SCC.getNode())
6435       return SCC;
6436   }
6437
6438   return SDValue();
6439 }
6440
6441 /// See if the specified operand can be simplified with the knowledge that only
6442 /// the bits specified by Mask are used.  If so, return the simpler operand,
6443 /// otherwise return a null SDValue.
6444 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6445   switch (V.getOpcode()) {
6446   default: break;
6447   case ISD::Constant: {
6448     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6449     assert(CV && "Const value should be ConstSDNode.");
6450     const APInt &CVal = CV->getAPIntValue();
6451     APInt NewVal = CVal & Mask;
6452     if (NewVal != CVal)
6453       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6454     break;
6455   }
6456   case ISD::OR:
6457   case ISD::XOR:
6458     // If the LHS or RHS don't contribute bits to the or, drop them.
6459     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6460       return V.getOperand(1);
6461     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6462       return V.getOperand(0);
6463     break;
6464   case ISD::SRL:
6465     // Only look at single-use SRLs.
6466     if (!V.getNode()->hasOneUse())
6467       break;
6468     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6469       // See if we can recursively simplify the LHS.
6470       unsigned Amt = RHSC->getZExtValue();
6471
6472       // Watch out for shift count overflow though.
6473       if (Amt >= Mask.getBitWidth()) break;
6474       APInt NewMask = Mask << Amt;
6475       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6476       if (SimplifyLHS.getNode())
6477         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6478                            SimplifyLHS, V.getOperand(1));
6479     }
6480   }
6481   return SDValue();
6482 }
6483
6484 /// If the result of a wider load is shifted to right of N  bits and then
6485 /// truncated to a narrower type and where N is a multiple of number of bits of
6486 /// the narrower type, transform it to a narrower load from address + N / num of
6487 /// bits of new type. If the result is to be extended, also fold the extension
6488 /// to form a extending load.
6489 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6490   unsigned Opc = N->getOpcode();
6491
6492   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6493   SDValue N0 = N->getOperand(0);
6494   EVT VT = N->getValueType(0);
6495   EVT ExtVT = VT;
6496
6497   // This transformation isn't valid for vector loads.
6498   if (VT.isVector())
6499     return SDValue();
6500
6501   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6502   // extended to VT.
6503   if (Opc == ISD::SIGN_EXTEND_INREG) {
6504     ExtType = ISD::SEXTLOAD;
6505     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6506   } else if (Opc == ISD::SRL) {
6507     // Another special-case: SRL is basically zero-extending a narrower value.
6508     ExtType = ISD::ZEXTLOAD;
6509     N0 = SDValue(N, 0);
6510     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6511     if (!N01) return SDValue();
6512     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6513                               VT.getSizeInBits() - N01->getZExtValue());
6514   }
6515   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6516     return SDValue();
6517
6518   unsigned EVTBits = ExtVT.getSizeInBits();
6519
6520   // Do not generate loads of non-round integer types since these can
6521   // be expensive (and would be wrong if the type is not byte sized).
6522   if (!ExtVT.isRound())
6523     return SDValue();
6524
6525   unsigned ShAmt = 0;
6526   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6527     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6528       ShAmt = N01->getZExtValue();
6529       // Is the shift amount a multiple of size of VT?
6530       if ((ShAmt & (EVTBits-1)) == 0) {
6531         N0 = N0.getOperand(0);
6532         // Is the load width a multiple of size of VT?
6533         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6534           return SDValue();
6535       }
6536
6537       // At this point, we must have a load or else we can't do the transform.
6538       if (!isa<LoadSDNode>(N0)) return SDValue();
6539
6540       // Because a SRL must be assumed to *need* to zero-extend the high bits
6541       // (as opposed to anyext the high bits), we can't combine the zextload
6542       // lowering of SRL and an sextload.
6543       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6544         return SDValue();
6545
6546       // If the shift amount is larger than the input type then we're not
6547       // accessing any of the loaded bytes.  If the load was a zextload/extload
6548       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6549       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6550         return SDValue();
6551     }
6552   }
6553
6554   // If the load is shifted left (and the result isn't shifted back right),
6555   // we can fold the truncate through the shift.
6556   unsigned ShLeftAmt = 0;
6557   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6558       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6559     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6560       ShLeftAmt = N01->getZExtValue();
6561       N0 = N0.getOperand(0);
6562     }
6563   }
6564
6565   // If we haven't found a load, we can't narrow it.  Don't transform one with
6566   // multiple uses, this would require adding a new load.
6567   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6568     return SDValue();
6569
6570   // Don't change the width of a volatile load.
6571   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6572   if (LN0->isVolatile())
6573     return SDValue();
6574
6575   // Verify that we are actually reducing a load width here.
6576   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6577     return SDValue();
6578
6579   // For the transform to be legal, the load must produce only two values
6580   // (the value loaded and the chain).  Don't transform a pre-increment
6581   // load, for example, which produces an extra value.  Otherwise the
6582   // transformation is not equivalent, and the downstream logic to replace
6583   // uses gets things wrong.
6584   if (LN0->getNumValues() > 2)
6585     return SDValue();
6586
6587   // If the load that we're shrinking is an extload and we're not just
6588   // discarding the extension we can't simply shrink the load. Bail.
6589   // TODO: It would be possible to merge the extensions in some cases.
6590   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6591       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6592     return SDValue();
6593
6594   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6595     return SDValue();
6596
6597   EVT PtrType = N0.getOperand(1).getValueType();
6598
6599   if (PtrType == MVT::Untyped || PtrType.isExtended())
6600     // It's not possible to generate a constant of extended or untyped type.
6601     return SDValue();
6602
6603   // For big endian targets, we need to adjust the offset to the pointer to
6604   // load the correct bytes.
6605   if (TLI.isBigEndian()) {
6606     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6607     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6608     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6609   }
6610
6611   uint64_t PtrOff = ShAmt / 8;
6612   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6613   SDLoc DL(LN0);
6614   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6615                                PtrType, LN0->getBasePtr(),
6616                                DAG.getConstant(PtrOff, DL, PtrType));
6617   AddToWorklist(NewPtr.getNode());
6618
6619   SDValue Load;
6620   if (ExtType == ISD::NON_EXTLOAD)
6621     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6622                         LN0->getPointerInfo().getWithOffset(PtrOff),
6623                         LN0->isVolatile(), LN0->isNonTemporal(),
6624                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6625   else
6626     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6627                           LN0->getPointerInfo().getWithOffset(PtrOff),
6628                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6629                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6630
6631   // Replace the old load's chain with the new load's chain.
6632   WorklistRemover DeadNodes(*this);
6633   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6634
6635   // Shift the result left, if we've swallowed a left shift.
6636   SDValue Result = Load;
6637   if (ShLeftAmt != 0) {
6638     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6639     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6640       ShImmTy = VT;
6641     // If the shift amount is as large as the result size (but, presumably,
6642     // no larger than the source) then the useful bits of the result are
6643     // zero; we can't simply return the shortened shift, because the result
6644     // of that operation is undefined.
6645     SDLoc DL(N0);
6646     if (ShLeftAmt >= VT.getSizeInBits())
6647       Result = DAG.getConstant(0, DL, VT);
6648     else
6649       Result = DAG.getNode(ISD::SHL, DL, VT,
6650                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6651   }
6652
6653   // Return the new loaded value.
6654   return Result;
6655 }
6656
6657 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6658   SDValue N0 = N->getOperand(0);
6659   SDValue N1 = N->getOperand(1);
6660   EVT VT = N->getValueType(0);
6661   EVT EVT = cast<VTSDNode>(N1)->getVT();
6662   unsigned VTBits = VT.getScalarType().getSizeInBits();
6663   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6664
6665   // fold (sext_in_reg c1) -> c1
6666   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6667     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6668
6669   // If the input is already sign extended, just drop the extension.
6670   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6671     return N0;
6672
6673   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6674   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6675       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6676     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6677                        N0.getOperand(0), N1);
6678
6679   // fold (sext_in_reg (sext x)) -> (sext x)
6680   // fold (sext_in_reg (aext x)) -> (sext x)
6681   // if x is small enough.
6682   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6683     SDValue N00 = N0.getOperand(0);
6684     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6685         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6686       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6687   }
6688
6689   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6690   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6691     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6692
6693   // fold operands of sext_in_reg based on knowledge that the top bits are not
6694   // demanded.
6695   if (SimplifyDemandedBits(SDValue(N, 0)))
6696     return SDValue(N, 0);
6697
6698   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6699   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6700   SDValue NarrowLoad = ReduceLoadWidth(N);
6701   if (NarrowLoad.getNode())
6702     return NarrowLoad;
6703
6704   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6705   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6706   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6707   if (N0.getOpcode() == ISD::SRL) {
6708     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6709       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6710         // We can turn this into an SRA iff the input to the SRL is already sign
6711         // extended enough.
6712         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6713         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6714           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6715                              N0.getOperand(0), N0.getOperand(1));
6716       }
6717   }
6718
6719   // fold (sext_inreg (extload x)) -> (sextload x)
6720   if (ISD::isEXTLoad(N0.getNode()) &&
6721       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6722       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6723       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6724        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6725     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6726     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6727                                      LN0->getChain(),
6728                                      LN0->getBasePtr(), EVT,
6729                                      LN0->getMemOperand());
6730     CombineTo(N, ExtLoad);
6731     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6732     AddToWorklist(ExtLoad.getNode());
6733     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6734   }
6735   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6736   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6737       N0.hasOneUse() &&
6738       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6739       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6740        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6741     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6742     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6743                                      LN0->getChain(),
6744                                      LN0->getBasePtr(), EVT,
6745                                      LN0->getMemOperand());
6746     CombineTo(N, ExtLoad);
6747     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6748     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6749   }
6750
6751   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6752   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6753     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6754                                        N0.getOperand(1), false);
6755     if (BSwap.getNode())
6756       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6757                          BSwap, N1);
6758   }
6759
6760   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6761   // into a build_vector.
6762   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6763     SmallVector<SDValue, 8> Elts;
6764     unsigned NumElts = N0->getNumOperands();
6765     unsigned ShAmt = VTBits - EVTBits;
6766
6767     for (unsigned i = 0; i != NumElts; ++i) {
6768       SDValue Op = N0->getOperand(i);
6769       if (Op->getOpcode() == ISD::UNDEF) {
6770         Elts.push_back(Op);
6771         continue;
6772       }
6773
6774       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6775       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6776       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6777                                      SDLoc(Op), Op.getValueType()));
6778     }
6779
6780     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6781   }
6782
6783   return SDValue();
6784 }
6785
6786 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6787   SDValue N0 = N->getOperand(0);
6788   EVT VT = N->getValueType(0);
6789   bool isLE = TLI.isLittleEndian();
6790
6791   // noop truncate
6792   if (N0.getValueType() == N->getValueType(0))
6793     return N0;
6794   // fold (truncate c1) -> c1
6795   if (isConstantIntBuildVectorOrConstantInt(N0))
6796     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6797   // fold (truncate (truncate x)) -> (truncate x)
6798   if (N0.getOpcode() == ISD::TRUNCATE)
6799     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6800   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6801   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6802       N0.getOpcode() == ISD::SIGN_EXTEND ||
6803       N0.getOpcode() == ISD::ANY_EXTEND) {
6804     if (N0.getOperand(0).getValueType().bitsLT(VT))
6805       // if the source is smaller than the dest, we still need an extend
6806       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6807                          N0.getOperand(0));
6808     if (N0.getOperand(0).getValueType().bitsGT(VT))
6809       // if the source is larger than the dest, than we just need the truncate
6810       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6811     // if the source and dest are the same type, we can drop both the extend
6812     // and the truncate.
6813     return N0.getOperand(0);
6814   }
6815
6816   // Fold extract-and-trunc into a narrow extract. For example:
6817   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6818   //   i32 y = TRUNCATE(i64 x)
6819   //        -- becomes --
6820   //   v16i8 b = BITCAST (v2i64 val)
6821   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6822   //
6823   // Note: We only run this optimization after type legalization (which often
6824   // creates this pattern) and before operation legalization after which
6825   // we need to be more careful about the vector instructions that we generate.
6826   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6827       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6828
6829     EVT VecTy = N0.getOperand(0).getValueType();
6830     EVT ExTy = N0.getValueType();
6831     EVT TrTy = N->getValueType(0);
6832
6833     unsigned NumElem = VecTy.getVectorNumElements();
6834     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6835
6836     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6837     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6838
6839     SDValue EltNo = N0->getOperand(1);
6840     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6841       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6842       EVT IndexTy = TLI.getVectorIdxTy();
6843       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6844
6845       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6846                               NVT, N0.getOperand(0));
6847
6848       SDLoc DL(N);
6849       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6850                          DL, TrTy, V,
6851                          DAG.getConstant(Index, DL, IndexTy));
6852     }
6853   }
6854
6855   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6856   if (N0.getOpcode() == ISD::SELECT) {
6857     EVT SrcVT = N0.getValueType();
6858     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6859         TLI.isTruncateFree(SrcVT, VT)) {
6860       SDLoc SL(N0);
6861       SDValue Cond = N0.getOperand(0);
6862       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6863       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6864       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6865     }
6866   }
6867
6868   // Fold a series of buildvector, bitcast, and truncate if possible.
6869   // For example fold
6870   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6871   //   (2xi32 (buildvector x, y)).
6872   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6873       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6874       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6875       N0.getOperand(0).hasOneUse()) {
6876
6877     SDValue BuildVect = N0.getOperand(0);
6878     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6879     EVT TruncVecEltTy = VT.getVectorElementType();
6880
6881     // Check that the element types match.
6882     if (BuildVectEltTy == TruncVecEltTy) {
6883       // Now we only need to compute the offset of the truncated elements.
6884       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6885       unsigned TruncVecNumElts = VT.getVectorNumElements();
6886       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6887
6888       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6889              "Invalid number of elements");
6890
6891       SmallVector<SDValue, 8> Opnds;
6892       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6893         Opnds.push_back(BuildVect.getOperand(i));
6894
6895       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6896     }
6897   }
6898
6899   // See if we can simplify the input to this truncate through knowledge that
6900   // only the low bits are being used.
6901   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6902   // Currently we only perform this optimization on scalars because vectors
6903   // may have different active low bits.
6904   if (!VT.isVector()) {
6905     SDValue Shorter =
6906       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6907                                                VT.getSizeInBits()));
6908     if (Shorter.getNode())
6909       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6910   }
6911   // fold (truncate (load x)) -> (smaller load x)
6912   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6913   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6914     SDValue Reduced = ReduceLoadWidth(N);
6915     if (Reduced.getNode())
6916       return Reduced;
6917     // Handle the case where the load remains an extending load even
6918     // after truncation.
6919     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6920       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6921       if (!LN0->isVolatile() &&
6922           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6923         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6924                                          VT, LN0->getChain(), LN0->getBasePtr(),
6925                                          LN0->getMemoryVT(),
6926                                          LN0->getMemOperand());
6927         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6928         return NewLoad;
6929       }
6930     }
6931   }
6932   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6933   // where ... are all 'undef'.
6934   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6935     SmallVector<EVT, 8> VTs;
6936     SDValue V;
6937     unsigned Idx = 0;
6938     unsigned NumDefs = 0;
6939
6940     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6941       SDValue X = N0.getOperand(i);
6942       if (X.getOpcode() != ISD::UNDEF) {
6943         V = X;
6944         Idx = i;
6945         NumDefs++;
6946       }
6947       // Stop if more than one members are non-undef.
6948       if (NumDefs > 1)
6949         break;
6950       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6951                                      VT.getVectorElementType(),
6952                                      X.getValueType().getVectorNumElements()));
6953     }
6954
6955     if (NumDefs == 0)
6956       return DAG.getUNDEF(VT);
6957
6958     if (NumDefs == 1) {
6959       assert(V.getNode() && "The single defined operand is empty!");
6960       SmallVector<SDValue, 8> Opnds;
6961       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6962         if (i != Idx) {
6963           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6964           continue;
6965         }
6966         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6967         AddToWorklist(NV.getNode());
6968         Opnds.push_back(NV);
6969       }
6970       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6971     }
6972   }
6973
6974   // Simplify the operands using demanded-bits information.
6975   if (!VT.isVector() &&
6976       SimplifyDemandedBits(SDValue(N, 0)))
6977     return SDValue(N, 0);
6978
6979   return SDValue();
6980 }
6981
6982 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6983   SDValue Elt = N->getOperand(i);
6984   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6985     return Elt.getNode();
6986   return Elt.getOperand(Elt.getResNo()).getNode();
6987 }
6988
6989 /// build_pair (load, load) -> load
6990 /// if load locations are consecutive.
6991 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6992   assert(N->getOpcode() == ISD::BUILD_PAIR);
6993
6994   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6995   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6996   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6997       LD1->getAddressSpace() != LD2->getAddressSpace())
6998     return SDValue();
6999   EVT LD1VT = LD1->getValueType(0);
7000
7001   if (ISD::isNON_EXTLoad(LD2) &&
7002       LD2->hasOneUse() &&
7003       // If both are volatile this would reduce the number of volatile loads.
7004       // If one is volatile it might be ok, but play conservative and bail out.
7005       !LD1->isVolatile() &&
7006       !LD2->isVolatile() &&
7007       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7008     unsigned Align = LD1->getAlignment();
7009     unsigned NewAlign = TLI.getDataLayout()->
7010       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7011
7012     if (NewAlign <= Align &&
7013         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7014       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7015                          LD1->getBasePtr(), LD1->getPointerInfo(),
7016                          false, false, false, Align);
7017   }
7018
7019   return SDValue();
7020 }
7021
7022 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7023   SDValue N0 = N->getOperand(0);
7024   EVT VT = N->getValueType(0);
7025
7026   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7027   // Only do this before legalize, since afterward the target may be depending
7028   // on the bitconvert.
7029   // First check to see if this is all constant.
7030   if (!LegalTypes &&
7031       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7032       VT.isVector()) {
7033     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7034
7035     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7036     assert(!DestEltVT.isVector() &&
7037            "Element type of vector ValueType must not be vector!");
7038     if (isSimple)
7039       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7040   }
7041
7042   // If the input is a constant, let getNode fold it.
7043   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7044     // If we can't allow illegal operations, we need to check that this is just
7045     // a fp -> int or int -> conversion and that the resulting operation will
7046     // be legal.
7047     if (!LegalOperations ||
7048         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7049          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7050         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7051          TLI.isOperationLegal(ISD::Constant, VT)))
7052       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7053   }
7054
7055   // (conv (conv x, t1), t2) -> (conv x, t2)
7056   if (N0.getOpcode() == ISD::BITCAST)
7057     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7058                        N0.getOperand(0));
7059
7060   // fold (conv (load x)) -> (load (conv*)x)
7061   // If the resultant load doesn't need a higher alignment than the original!
7062   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7063       // Do not change the width of a volatile load.
7064       !cast<LoadSDNode>(N0)->isVolatile() &&
7065       // Do not remove the cast if the types differ in endian layout.
7066       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7067       TLI.hasBigEndianPartOrdering(VT) &&
7068       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7069       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7070     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7071     unsigned Align = TLI.getDataLayout()->
7072       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7073     unsigned OrigAlign = LN0->getAlignment();
7074
7075     if (Align <= OrigAlign) {
7076       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7077                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7078                                  LN0->isVolatile(), LN0->isNonTemporal(),
7079                                  LN0->isInvariant(), OrigAlign,
7080                                  LN0->getAAInfo());
7081       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7082       return Load;
7083     }
7084   }
7085
7086   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7087   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7088   // This often reduces constant pool loads.
7089   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7090        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7091       N0.getNode()->hasOneUse() && VT.isInteger() &&
7092       !VT.isVector() && !N0.getValueType().isVector()) {
7093     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7094                                   N0.getOperand(0));
7095     AddToWorklist(NewConv.getNode());
7096
7097     SDLoc DL(N);
7098     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7099     if (N0.getOpcode() == ISD::FNEG)
7100       return DAG.getNode(ISD::XOR, DL, VT,
7101                          NewConv, DAG.getConstant(SignBit, DL, VT));
7102     assert(N0.getOpcode() == ISD::FABS);
7103     return DAG.getNode(ISD::AND, DL, VT,
7104                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7105   }
7106
7107   // fold (bitconvert (fcopysign cst, x)) ->
7108   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7109   // Note that we don't handle (copysign x, cst) because this can always be
7110   // folded to an fneg or fabs.
7111   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7112       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7113       VT.isInteger() && !VT.isVector()) {
7114     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7115     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7116     if (isTypeLegal(IntXVT)) {
7117       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7118                               IntXVT, N0.getOperand(1));
7119       AddToWorklist(X.getNode());
7120
7121       // If X has a different width than the result/lhs, sext it or truncate it.
7122       unsigned VTWidth = VT.getSizeInBits();
7123       if (OrigXWidth < VTWidth) {
7124         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7125         AddToWorklist(X.getNode());
7126       } else if (OrigXWidth > VTWidth) {
7127         // To get the sign bit in the right place, we have to shift it right
7128         // before truncating.
7129         SDLoc DL(X);
7130         X = DAG.getNode(ISD::SRL, DL,
7131                         X.getValueType(), X,
7132                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7133                                         X.getValueType()));
7134         AddToWorklist(X.getNode());
7135         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7136         AddToWorklist(X.getNode());
7137       }
7138
7139       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7140       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7141                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7142       AddToWorklist(X.getNode());
7143
7144       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7145                                 VT, N0.getOperand(0));
7146       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7147                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7148       AddToWorklist(Cst.getNode());
7149
7150       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7151     }
7152   }
7153
7154   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7155   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7156     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7157     if (CombineLD.getNode())
7158       return CombineLD;
7159   }
7160
7161   // Remove double bitcasts from shuffles - this is often a legacy of
7162   // XformToShuffleWithZero being used to combine bitmaskings (of
7163   // float vectors bitcast to integer vectors) into shuffles.
7164   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7165   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7166       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7167       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7168       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7169     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7170
7171     // If operands are a bitcast, peek through if it casts the original VT.
7172     // If operands are a UNDEF or constant, just bitcast back to original VT.
7173     auto PeekThroughBitcast = [&](SDValue Op) {
7174       if (Op.getOpcode() == ISD::BITCAST &&
7175           Op.getOperand(0)->getValueType(0) == VT)
7176         return SDValue(Op.getOperand(0));
7177       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7178           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7179         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7180       return SDValue();
7181     };
7182
7183     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7184     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7185     if (!(SV0 && SV1))
7186       return SDValue();
7187
7188     int MaskScale =
7189         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7190     SmallVector<int, 8> NewMask;
7191     for (int M : SVN->getMask())
7192       for (int i = 0; i != MaskScale; ++i)
7193         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7194
7195     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7196     if (!LegalMask) {
7197       std::swap(SV0, SV1);
7198       ShuffleVectorSDNode::commuteMask(NewMask);
7199       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7200     }
7201
7202     if (LegalMask)
7203       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7204   }
7205
7206   return SDValue();
7207 }
7208
7209 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7210   EVT VT = N->getValueType(0);
7211   return CombineConsecutiveLoads(N, VT);
7212 }
7213
7214 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7215 /// operands. DstEltVT indicates the destination element value type.
7216 SDValue DAGCombiner::
7217 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7218   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7219
7220   // If this is already the right type, we're done.
7221   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7222
7223   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7224   unsigned DstBitSize = DstEltVT.getSizeInBits();
7225
7226   // If this is a conversion of N elements of one type to N elements of another
7227   // type, convert each element.  This handles FP<->INT cases.
7228   if (SrcBitSize == DstBitSize) {
7229     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7230                               BV->getValueType(0).getVectorNumElements());
7231
7232     // Due to the FP element handling below calling this routine recursively,
7233     // we can end up with a scalar-to-vector node here.
7234     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7235       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7236                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7237                                      DstEltVT, BV->getOperand(0)));
7238
7239     SmallVector<SDValue, 8> Ops;
7240     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7241       SDValue Op = BV->getOperand(i);
7242       // If the vector element type is not legal, the BUILD_VECTOR operands
7243       // are promoted and implicitly truncated.  Make that explicit here.
7244       if (Op.getValueType() != SrcEltVT)
7245         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7246       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7247                                 DstEltVT, Op));
7248       AddToWorklist(Ops.back().getNode());
7249     }
7250     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7251   }
7252
7253   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7254   // handle annoying details of growing/shrinking FP values, we convert them to
7255   // int first.
7256   if (SrcEltVT.isFloatingPoint()) {
7257     // Convert the input float vector to a int vector where the elements are the
7258     // same sizes.
7259     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7260     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7261     SrcEltVT = IntVT;
7262   }
7263
7264   // Now we know the input is an integer vector.  If the output is a FP type,
7265   // convert to integer first, then to FP of the right size.
7266   if (DstEltVT.isFloatingPoint()) {
7267     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7268     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7269
7270     // Next, convert to FP elements of the same size.
7271     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7272   }
7273
7274   SDLoc DL(BV);
7275
7276   // Okay, we know the src/dst types are both integers of differing types.
7277   // Handling growing first.
7278   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7279   if (SrcBitSize < DstBitSize) {
7280     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7281
7282     SmallVector<SDValue, 8> Ops;
7283     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7284          i += NumInputsPerOutput) {
7285       bool isLE = TLI.isLittleEndian();
7286       APInt NewBits = APInt(DstBitSize, 0);
7287       bool EltIsUndef = true;
7288       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7289         // Shift the previously computed bits over.
7290         NewBits <<= SrcBitSize;
7291         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7292         if (Op.getOpcode() == ISD::UNDEF) continue;
7293         EltIsUndef = false;
7294
7295         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7296                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7297       }
7298
7299       if (EltIsUndef)
7300         Ops.push_back(DAG.getUNDEF(DstEltVT));
7301       else
7302         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7303     }
7304
7305     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7306     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7307   }
7308
7309   // Finally, this must be the case where we are shrinking elements: each input
7310   // turns into multiple outputs.
7311   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7312   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7313                             NumOutputsPerInput*BV->getNumOperands());
7314   SmallVector<SDValue, 8> Ops;
7315
7316   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7317     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7318       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7319       continue;
7320     }
7321
7322     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7323                   getAPIntValue().zextOrTrunc(SrcBitSize);
7324
7325     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7326       APInt ThisVal = OpVal.trunc(DstBitSize);
7327       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7328       OpVal = OpVal.lshr(DstBitSize);
7329     }
7330
7331     // For big endian targets, swap the order of the pieces of each element.
7332     if (TLI.isBigEndian())
7333       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7334   }
7335
7336   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7337 }
7338
7339 /// Try to perform FMA combining on a given FADD node.
7340 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7341   SDValue N0 = N->getOperand(0);
7342   SDValue N1 = N->getOperand(1);
7343   EVT VT = N->getValueType(0);
7344   SDLoc SL(N);
7345
7346   const TargetOptions &Options = DAG.getTarget().Options;
7347   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7348                        Options.UnsafeFPMath);
7349
7350   // Floating-point multiply-add with intermediate rounding.
7351   bool HasFMAD = (LegalOperations &&
7352                   TLI.isOperationLegal(ISD::FMAD, VT));
7353
7354   // Floating-point multiply-add without intermediate rounding.
7355   bool HasFMA = ((!LegalOperations ||
7356                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7357                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7358                  UnsafeFPMath);
7359
7360   // No valid opcode, do not combine.
7361   if (!HasFMAD && !HasFMA)
7362     return SDValue();
7363
7364   // Always prefer FMAD to FMA for precision.
7365   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7366   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7367   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7368
7369   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7370   if (N0.getOpcode() == ISD::FMUL &&
7371       (Aggressive || N0->hasOneUse())) {
7372     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7373                        N0.getOperand(0), N0.getOperand(1), N1);
7374   }
7375
7376   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7377   // Note: Commutes FADD operands.
7378   if (N1.getOpcode() == ISD::FMUL &&
7379       (Aggressive || N1->hasOneUse())) {
7380     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7381                        N1.getOperand(0), N1.getOperand(1), N0);
7382   }
7383
7384   // Look through FP_EXTEND nodes to do more combining.
7385   if (UnsafeFPMath && LookThroughFPExt) {
7386     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7387     if (N0.getOpcode() == ISD::FP_EXTEND) {
7388       SDValue N00 = N0.getOperand(0);
7389       if (N00.getOpcode() == ISD::FMUL)
7390         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7391                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7392                                        N00.getOperand(0)),
7393                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7394                                        N00.getOperand(1)), N1);
7395     }
7396
7397     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7398     // Note: Commutes FADD operands.
7399     if (N1.getOpcode() == ISD::FP_EXTEND) {
7400       SDValue N10 = N1.getOperand(0);
7401       if (N10.getOpcode() == ISD::FMUL)
7402         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7403                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7404                                        N10.getOperand(0)),
7405                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7406                                        N10.getOperand(1)), N0);
7407     }
7408   }
7409
7410   // More folding opportunities when target permits.
7411   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7412     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7413     if (N0.getOpcode() == PreferredFusedOpcode &&
7414         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7415       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7416                          N0.getOperand(0), N0.getOperand(1),
7417                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7418                                      N0.getOperand(2).getOperand(0),
7419                                      N0.getOperand(2).getOperand(1),
7420                                      N1));
7421     }
7422
7423     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7424     if (N1->getOpcode() == PreferredFusedOpcode &&
7425         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7426       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7427                          N1.getOperand(0), N1.getOperand(1),
7428                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7429                                      N1.getOperand(2).getOperand(0),
7430                                      N1.getOperand(2).getOperand(1),
7431                                      N0));
7432     }
7433
7434     if (UnsafeFPMath && LookThroughFPExt) {
7435       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7436       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7437       auto FoldFAddFMAFPExtFMul = [&] (
7438           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7439         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7440                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7441                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7442                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7443                                        Z));
7444       };
7445       if (N0.getOpcode() == PreferredFusedOpcode) {
7446         SDValue N02 = N0.getOperand(2);
7447         if (N02.getOpcode() == ISD::FP_EXTEND) {
7448           SDValue N020 = N02.getOperand(0);
7449           if (N020.getOpcode() == ISD::FMUL)
7450             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7451                                         N020.getOperand(0), N020.getOperand(1),
7452                                         N1);
7453         }
7454       }
7455
7456       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7457       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7458       // FIXME: This turns two single-precision and one double-precision
7459       // operation into two double-precision operations, which might not be
7460       // interesting for all targets, especially GPUs.
7461       auto FoldFAddFPExtFMAFMul = [&] (
7462           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7463         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7464                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7465                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7466                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7467                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7468                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7469                                        Z));
7470       };
7471       if (N0.getOpcode() == ISD::FP_EXTEND) {
7472         SDValue N00 = N0.getOperand(0);
7473         if (N00.getOpcode() == PreferredFusedOpcode) {
7474           SDValue N002 = N00.getOperand(2);
7475           if (N002.getOpcode() == ISD::FMUL)
7476             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7477                                         N002.getOperand(0), N002.getOperand(1),
7478                                         N1);
7479         }
7480       }
7481
7482       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7483       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7484       if (N1.getOpcode() == PreferredFusedOpcode) {
7485         SDValue N12 = N1.getOperand(2);
7486         if (N12.getOpcode() == ISD::FP_EXTEND) {
7487           SDValue N120 = N12.getOperand(0);
7488           if (N120.getOpcode() == ISD::FMUL)
7489             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7490                                         N120.getOperand(0), N120.getOperand(1),
7491                                         N0);
7492         }
7493       }
7494
7495       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7496       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7497       // FIXME: This turns two single-precision and one double-precision
7498       // operation into two double-precision operations, which might not be
7499       // interesting for all targets, especially GPUs.
7500       if (N1.getOpcode() == ISD::FP_EXTEND) {
7501         SDValue N10 = N1.getOperand(0);
7502         if (N10.getOpcode() == PreferredFusedOpcode) {
7503           SDValue N102 = N10.getOperand(2);
7504           if (N102.getOpcode() == ISD::FMUL)
7505             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7506                                         N102.getOperand(0), N102.getOperand(1),
7507                                         N0);
7508         }
7509       }
7510     }
7511   }
7512
7513   return SDValue();
7514 }
7515
7516 /// Try to perform FMA combining on a given FSUB node.
7517 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7518   SDValue N0 = N->getOperand(0);
7519   SDValue N1 = N->getOperand(1);
7520   EVT VT = N->getValueType(0);
7521   SDLoc SL(N);
7522
7523   const TargetOptions &Options = DAG.getTarget().Options;
7524   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7525                        Options.UnsafeFPMath);
7526
7527   // Floating-point multiply-add with intermediate rounding.
7528   bool HasFMAD = (LegalOperations &&
7529                   TLI.isOperationLegal(ISD::FMAD, VT));
7530
7531   // Floating-point multiply-add without intermediate rounding.
7532   bool HasFMA = ((!LegalOperations ||
7533                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7534                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7535                  UnsafeFPMath);
7536
7537   // No valid opcode, do not combine.
7538   if (!HasFMAD && !HasFMA)
7539     return SDValue();
7540
7541   // Always prefer FMAD to FMA for precision.
7542   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7543   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7544   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7545
7546   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7547   if (N0.getOpcode() == ISD::FMUL &&
7548       (Aggressive || N0->hasOneUse())) {
7549     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7550                        N0.getOperand(0), N0.getOperand(1),
7551                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7552   }
7553
7554   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7555   // Note: Commutes FSUB operands.
7556   if (N1.getOpcode() == ISD::FMUL &&
7557       (Aggressive || N1->hasOneUse()))
7558     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7559                        DAG.getNode(ISD::FNEG, SL, VT,
7560                                    N1.getOperand(0)),
7561                        N1.getOperand(1), N0);
7562
7563   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7564   if (N0.getOpcode() == ISD::FNEG &&
7565       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7566       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7567     SDValue N00 = N0.getOperand(0).getOperand(0);
7568     SDValue N01 = N0.getOperand(0).getOperand(1);
7569     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7570                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7571                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7572   }
7573
7574   // Look through FP_EXTEND nodes to do more combining.
7575   if (UnsafeFPMath && LookThroughFPExt) {
7576     // fold (fsub (fpext (fmul x, y)), z)
7577     //   -> (fma (fpext x), (fpext y), (fneg z))
7578     if (N0.getOpcode() == ISD::FP_EXTEND) {
7579       SDValue N00 = N0.getOperand(0);
7580       if (N00.getOpcode() == ISD::FMUL)
7581         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7582                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7583                                        N00.getOperand(0)),
7584                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7585                                        N00.getOperand(1)),
7586                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7587     }
7588
7589     // fold (fsub x, (fpext (fmul y, z)))
7590     //   -> (fma (fneg (fpext y)), (fpext z), x)
7591     // Note: Commutes FSUB operands.
7592     if (N1.getOpcode() == ISD::FP_EXTEND) {
7593       SDValue N10 = N1.getOperand(0);
7594       if (N10.getOpcode() == ISD::FMUL)
7595         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7596                            DAG.getNode(ISD::FNEG, SL, VT,
7597                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7598                                                    N10.getOperand(0))),
7599                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7600                                        N10.getOperand(1)),
7601                            N0);
7602     }
7603
7604     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7605     //   -> (fneg (fma (fpext x), (fpext y), z))
7606     // Note: This could be removed with appropriate canonicalization of the
7607     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7608     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7609     // from implementing the canonicalization in visitFSUB.
7610     if (N0.getOpcode() == ISD::FP_EXTEND) {
7611       SDValue N00 = N0.getOperand(0);
7612       if (N00.getOpcode() == ISD::FNEG) {
7613         SDValue N000 = N00.getOperand(0);
7614         if (N000.getOpcode() == ISD::FMUL) {
7615           return DAG.getNode(ISD::FNEG, SL, VT,
7616                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7617                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7618                                                      N000.getOperand(0)),
7619                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7620                                                      N000.getOperand(1)),
7621                                          N1));
7622         }
7623       }
7624     }
7625
7626     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7627     //   -> (fneg (fma (fpext x)), (fpext y), z)
7628     // Note: This could be removed with appropriate canonicalization of the
7629     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7630     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7631     // from implementing the canonicalization in visitFSUB.
7632     if (N0.getOpcode() == ISD::FNEG) {
7633       SDValue N00 = N0.getOperand(0);
7634       if (N00.getOpcode() == ISD::FP_EXTEND) {
7635         SDValue N000 = N00.getOperand(0);
7636         if (N000.getOpcode() == ISD::FMUL) {
7637           return DAG.getNode(ISD::FNEG, SL, VT,
7638                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7639                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640                                                      N000.getOperand(0)),
7641                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642                                                      N000.getOperand(1)),
7643                                          N1));
7644         }
7645       }
7646     }
7647
7648   }
7649
7650   // More folding opportunities when target permits.
7651   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7652     // fold (fsub (fma x, y, (fmul u, v)), z)
7653     //   -> (fma x, y (fma u, v, (fneg z)))
7654     if (N0.getOpcode() == PreferredFusedOpcode &&
7655         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7656       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7657                          N0.getOperand(0), N0.getOperand(1),
7658                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7659                                      N0.getOperand(2).getOperand(0),
7660                                      N0.getOperand(2).getOperand(1),
7661                                      DAG.getNode(ISD::FNEG, SL, VT,
7662                                                  N1)));
7663     }
7664
7665     // fold (fsub x, (fma y, z, (fmul u, v)))
7666     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7667     if (N1.getOpcode() == PreferredFusedOpcode &&
7668         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7669       SDValue N20 = N1.getOperand(2).getOperand(0);
7670       SDValue N21 = N1.getOperand(2).getOperand(1);
7671       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7672                          DAG.getNode(ISD::FNEG, SL, VT,
7673                                      N1.getOperand(0)),
7674                          N1.getOperand(1),
7675                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7676                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7677
7678                                      N21, N0));
7679     }
7680
7681     if (UnsafeFPMath && LookThroughFPExt) {
7682       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7683       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7684       if (N0.getOpcode() == PreferredFusedOpcode) {
7685         SDValue N02 = N0.getOperand(2);
7686         if (N02.getOpcode() == ISD::FP_EXTEND) {
7687           SDValue N020 = N02.getOperand(0);
7688           if (N020.getOpcode() == ISD::FMUL)
7689             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7690                                N0.getOperand(0), N0.getOperand(1),
7691                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7692                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7693                                                        N020.getOperand(0)),
7694                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7695                                                        N020.getOperand(1)),
7696                                            DAG.getNode(ISD::FNEG, SL, VT,
7697                                                        N1)));
7698         }
7699       }
7700
7701       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7702       //   -> (fma (fpext x), (fpext y),
7703       //           (fma (fpext u), (fpext v), (fneg z)))
7704       // FIXME: This turns two single-precision and one double-precision
7705       // operation into two double-precision operations, which might not be
7706       // interesting for all targets, especially GPUs.
7707       if (N0.getOpcode() == ISD::FP_EXTEND) {
7708         SDValue N00 = N0.getOperand(0);
7709         if (N00.getOpcode() == PreferredFusedOpcode) {
7710           SDValue N002 = N00.getOperand(2);
7711           if (N002.getOpcode() == ISD::FMUL)
7712             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7713                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7714                                            N00.getOperand(0)),
7715                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7716                                            N00.getOperand(1)),
7717                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7718                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7719                                                        N002.getOperand(0)),
7720                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721                                                        N002.getOperand(1)),
7722                                            DAG.getNode(ISD::FNEG, SL, VT,
7723                                                        N1)));
7724         }
7725       }
7726
7727       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7728       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7729       if (N1.getOpcode() == PreferredFusedOpcode &&
7730         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7731         SDValue N120 = N1.getOperand(2).getOperand(0);
7732         if (N120.getOpcode() == ISD::FMUL) {
7733           SDValue N1200 = N120.getOperand(0);
7734           SDValue N1201 = N120.getOperand(1);
7735           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7736                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7737                              N1.getOperand(1),
7738                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7739                                          DAG.getNode(ISD::FNEG, SL, VT,
7740                                              DAG.getNode(ISD::FP_EXTEND, SL,
7741                                                          VT, N1200)),
7742                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743                                                      N1201),
7744                                          N0));
7745         }
7746       }
7747
7748       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7749       //   -> (fma (fneg (fpext y)), (fpext z),
7750       //           (fma (fneg (fpext u)), (fpext v), x))
7751       // FIXME: This turns two single-precision and one double-precision
7752       // operation into two double-precision operations, which might not be
7753       // interesting for all targets, especially GPUs.
7754       if (N1.getOpcode() == ISD::FP_EXTEND &&
7755         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7756         SDValue N100 = N1.getOperand(0).getOperand(0);
7757         SDValue N101 = N1.getOperand(0).getOperand(1);
7758         SDValue N102 = N1.getOperand(0).getOperand(2);
7759         if (N102.getOpcode() == ISD::FMUL) {
7760           SDValue N1020 = N102.getOperand(0);
7761           SDValue N1021 = N102.getOperand(1);
7762           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763                              DAG.getNode(ISD::FNEG, SL, VT,
7764                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765                                                      N100)),
7766                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7767                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7768                                          DAG.getNode(ISD::FNEG, SL, VT,
7769                                              DAG.getNode(ISD::FP_EXTEND, SL,
7770                                                          VT, N1020)),
7771                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772                                                      N1021),
7773                                          N0));
7774         }
7775       }
7776     }
7777   }
7778
7779   return SDValue();
7780 }
7781
7782 SDValue DAGCombiner::visitFADD(SDNode *N) {
7783   SDValue N0 = N->getOperand(0);
7784   SDValue N1 = N->getOperand(1);
7785   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7786   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7787   EVT VT = N->getValueType(0);
7788   SDLoc DL(N);
7789   const TargetOptions &Options = DAG.getTarget().Options;
7790
7791   // fold vector ops
7792   if (VT.isVector())
7793     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7794       return FoldedVOp;
7795
7796   // fold (fadd c1, c2) -> c1 + c2
7797   if (N0CFP && N1CFP)
7798     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7799
7800   // canonicalize constant to RHS
7801   if (N0CFP && !N1CFP)
7802     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7803
7804   // fold (fadd A, (fneg B)) -> (fsub A, B)
7805   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7806       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7807     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7808                        GetNegatedExpression(N1, DAG, LegalOperations));
7809
7810   // fold (fadd (fneg A), B) -> (fsub B, A)
7811   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7812       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7813     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7814                        GetNegatedExpression(N0, DAG, LegalOperations));
7815
7816   // If 'unsafe math' is enabled, fold lots of things.
7817   if (Options.UnsafeFPMath) {
7818     // No FP constant should be created after legalization as Instruction
7819     // Selection pass has a hard time dealing with FP constants.
7820     bool AllowNewConst = (Level < AfterLegalizeDAG);
7821
7822     // fold (fadd A, 0) -> A
7823     if (N1CFP && N1CFP->getValueAPF().isZero())
7824       return N0;
7825
7826     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7827     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7828         isa<ConstantFPSDNode>(N0.getOperand(1)))
7829       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7830                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7831
7832     // If allowed, fold (fadd (fneg x), x) -> 0.0
7833     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7834       return DAG.getConstantFP(0.0, DL, VT);
7835
7836     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7837     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7838       return DAG.getConstantFP(0.0, DL, VT);
7839
7840     // We can fold chains of FADD's of the same value into multiplications.
7841     // This transform is not safe in general because we are reducing the number
7842     // of rounding steps.
7843     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7844       if (N0.getOpcode() == ISD::FMUL) {
7845         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7846         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7847
7848         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7849         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7850           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7851                                        DAG.getConstantFP(1.0, DL, VT));
7852           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7853         }
7854
7855         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7856         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7857             N1.getOperand(0) == N1.getOperand(1) &&
7858             N0.getOperand(0) == N1.getOperand(0)) {
7859           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7860                                        DAG.getConstantFP(2.0, DL, VT));
7861           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7862         }
7863       }
7864
7865       if (N1.getOpcode() == ISD::FMUL) {
7866         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7867         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7868
7869         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7870         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7871           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7872                                        DAG.getConstantFP(1.0, DL, VT));
7873           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7874         }
7875
7876         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7877         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7878             N0.getOperand(0) == N0.getOperand(1) &&
7879             N1.getOperand(0) == N0.getOperand(0)) {
7880           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7881                                        DAG.getConstantFP(2.0, DL, VT));
7882           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7883         }
7884       }
7885
7886       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7887         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7888         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7889         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7890             (N0.getOperand(0) == N1)) {
7891           return DAG.getNode(ISD::FMUL, DL, VT,
7892                              N1, DAG.getConstantFP(3.0, DL, VT));
7893         }
7894       }
7895
7896       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7897         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7898         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7899         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7900             N1.getOperand(0) == N0) {
7901           return DAG.getNode(ISD::FMUL, DL, VT,
7902                              N0, DAG.getConstantFP(3.0, DL, VT));
7903         }
7904       }
7905
7906       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7907       if (AllowNewConst &&
7908           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7909           N0.getOperand(0) == N0.getOperand(1) &&
7910           N1.getOperand(0) == N1.getOperand(1) &&
7911           N0.getOperand(0) == N1.getOperand(0)) {
7912         return DAG.getNode(ISD::FMUL, DL, VT,
7913                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7914       }
7915     }
7916   } // enable-unsafe-fp-math
7917
7918   // FADD -> FMA combines:
7919   SDValue Fused = visitFADDForFMACombine(N);
7920   if (Fused) {
7921     AddToWorklist(Fused.getNode());
7922     return Fused;
7923   }
7924
7925   return SDValue();
7926 }
7927
7928 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7929   SDValue N0 = N->getOperand(0);
7930   SDValue N1 = N->getOperand(1);
7931   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7932   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7933   EVT VT = N->getValueType(0);
7934   SDLoc dl(N);
7935   const TargetOptions &Options = DAG.getTarget().Options;
7936
7937   // fold vector ops
7938   if (VT.isVector())
7939     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7940       return FoldedVOp;
7941
7942   // fold (fsub c1, c2) -> c1-c2
7943   if (N0CFP && N1CFP)
7944     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7945
7946   // fold (fsub A, (fneg B)) -> (fadd A, B)
7947   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7948     return DAG.getNode(ISD::FADD, dl, VT, N0,
7949                        GetNegatedExpression(N1, DAG, LegalOperations));
7950
7951   // If 'unsafe math' is enabled, fold lots of things.
7952   if (Options.UnsafeFPMath) {
7953     // (fsub A, 0) -> A
7954     if (N1CFP && N1CFP->getValueAPF().isZero())
7955       return N0;
7956
7957     // (fsub 0, B) -> -B
7958     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7959       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7960         return GetNegatedExpression(N1, DAG, LegalOperations);
7961       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7962         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7963     }
7964
7965     // (fsub x, x) -> 0.0
7966     if (N0 == N1)
7967       return DAG.getConstantFP(0.0f, dl, VT);
7968
7969     // (fsub x, (fadd x, y)) -> (fneg y)
7970     // (fsub x, (fadd y, x)) -> (fneg y)
7971     if (N1.getOpcode() == ISD::FADD) {
7972       SDValue N10 = N1->getOperand(0);
7973       SDValue N11 = N1->getOperand(1);
7974
7975       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7976         return GetNegatedExpression(N11, DAG, LegalOperations);
7977
7978       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7979         return GetNegatedExpression(N10, DAG, LegalOperations);
7980     }
7981   }
7982
7983   // FSUB -> FMA combines:
7984   SDValue Fused = visitFSUBForFMACombine(N);
7985   if (Fused) {
7986     AddToWorklist(Fused.getNode());
7987     return Fused;
7988   }
7989
7990   return SDValue();
7991 }
7992
7993 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7994   SDValue N0 = N->getOperand(0);
7995   SDValue N1 = N->getOperand(1);
7996   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7997   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7998   EVT VT = N->getValueType(0);
7999   SDLoc DL(N);
8000   const TargetOptions &Options = DAG.getTarget().Options;
8001
8002   // fold vector ops
8003   if (VT.isVector()) {
8004     // This just handles C1 * C2 for vectors. Other vector folds are below.
8005     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8006       return FoldedVOp;
8007   }
8008
8009   // fold (fmul c1, c2) -> c1*c2
8010   if (N0CFP && N1CFP)
8011     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8012
8013   // canonicalize constant to RHS
8014   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8015      !isConstantFPBuildVectorOrConstantFP(N1))
8016     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8017
8018   // fold (fmul A, 1.0) -> A
8019   if (N1CFP && N1CFP->isExactlyValue(1.0))
8020     return N0;
8021
8022   if (Options.UnsafeFPMath) {
8023     // fold (fmul A, 0) -> 0
8024     if (N1CFP && N1CFP->getValueAPF().isZero())
8025       return N1;
8026
8027     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8028     if (N0.getOpcode() == ISD::FMUL) {
8029       // Fold scalars or any vector constants (not just splats).
8030       // This fold is done in general by InstCombine, but extra fmul insts
8031       // may have been generated during lowering.
8032       SDValue N00 = N0.getOperand(0);
8033       SDValue N01 = N0.getOperand(1);
8034       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8035       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8036       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8037       
8038       // Check 1: Make sure that the first operand of the inner multiply is NOT
8039       // a constant. Otherwise, we may induce infinite looping.
8040       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8041         // Check 2: Make sure that the second operand of the inner multiply and
8042         // the second operand of the outer multiply are constants.
8043         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8044             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8045           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8046           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8047         }
8048       }
8049     }
8050
8051     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8052     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8053     // during an early run of DAGCombiner can prevent folding with fmuls
8054     // inserted during lowering.
8055     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8056       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8057       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8058       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8059     }
8060   }
8061
8062   // fold (fmul X, 2.0) -> (fadd X, X)
8063   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8064     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8065
8066   // fold (fmul X, -1.0) -> (fneg X)
8067   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8068     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8069       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8070
8071   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8072   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8073     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8074       // Both can be negated for free, check to see if at least one is cheaper
8075       // negated.
8076       if (LHSNeg == 2 || RHSNeg == 2)
8077         return DAG.getNode(ISD::FMUL, DL, VT,
8078                            GetNegatedExpression(N0, DAG, LegalOperations),
8079                            GetNegatedExpression(N1, DAG, LegalOperations));
8080     }
8081   }
8082
8083   return SDValue();
8084 }
8085
8086 SDValue DAGCombiner::visitFMA(SDNode *N) {
8087   SDValue N0 = N->getOperand(0);
8088   SDValue N1 = N->getOperand(1);
8089   SDValue N2 = N->getOperand(2);
8090   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8091   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8092   EVT VT = N->getValueType(0);
8093   SDLoc dl(N);
8094   const TargetOptions &Options = DAG.getTarget().Options;
8095
8096   // Constant fold FMA.
8097   if (isa<ConstantFPSDNode>(N0) &&
8098       isa<ConstantFPSDNode>(N1) &&
8099       isa<ConstantFPSDNode>(N2)) {
8100     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8101   }
8102
8103   if (Options.UnsafeFPMath) {
8104     if (N0CFP && N0CFP->isZero())
8105       return N2;
8106     if (N1CFP && N1CFP->isZero())
8107       return N2;
8108   }
8109   if (N0CFP && N0CFP->isExactlyValue(1.0))
8110     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8111   if (N1CFP && N1CFP->isExactlyValue(1.0))
8112     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8113
8114   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8115   if (N0CFP && !N1CFP)
8116     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8117
8118   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8119   if (Options.UnsafeFPMath && N1CFP &&
8120       N2.getOpcode() == ISD::FMUL &&
8121       N0 == N2.getOperand(0) &&
8122       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8123     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8124                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8125   }
8126
8127
8128   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8129   if (Options.UnsafeFPMath &&
8130       N0.getOpcode() == ISD::FMUL && N1CFP &&
8131       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8132     return DAG.getNode(ISD::FMA, dl, VT,
8133                        N0.getOperand(0),
8134                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8135                        N2);
8136   }
8137
8138   // (fma x, 1, y) -> (fadd x, y)
8139   // (fma x, -1, y) -> (fadd (fneg x), y)
8140   if (N1CFP) {
8141     if (N1CFP->isExactlyValue(1.0))
8142       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8143
8144     if (N1CFP->isExactlyValue(-1.0) &&
8145         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8146       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8147       AddToWorklist(RHSNeg.getNode());
8148       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8149     }
8150   }
8151
8152   // (fma x, c, x) -> (fmul x, (c+1))
8153   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8154     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8155                        DAG.getNode(ISD::FADD, dl, VT,
8156                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8157
8158   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8159   if (Options.UnsafeFPMath && N1CFP &&
8160       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8161     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8162                        DAG.getNode(ISD::FADD, dl, VT,
8163                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8164
8165
8166   return SDValue();
8167 }
8168
8169 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8170   SDValue N0 = N->getOperand(0);
8171   SDValue N1 = N->getOperand(1);
8172   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8173   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8174   EVT VT = N->getValueType(0);
8175   SDLoc DL(N);
8176   const TargetOptions &Options = DAG.getTarget().Options;
8177
8178   // fold vector ops
8179   if (VT.isVector())
8180     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8181       return FoldedVOp;
8182
8183   // fold (fdiv c1, c2) -> c1/c2
8184   if (N0CFP && N1CFP)
8185     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8186
8187   if (Options.UnsafeFPMath) {
8188     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8189     if (N1CFP) {
8190       // Compute the reciprocal 1.0 / c2.
8191       APFloat N1APF = N1CFP->getValueAPF();
8192       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8193       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8194       // Only do the transform if the reciprocal is a legal fp immediate that
8195       // isn't too nasty (eg NaN, denormal, ...).
8196       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8197           (!LegalOperations ||
8198            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8199            // backend)... we should handle this gracefully after Legalize.
8200            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8201            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8202            TLI.isFPImmLegal(Recip, VT)))
8203         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8204                            DAG.getConstantFP(Recip, DL, VT));
8205     }
8206
8207     // If this FDIV is part of a reciprocal square root, it may be folded
8208     // into a target-specific square root estimate instruction.
8209     if (N1.getOpcode() == ISD::FSQRT) {
8210       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8211         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8212       }
8213     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8214                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8215       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8216         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8217         AddToWorklist(RV.getNode());
8218         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8219       }
8220     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8221                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8222       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8223         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8224         AddToWorklist(RV.getNode());
8225         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8226       }
8227     } else if (N1.getOpcode() == ISD::FMUL) {
8228       // Look through an FMUL. Even though this won't remove the FDIV directly,
8229       // it's still worthwhile to get rid of the FSQRT if possible.
8230       SDValue SqrtOp;
8231       SDValue OtherOp;
8232       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8233         SqrtOp = N1.getOperand(0);
8234         OtherOp = N1.getOperand(1);
8235       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8236         SqrtOp = N1.getOperand(1);
8237         OtherOp = N1.getOperand(0);
8238       }
8239       if (SqrtOp.getNode()) {
8240         // We found a FSQRT, so try to make this fold:
8241         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8242         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8243           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8244           AddToWorklist(RV.getNode());
8245           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8246         }
8247       }
8248     }
8249
8250     // Fold into a reciprocal estimate and multiply instead of a real divide.
8251     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8252       AddToWorklist(RV.getNode());
8253       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8254     }
8255   }
8256
8257   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8258   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8259     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8260       // Both can be negated for free, check to see if at least one is cheaper
8261       // negated.
8262       if (LHSNeg == 2 || RHSNeg == 2)
8263         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8264                            GetNegatedExpression(N0, DAG, LegalOperations),
8265                            GetNegatedExpression(N1, DAG, LegalOperations));
8266     }
8267   }
8268
8269   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8270   // reciprocal.
8271   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8272   // Notice that this is not always beneficial. One reason is different target
8273   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8274   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8275   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8276   if (Options.UnsafeFPMath) {
8277     // Skip if current node is a reciprocal.
8278     if (N0CFP && N0CFP->isExactlyValue(1.0))
8279       return SDValue();
8280
8281     SmallVector<SDNode *, 4> Users;
8282     // Find all FDIV users of the same divisor.
8283     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8284                               UE = N1.getNode()->use_end();
8285          UI != UE; ++UI) {
8286       SDNode *User = UI.getUse().getUser();
8287       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8288         Users.push_back(User);
8289     }
8290
8291     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8292       SDLoc DL(N);
8293       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8294       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8295
8296       // Dividend / Divisor -> Dividend * Reciprocal
8297       for (auto &U : Users) {
8298         if (U->getOperand(0) != FPOne) {
8299           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT,
8300                                         U->getOperand(0), Reciprocal);
8301           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8302         }
8303       }
8304       return SDValue();
8305     }
8306   }
8307
8308   return SDValue();
8309 }
8310
8311 SDValue DAGCombiner::visitFREM(SDNode *N) {
8312   SDValue N0 = N->getOperand(0);
8313   SDValue N1 = N->getOperand(1);
8314   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8315   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8316   EVT VT = N->getValueType(0);
8317
8318   // fold (frem c1, c2) -> fmod(c1,c2)
8319   if (N0CFP && N1CFP)
8320     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8321
8322   return SDValue();
8323 }
8324
8325 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8326   if (DAG.getTarget().Options.UnsafeFPMath &&
8327       !TLI.isFsqrtCheap()) {
8328     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8329     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8330       EVT VT = RV.getValueType();
8331       SDLoc DL(N);
8332       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8333       AddToWorklist(RV.getNode());
8334
8335       // Unfortunately, RV is now NaN if the input was exactly 0.
8336       // Select out this case and force the answer to 0.
8337       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8338       SDValue ZeroCmp =
8339         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8340                      N->getOperand(0), Zero, ISD::SETEQ);
8341       AddToWorklist(ZeroCmp.getNode());
8342       AddToWorklist(RV.getNode());
8343
8344       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8345                        DL, VT, ZeroCmp, Zero, RV);
8346       return RV;
8347     }
8348   }
8349   return SDValue();
8350 }
8351
8352 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8353   SDValue N0 = N->getOperand(0);
8354   SDValue N1 = N->getOperand(1);
8355   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8356   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8357   EVT VT = N->getValueType(0);
8358
8359   if (N0CFP && N1CFP)  // Constant fold
8360     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8361
8362   if (N1CFP) {
8363     const APFloat& V = N1CFP->getValueAPF();
8364     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8365     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8366     if (!V.isNegative()) {
8367       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8368         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8369     } else {
8370       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8371         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8372                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8373     }
8374   }
8375
8376   // copysign(fabs(x), y) -> copysign(x, y)
8377   // copysign(fneg(x), y) -> copysign(x, y)
8378   // copysign(copysign(x,z), y) -> copysign(x, y)
8379   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8380       N0.getOpcode() == ISD::FCOPYSIGN)
8381     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8382                        N0.getOperand(0), N1);
8383
8384   // copysign(x, abs(y)) -> abs(x)
8385   if (N1.getOpcode() == ISD::FABS)
8386     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8387
8388   // copysign(x, copysign(y,z)) -> copysign(x, z)
8389   if (N1.getOpcode() == ISD::FCOPYSIGN)
8390     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8391                        N0, N1.getOperand(1));
8392
8393   // copysign(x, fp_extend(y)) -> copysign(x, y)
8394   // copysign(x, fp_round(y)) -> copysign(x, y)
8395   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8396     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8397                        N0, N1.getOperand(0));
8398
8399   return SDValue();
8400 }
8401
8402 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8403   SDValue N0 = N->getOperand(0);
8404   EVT VT = N->getValueType(0);
8405   EVT OpVT = N0.getValueType();
8406
8407   // fold (sint_to_fp c1) -> c1fp
8408   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8409       // ...but only if the target supports immediate floating-point values
8410       (!LegalOperations ||
8411        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8412     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8413
8414   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8415   // but UINT_TO_FP is legal on this target, try to convert.
8416   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8417       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8418     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8419     if (DAG.SignBitIsZero(N0))
8420       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8421   }
8422
8423   // The next optimizations are desirable only if SELECT_CC can be lowered.
8424   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8425     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8426     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8427         !VT.isVector() &&
8428         (!LegalOperations ||
8429          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8430       SDLoc DL(N);
8431       SDValue Ops[] =
8432         { N0.getOperand(0), N0.getOperand(1),
8433           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8434           N0.getOperand(2) };
8435       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8436     }
8437
8438     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8439     //      (select_cc x, y, 1.0, 0.0,, cc)
8440     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8441         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8442         (!LegalOperations ||
8443          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8444       SDLoc DL(N);
8445       SDValue Ops[] =
8446         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8447           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8448           N0.getOperand(0).getOperand(2) };
8449       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8450     }
8451   }
8452
8453   return SDValue();
8454 }
8455
8456 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8457   SDValue N0 = N->getOperand(0);
8458   EVT VT = N->getValueType(0);
8459   EVT OpVT = N0.getValueType();
8460
8461   // fold (uint_to_fp c1) -> c1fp
8462   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8463       // ...but only if the target supports immediate floating-point values
8464       (!LegalOperations ||
8465        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8466     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8467
8468   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8469   // but SINT_TO_FP is legal on this target, try to convert.
8470   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8471       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8472     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8473     if (DAG.SignBitIsZero(N0))
8474       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8475   }
8476
8477   // The next optimizations are desirable only if SELECT_CC can be lowered.
8478   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8479     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8480
8481     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8482         (!LegalOperations ||
8483          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8484       SDLoc DL(N);
8485       SDValue Ops[] =
8486         { N0.getOperand(0), N0.getOperand(1),
8487           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8488           N0.getOperand(2) };
8489       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8490     }
8491   }
8492
8493   return SDValue();
8494 }
8495
8496 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8497 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8498   SDValue N0 = N->getOperand(0);
8499   EVT VT = N->getValueType(0);
8500
8501   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8502     return SDValue();
8503
8504   SDValue Src = N0.getOperand(0);
8505   EVT SrcVT = Src.getValueType();
8506   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8507   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8508
8509   // We can safely assume the conversion won't overflow the output range,
8510   // because (for example) (uint8_t)18293.f is undefined behavior.
8511
8512   // Since we can assume the conversion won't overflow, our decision as to
8513   // whether the input will fit in the float should depend on the minimum
8514   // of the input range and output range.
8515
8516   // This means this is also safe for a signed input and unsigned output, since
8517   // a negative input would lead to undefined behavior.
8518   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8519   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8520   unsigned ActualSize = std::min(InputSize, OutputSize);
8521   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8522
8523   // We can only fold away the float conversion if the input range can be
8524   // represented exactly in the float range.
8525   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8526     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8527       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8528                                                        : ISD::ZERO_EXTEND;
8529       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8530     }
8531     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8532       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8533     if (SrcVT == VT)
8534       return Src;
8535     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8536   }
8537   return SDValue();
8538 }
8539
8540 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8541   SDValue N0 = N->getOperand(0);
8542   EVT VT = N->getValueType(0);
8543
8544   // fold (fp_to_sint c1fp) -> c1
8545   if (isConstantFPBuildVectorOrConstantFP(N0))
8546     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8547
8548   return FoldIntToFPToInt(N, DAG);
8549 }
8550
8551 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8552   SDValue N0 = N->getOperand(0);
8553   EVT VT = N->getValueType(0);
8554
8555   // fold (fp_to_uint c1fp) -> c1
8556   if (isConstantFPBuildVectorOrConstantFP(N0))
8557     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8558
8559   return FoldIntToFPToInt(N, DAG);
8560 }
8561
8562 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8563   SDValue N0 = N->getOperand(0);
8564   SDValue N1 = N->getOperand(1);
8565   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8566   EVT VT = N->getValueType(0);
8567
8568   // fold (fp_round c1fp) -> c1fp
8569   if (N0CFP)
8570     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8571
8572   // fold (fp_round (fp_extend x)) -> x
8573   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8574     return N0.getOperand(0);
8575
8576   // fold (fp_round (fp_round x)) -> (fp_round x)
8577   if (N0.getOpcode() == ISD::FP_ROUND) {
8578     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8579     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8580     // If the first fp_round isn't a value preserving truncation, it might
8581     // introduce a tie in the second fp_round, that wouldn't occur in the
8582     // single-step fp_round we want to fold to.
8583     // In other words, double rounding isn't the same as rounding.
8584     // Also, this is a value preserving truncation iff both fp_round's are.
8585     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8586       SDLoc DL(N);
8587       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8588                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8589     }
8590   }
8591
8592   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8593   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8594     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8595                               N0.getOperand(0), N1);
8596     AddToWorklist(Tmp.getNode());
8597     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8598                        Tmp, N0.getOperand(1));
8599   }
8600
8601   return SDValue();
8602 }
8603
8604 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8605   SDValue N0 = N->getOperand(0);
8606   EVT VT = N->getValueType(0);
8607   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8608   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8609
8610   // fold (fp_round_inreg c1fp) -> c1fp
8611   if (N0CFP && isTypeLegal(EVT)) {
8612     SDLoc DL(N);
8613     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8614     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8615   }
8616
8617   return SDValue();
8618 }
8619
8620 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8621   SDValue N0 = N->getOperand(0);
8622   EVT VT = N->getValueType(0);
8623
8624   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8625   if (N->hasOneUse() &&
8626       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8627     return SDValue();
8628
8629   // fold (fp_extend c1fp) -> c1fp
8630   if (isConstantFPBuildVectorOrConstantFP(N0))
8631     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8632
8633   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8634   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8635       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8636     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8637
8638   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8639   // value of X.
8640   if (N0.getOpcode() == ISD::FP_ROUND
8641       && N0.getNode()->getConstantOperandVal(1) == 1) {
8642     SDValue In = N0.getOperand(0);
8643     if (In.getValueType() == VT) return In;
8644     if (VT.bitsLT(In.getValueType()))
8645       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8646                          In, N0.getOperand(1));
8647     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8648   }
8649
8650   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8651   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8652        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8653     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8654     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8655                                      LN0->getChain(),
8656                                      LN0->getBasePtr(), N0.getValueType(),
8657                                      LN0->getMemOperand());
8658     CombineTo(N, ExtLoad);
8659     CombineTo(N0.getNode(),
8660               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8661                           N0.getValueType(), ExtLoad,
8662                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8663               ExtLoad.getValue(1));
8664     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8665   }
8666
8667   return SDValue();
8668 }
8669
8670 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8671   SDValue N0 = N->getOperand(0);
8672   EVT VT = N->getValueType(0);
8673
8674   // fold (fceil c1) -> fceil(c1)
8675   if (isConstantFPBuildVectorOrConstantFP(N0))
8676     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8677
8678   return SDValue();
8679 }
8680
8681 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8682   SDValue N0 = N->getOperand(0);
8683   EVT VT = N->getValueType(0);
8684
8685   // fold (ftrunc c1) -> ftrunc(c1)
8686   if (isConstantFPBuildVectorOrConstantFP(N0))
8687     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8688
8689   return SDValue();
8690 }
8691
8692 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8693   SDValue N0 = N->getOperand(0);
8694   EVT VT = N->getValueType(0);
8695
8696   // fold (ffloor c1) -> ffloor(c1)
8697   if (isConstantFPBuildVectorOrConstantFP(N0))
8698     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8699
8700   return SDValue();
8701 }
8702
8703 // FIXME: FNEG and FABS have a lot in common; refactor.
8704 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8705   SDValue N0 = N->getOperand(0);
8706   EVT VT = N->getValueType(0);
8707
8708   // Constant fold FNEG.
8709   if (isConstantFPBuildVectorOrConstantFP(N0))
8710     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8711
8712   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8713                          &DAG.getTarget().Options))
8714     return GetNegatedExpression(N0, DAG, LegalOperations);
8715
8716   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8717   // constant pool values.
8718   if (!TLI.isFNegFree(VT) &&
8719       N0.getOpcode() == ISD::BITCAST &&
8720       N0.getNode()->hasOneUse()) {
8721     SDValue Int = N0.getOperand(0);
8722     EVT IntVT = Int.getValueType();
8723     if (IntVT.isInteger() && !IntVT.isVector()) {
8724       APInt SignMask;
8725       if (N0.getValueType().isVector()) {
8726         // For a vector, get a mask such as 0x80... per scalar element
8727         // and splat it.
8728         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8729         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8730       } else {
8731         // For a scalar, just generate 0x80...
8732         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8733       }
8734       SDLoc DL0(N0);
8735       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8736                         DAG.getConstant(SignMask, DL0, IntVT));
8737       AddToWorklist(Int.getNode());
8738       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8739     }
8740   }
8741
8742   // (fneg (fmul c, x)) -> (fmul -c, x)
8743   if (N0.getOpcode() == ISD::FMUL) {
8744     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8745     if (CFP1) {
8746       APFloat CVal = CFP1->getValueAPF();
8747       CVal.changeSign();
8748       if (Level >= AfterLegalizeDAG &&
8749           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8750            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8751         return DAG.getNode(
8752             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8753             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8754     }
8755   }
8756
8757   return SDValue();
8758 }
8759
8760 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8761   SDValue N0 = N->getOperand(0);
8762   SDValue N1 = N->getOperand(1);
8763   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8764   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8765
8766   if (N0CFP && N1CFP) {
8767     const APFloat &C0 = N0CFP->getValueAPF();
8768     const APFloat &C1 = N1CFP->getValueAPF();
8769     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8770   }
8771
8772   if (N0CFP) {
8773     EVT VT = N->getValueType(0);
8774     // Canonicalize to constant on RHS.
8775     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8776   }
8777
8778   return SDValue();
8779 }
8780
8781 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8782   SDValue N0 = N->getOperand(0);
8783   SDValue N1 = N->getOperand(1);
8784   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8785   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8786
8787   if (N0CFP && N1CFP) {
8788     const APFloat &C0 = N0CFP->getValueAPF();
8789     const APFloat &C1 = N1CFP->getValueAPF();
8790     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8791   }
8792
8793   if (N0CFP) {
8794     EVT VT = N->getValueType(0);
8795     // Canonicalize to constant on RHS.
8796     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8797   }
8798
8799   return SDValue();
8800 }
8801
8802 SDValue DAGCombiner::visitFABS(SDNode *N) {
8803   SDValue N0 = N->getOperand(0);
8804   EVT VT = N->getValueType(0);
8805
8806   // fold (fabs c1) -> fabs(c1)
8807   if (isConstantFPBuildVectorOrConstantFP(N0))
8808     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8809
8810   // fold (fabs (fabs x)) -> (fabs x)
8811   if (N0.getOpcode() == ISD::FABS)
8812     return N->getOperand(0);
8813
8814   // fold (fabs (fneg x)) -> (fabs x)
8815   // fold (fabs (fcopysign x, y)) -> (fabs x)
8816   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8817     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8818
8819   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8820   // constant pool values.
8821   if (!TLI.isFAbsFree(VT) &&
8822       N0.getOpcode() == ISD::BITCAST &&
8823       N0.getNode()->hasOneUse()) {
8824     SDValue Int = N0.getOperand(0);
8825     EVT IntVT = Int.getValueType();
8826     if (IntVT.isInteger() && !IntVT.isVector()) {
8827       APInt SignMask;
8828       if (N0.getValueType().isVector()) {
8829         // For a vector, get a mask such as 0x7f... per scalar element
8830         // and splat it.
8831         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8832         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8833       } else {
8834         // For a scalar, just generate 0x7f...
8835         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8836       }
8837       SDLoc DL(N0);
8838       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8839                         DAG.getConstant(SignMask, DL, IntVT));
8840       AddToWorklist(Int.getNode());
8841       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8842     }
8843   }
8844
8845   return SDValue();
8846 }
8847
8848 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8849   SDValue Chain = N->getOperand(0);
8850   SDValue N1 = N->getOperand(1);
8851   SDValue N2 = N->getOperand(2);
8852
8853   // If N is a constant we could fold this into a fallthrough or unconditional
8854   // branch. However that doesn't happen very often in normal code, because
8855   // Instcombine/SimplifyCFG should have handled the available opportunities.
8856   // If we did this folding here, it would be necessary to update the
8857   // MachineBasicBlock CFG, which is awkward.
8858
8859   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8860   // on the target.
8861   if (N1.getOpcode() == ISD::SETCC &&
8862       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8863                                    N1.getOperand(0).getValueType())) {
8864     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8865                        Chain, N1.getOperand(2),
8866                        N1.getOperand(0), N1.getOperand(1), N2);
8867   }
8868
8869   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8870       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8871        (N1.getOperand(0).hasOneUse() &&
8872         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8873     SDNode *Trunc = nullptr;
8874     if (N1.getOpcode() == ISD::TRUNCATE) {
8875       // Look pass the truncate.
8876       Trunc = N1.getNode();
8877       N1 = N1.getOperand(0);
8878     }
8879
8880     // Match this pattern so that we can generate simpler code:
8881     //
8882     //   %a = ...
8883     //   %b = and i32 %a, 2
8884     //   %c = srl i32 %b, 1
8885     //   brcond i32 %c ...
8886     //
8887     // into
8888     //
8889     //   %a = ...
8890     //   %b = and i32 %a, 2
8891     //   %c = setcc eq %b, 0
8892     //   brcond %c ...
8893     //
8894     // This applies only when the AND constant value has one bit set and the
8895     // SRL constant is equal to the log2 of the AND constant. The back-end is
8896     // smart enough to convert the result into a TEST/JMP sequence.
8897     SDValue Op0 = N1.getOperand(0);
8898     SDValue Op1 = N1.getOperand(1);
8899
8900     if (Op0.getOpcode() == ISD::AND &&
8901         Op1.getOpcode() == ISD::Constant) {
8902       SDValue AndOp1 = Op0.getOperand(1);
8903
8904       if (AndOp1.getOpcode() == ISD::Constant) {
8905         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8906
8907         if (AndConst.isPowerOf2() &&
8908             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8909           SDLoc DL(N);
8910           SDValue SetCC =
8911             DAG.getSetCC(DL,
8912                          getSetCCResultType(Op0.getValueType()),
8913                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8914                          ISD::SETNE);
8915
8916           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8917                                           MVT::Other, Chain, SetCC, N2);
8918           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8919           // will convert it back to (X & C1) >> C2.
8920           CombineTo(N, NewBRCond, false);
8921           // Truncate is dead.
8922           if (Trunc)
8923             deleteAndRecombine(Trunc);
8924           // Replace the uses of SRL with SETCC
8925           WorklistRemover DeadNodes(*this);
8926           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8927           deleteAndRecombine(N1.getNode());
8928           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8929         }
8930       }
8931     }
8932
8933     if (Trunc)
8934       // Restore N1 if the above transformation doesn't match.
8935       N1 = N->getOperand(1);
8936   }
8937
8938   // Transform br(xor(x, y)) -> br(x != y)
8939   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8940   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8941     SDNode *TheXor = N1.getNode();
8942     SDValue Op0 = TheXor->getOperand(0);
8943     SDValue Op1 = TheXor->getOperand(1);
8944     if (Op0.getOpcode() == Op1.getOpcode()) {
8945       // Avoid missing important xor optimizations.
8946       SDValue Tmp = visitXOR(TheXor);
8947       if (Tmp.getNode()) {
8948         if (Tmp.getNode() != TheXor) {
8949           DEBUG(dbgs() << "\nReplacing.8 ";
8950                 TheXor->dump(&DAG);
8951                 dbgs() << "\nWith: ";
8952                 Tmp.getNode()->dump(&DAG);
8953                 dbgs() << '\n');
8954           WorklistRemover DeadNodes(*this);
8955           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8956           deleteAndRecombine(TheXor);
8957           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8958                              MVT::Other, Chain, Tmp, N2);
8959         }
8960
8961         // visitXOR has changed XOR's operands or replaced the XOR completely,
8962         // bail out.
8963         return SDValue(N, 0);
8964       }
8965     }
8966
8967     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8968       bool Equal = false;
8969       if (isOneConstant(Op0) && Op0.hasOneUse() &&
8970           Op0.getOpcode() == ISD::XOR) {
8971         TheXor = Op0.getNode();
8972         Equal = true;
8973       }
8974
8975       EVT SetCCVT = N1.getValueType();
8976       if (LegalTypes)
8977         SetCCVT = getSetCCResultType(SetCCVT);
8978       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8979                                    SetCCVT,
8980                                    Op0, Op1,
8981                                    Equal ? ISD::SETEQ : ISD::SETNE);
8982       // Replace the uses of XOR with SETCC
8983       WorklistRemover DeadNodes(*this);
8984       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8985       deleteAndRecombine(N1.getNode());
8986       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8987                          MVT::Other, Chain, SetCC, N2);
8988     }
8989   }
8990
8991   return SDValue();
8992 }
8993
8994 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8995 //
8996 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8997   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8998   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8999
9000   // If N is a constant we could fold this into a fallthrough or unconditional
9001   // branch. However that doesn't happen very often in normal code, because
9002   // Instcombine/SimplifyCFG should have handled the available opportunities.
9003   // If we did this folding here, it would be necessary to update the
9004   // MachineBasicBlock CFG, which is awkward.
9005
9006   // Use SimplifySetCC to simplify SETCC's.
9007   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9008                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9009                                false);
9010   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9011
9012   // fold to a simpler setcc
9013   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9014     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9015                        N->getOperand(0), Simp.getOperand(2),
9016                        Simp.getOperand(0), Simp.getOperand(1),
9017                        N->getOperand(4));
9018
9019   return SDValue();
9020 }
9021
9022 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9023 /// and that N may be folded in the load / store addressing mode.
9024 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9025                                     SelectionDAG &DAG,
9026                                     const TargetLowering &TLI) {
9027   EVT VT;
9028   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9029     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9030       return false;
9031     VT = LD->getMemoryVT();
9032   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9033     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9034       return false;
9035     VT = ST->getMemoryVT();
9036   } else
9037     return false;
9038
9039   TargetLowering::AddrMode AM;
9040   if (N->getOpcode() == ISD::ADD) {
9041     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9042     if (Offset)
9043       // [reg +/- imm]
9044       AM.BaseOffs = Offset->getSExtValue();
9045     else
9046       // [reg +/- reg]
9047       AM.Scale = 1;
9048   } else if (N->getOpcode() == ISD::SUB) {
9049     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9050     if (Offset)
9051       // [reg +/- imm]
9052       AM.BaseOffs = -Offset->getSExtValue();
9053     else
9054       // [reg +/- reg]
9055       AM.Scale = 1;
9056   } else
9057     return false;
9058
9059   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9060 }
9061
9062 /// Try turning a load/store into a pre-indexed load/store when the base
9063 /// pointer is an add or subtract and it has other uses besides the load/store.
9064 /// After the transformation, the new indexed load/store has effectively folded
9065 /// the add/subtract in and all of its other uses are redirected to the
9066 /// new load/store.
9067 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9068   if (Level < AfterLegalizeDAG)
9069     return false;
9070
9071   bool isLoad = true;
9072   SDValue Ptr;
9073   EVT VT;
9074   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9075     if (LD->isIndexed())
9076       return false;
9077     VT = LD->getMemoryVT();
9078     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9079         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9080       return false;
9081     Ptr = LD->getBasePtr();
9082   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9083     if (ST->isIndexed())
9084       return false;
9085     VT = ST->getMemoryVT();
9086     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9087         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9088       return false;
9089     Ptr = ST->getBasePtr();
9090     isLoad = false;
9091   } else {
9092     return false;
9093   }
9094
9095   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9096   // out.  There is no reason to make this a preinc/predec.
9097   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9098       Ptr.getNode()->hasOneUse())
9099     return false;
9100
9101   // Ask the target to do addressing mode selection.
9102   SDValue BasePtr;
9103   SDValue Offset;
9104   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9105   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9106     return false;
9107
9108   // Backends without true r+i pre-indexed forms may need to pass a
9109   // constant base with a variable offset so that constant coercion
9110   // will work with the patterns in canonical form.
9111   bool Swapped = false;
9112   if (isa<ConstantSDNode>(BasePtr)) {
9113     std::swap(BasePtr, Offset);
9114     Swapped = true;
9115   }
9116
9117   // Don't create a indexed load / store with zero offset.
9118   if (isNullConstant(Offset))
9119     return false;
9120
9121   // Try turning it into a pre-indexed load / store except when:
9122   // 1) The new base ptr is a frame index.
9123   // 2) If N is a store and the new base ptr is either the same as or is a
9124   //    predecessor of the value being stored.
9125   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9126   //    that would create a cycle.
9127   // 4) All uses are load / store ops that use it as old base ptr.
9128
9129   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9130   // (plus the implicit offset) to a register to preinc anyway.
9131   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9132     return false;
9133
9134   // Check #2.
9135   if (!isLoad) {
9136     SDValue Val = cast<StoreSDNode>(N)->getValue();
9137     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9138       return false;
9139   }
9140
9141   // If the offset is a constant, there may be other adds of constants that
9142   // can be folded with this one. We should do this to avoid having to keep
9143   // a copy of the original base pointer.
9144   SmallVector<SDNode *, 16> OtherUses;
9145   if (isa<ConstantSDNode>(Offset))
9146     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9147                               UE = BasePtr.getNode()->use_end();
9148          UI != UE; ++UI) {
9149       SDUse &Use = UI.getUse();
9150       // Skip the use that is Ptr and uses of other results from BasePtr's
9151       // node (important for nodes that return multiple results).
9152       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9153         continue;
9154
9155       if (Use.getUser()->isPredecessorOf(N))
9156         continue;
9157
9158       if (Use.getUser()->getOpcode() != ISD::ADD &&
9159           Use.getUser()->getOpcode() != ISD::SUB) {
9160         OtherUses.clear();
9161         break;
9162       }
9163
9164       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9165       if (!isa<ConstantSDNode>(Op1)) {
9166         OtherUses.clear();
9167         break;
9168       }
9169
9170       // FIXME: In some cases, we can be smarter about this.
9171       if (Op1.getValueType() != Offset.getValueType()) {
9172         OtherUses.clear();
9173         break;
9174       }
9175
9176       OtherUses.push_back(Use.getUser());
9177     }
9178
9179   if (Swapped)
9180     std::swap(BasePtr, Offset);
9181
9182   // Now check for #3 and #4.
9183   bool RealUse = false;
9184
9185   // Caches for hasPredecessorHelper
9186   SmallPtrSet<const SDNode *, 32> Visited;
9187   SmallVector<const SDNode *, 16> Worklist;
9188
9189   for (SDNode *Use : Ptr.getNode()->uses()) {
9190     if (Use == N)
9191       continue;
9192     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9193       return false;
9194
9195     // If Ptr may be folded in addressing mode of other use, then it's
9196     // not profitable to do this transformation.
9197     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9198       RealUse = true;
9199   }
9200
9201   if (!RealUse)
9202     return false;
9203
9204   SDValue Result;
9205   if (isLoad)
9206     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9207                                 BasePtr, Offset, AM);
9208   else
9209     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9210                                  BasePtr, Offset, AM);
9211   ++PreIndexedNodes;
9212   ++NodesCombined;
9213   DEBUG(dbgs() << "\nReplacing.4 ";
9214         N->dump(&DAG);
9215         dbgs() << "\nWith: ";
9216         Result.getNode()->dump(&DAG);
9217         dbgs() << '\n');
9218   WorklistRemover DeadNodes(*this);
9219   if (isLoad) {
9220     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9221     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9222   } else {
9223     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9224   }
9225
9226   // Finally, since the node is now dead, remove it from the graph.
9227   deleteAndRecombine(N);
9228
9229   if (Swapped)
9230     std::swap(BasePtr, Offset);
9231
9232   // Replace other uses of BasePtr that can be updated to use Ptr
9233   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9234     unsigned OffsetIdx = 1;
9235     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9236       OffsetIdx = 0;
9237     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9238            BasePtr.getNode() && "Expected BasePtr operand");
9239
9240     // We need to replace ptr0 in the following expression:
9241     //   x0 * offset0 + y0 * ptr0 = t0
9242     // knowing that
9243     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9244     //
9245     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9246     // indexed load/store and the expresion that needs to be re-written.
9247     //
9248     // Therefore, we have:
9249     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9250
9251     ConstantSDNode *CN =
9252       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9253     int X0, X1, Y0, Y1;
9254     APInt Offset0 = CN->getAPIntValue();
9255     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9256
9257     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9258     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9259     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9260     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9261
9262     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9263
9264     APInt CNV = Offset0;
9265     if (X0 < 0) CNV = -CNV;
9266     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9267     else CNV = CNV - Offset1;
9268
9269     SDLoc DL(OtherUses[i]);
9270
9271     // We can now generate the new expression.
9272     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9273     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9274
9275     SDValue NewUse = DAG.getNode(Opcode,
9276                                  DL,
9277                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9278     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9279     deleteAndRecombine(OtherUses[i]);
9280   }
9281
9282   // Replace the uses of Ptr with uses of the updated base value.
9283   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9284   deleteAndRecombine(Ptr.getNode());
9285
9286   return true;
9287 }
9288
9289 /// Try to combine a load/store with a add/sub of the base pointer node into a
9290 /// post-indexed load/store. The transformation folded the add/subtract into the
9291 /// new indexed load/store effectively and all of its uses are redirected to the
9292 /// new load/store.
9293 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9294   if (Level < AfterLegalizeDAG)
9295     return false;
9296
9297   bool isLoad = true;
9298   SDValue Ptr;
9299   EVT VT;
9300   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9301     if (LD->isIndexed())
9302       return false;
9303     VT = LD->getMemoryVT();
9304     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9305         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9306       return false;
9307     Ptr = LD->getBasePtr();
9308   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9309     if (ST->isIndexed())
9310       return false;
9311     VT = ST->getMemoryVT();
9312     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9313         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9314       return false;
9315     Ptr = ST->getBasePtr();
9316     isLoad = false;
9317   } else {
9318     return false;
9319   }
9320
9321   if (Ptr.getNode()->hasOneUse())
9322     return false;
9323
9324   for (SDNode *Op : Ptr.getNode()->uses()) {
9325     if (Op == N ||
9326         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9327       continue;
9328
9329     SDValue BasePtr;
9330     SDValue Offset;
9331     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9332     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9333       // Don't create a indexed load / store with zero offset.
9334       if (isNullConstant(Offset))
9335         continue;
9336
9337       // Try turning it into a post-indexed load / store except when
9338       // 1) All uses are load / store ops that use it as base ptr (and
9339       //    it may be folded as addressing mmode).
9340       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9341       //    nor a successor of N. Otherwise, if Op is folded that would
9342       //    create a cycle.
9343
9344       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9345         continue;
9346
9347       // Check for #1.
9348       bool TryNext = false;
9349       for (SDNode *Use : BasePtr.getNode()->uses()) {
9350         if (Use == Ptr.getNode())
9351           continue;
9352
9353         // If all the uses are load / store addresses, then don't do the
9354         // transformation.
9355         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9356           bool RealUse = false;
9357           for (SDNode *UseUse : Use->uses()) {
9358             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9359               RealUse = true;
9360           }
9361
9362           if (!RealUse) {
9363             TryNext = true;
9364             break;
9365           }
9366         }
9367       }
9368
9369       if (TryNext)
9370         continue;
9371
9372       // Check for #2
9373       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9374         SDValue Result = isLoad
9375           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9376                                BasePtr, Offset, AM)
9377           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9378                                 BasePtr, Offset, AM);
9379         ++PostIndexedNodes;
9380         ++NodesCombined;
9381         DEBUG(dbgs() << "\nReplacing.5 ";
9382               N->dump(&DAG);
9383               dbgs() << "\nWith: ";
9384               Result.getNode()->dump(&DAG);
9385               dbgs() << '\n');
9386         WorklistRemover DeadNodes(*this);
9387         if (isLoad) {
9388           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9389           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9390         } else {
9391           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9392         }
9393
9394         // Finally, since the node is now dead, remove it from the graph.
9395         deleteAndRecombine(N);
9396
9397         // Replace the uses of Use with uses of the updated base value.
9398         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9399                                       Result.getValue(isLoad ? 1 : 0));
9400         deleteAndRecombine(Op);
9401         return true;
9402       }
9403     }
9404   }
9405
9406   return false;
9407 }
9408
9409 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9410 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9411   ISD::MemIndexedMode AM = LD->getAddressingMode();
9412   assert(AM != ISD::UNINDEXED);
9413   SDValue BP = LD->getOperand(1);
9414   SDValue Inc = LD->getOperand(2);
9415
9416   // Some backends use TargetConstants for load offsets, but don't expect
9417   // TargetConstants in general ADD nodes. We can convert these constants into
9418   // regular Constants (if the constant is not opaque).
9419   assert((Inc.getOpcode() != ISD::TargetConstant ||
9420           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9421          "Cannot split out indexing using opaque target constants");
9422   if (Inc.getOpcode() == ISD::TargetConstant) {
9423     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9424     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9425                           ConstInc->getValueType(0));
9426   }
9427
9428   unsigned Opc =
9429       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9430   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9431 }
9432
9433 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9434   LoadSDNode *LD  = cast<LoadSDNode>(N);
9435   SDValue Chain = LD->getChain();
9436   SDValue Ptr   = LD->getBasePtr();
9437
9438   // If load is not volatile and there are no uses of the loaded value (and
9439   // the updated indexed value in case of indexed loads), change uses of the
9440   // chain value into uses of the chain input (i.e. delete the dead load).
9441   if (!LD->isVolatile()) {
9442     if (N->getValueType(1) == MVT::Other) {
9443       // Unindexed loads.
9444       if (!N->hasAnyUseOfValue(0)) {
9445         // It's not safe to use the two value CombineTo variant here. e.g.
9446         // v1, chain2 = load chain1, loc
9447         // v2, chain3 = load chain2, loc
9448         // v3         = add v2, c
9449         // Now we replace use of chain2 with chain1.  This makes the second load
9450         // isomorphic to the one we are deleting, and thus makes this load live.
9451         DEBUG(dbgs() << "\nReplacing.6 ";
9452               N->dump(&DAG);
9453               dbgs() << "\nWith chain: ";
9454               Chain.getNode()->dump(&DAG);
9455               dbgs() << "\n");
9456         WorklistRemover DeadNodes(*this);
9457         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9458
9459         if (N->use_empty())
9460           deleteAndRecombine(N);
9461
9462         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9463       }
9464     } else {
9465       // Indexed loads.
9466       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9467
9468       // If this load has an opaque TargetConstant offset, then we cannot split
9469       // the indexing into an add/sub directly (that TargetConstant may not be
9470       // valid for a different type of node, and we cannot convert an opaque
9471       // target constant into a regular constant).
9472       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9473                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9474
9475       if (!N->hasAnyUseOfValue(0) &&
9476           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9477         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9478         SDValue Index;
9479         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9480           Index = SplitIndexingFromLoad(LD);
9481           // Try to fold the base pointer arithmetic into subsequent loads and
9482           // stores.
9483           AddUsersToWorklist(N);
9484         } else
9485           Index = DAG.getUNDEF(N->getValueType(1));
9486         DEBUG(dbgs() << "\nReplacing.7 ";
9487               N->dump(&DAG);
9488               dbgs() << "\nWith: ";
9489               Undef.getNode()->dump(&DAG);
9490               dbgs() << " and 2 other values\n");
9491         WorklistRemover DeadNodes(*this);
9492         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9493         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9494         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9495         deleteAndRecombine(N);
9496         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9497       }
9498     }
9499   }
9500
9501   // If this load is directly stored, replace the load value with the stored
9502   // value.
9503   // TODO: Handle store large -> read small portion.
9504   // TODO: Handle TRUNCSTORE/LOADEXT
9505   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9506     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9507       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9508       if (PrevST->getBasePtr() == Ptr &&
9509           PrevST->getValue().getValueType() == N->getValueType(0))
9510       return CombineTo(N, Chain.getOperand(1), Chain);
9511     }
9512   }
9513
9514   // Try to infer better alignment information than the load already has.
9515   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9516     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9517       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9518         SDValue NewLoad =
9519                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9520                               LD->getValueType(0),
9521                               Chain, Ptr, LD->getPointerInfo(),
9522                               LD->getMemoryVT(),
9523                               LD->isVolatile(), LD->isNonTemporal(),
9524                               LD->isInvariant(), Align, LD->getAAInfo());
9525         if (NewLoad.getNode() != N)
9526           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9527       }
9528     }
9529   }
9530
9531   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9532                                                   : DAG.getSubtarget().useAA();
9533 #ifndef NDEBUG
9534   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9535       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9536     UseAA = false;
9537 #endif
9538   if (UseAA && LD->isUnindexed()) {
9539     // Walk up chain skipping non-aliasing memory nodes.
9540     SDValue BetterChain = FindBetterChain(N, Chain);
9541
9542     // If there is a better chain.
9543     if (Chain != BetterChain) {
9544       SDValue ReplLoad;
9545
9546       // Replace the chain to void dependency.
9547       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9548         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9549                                BetterChain, Ptr, LD->getMemOperand());
9550       } else {
9551         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9552                                   LD->getValueType(0),
9553                                   BetterChain, Ptr, LD->getMemoryVT(),
9554                                   LD->getMemOperand());
9555       }
9556
9557       // Create token factor to keep old chain connected.
9558       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9559                                   MVT::Other, Chain, ReplLoad.getValue(1));
9560
9561       // Make sure the new and old chains are cleaned up.
9562       AddToWorklist(Token.getNode());
9563
9564       // Replace uses with load result and token factor. Don't add users
9565       // to work list.
9566       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9567     }
9568   }
9569
9570   // Try transforming N to an indexed load.
9571   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9572     return SDValue(N, 0);
9573
9574   // Try to slice up N to more direct loads if the slices are mapped to
9575   // different register banks or pairing can take place.
9576   if (SliceUpLoad(N))
9577     return SDValue(N, 0);
9578
9579   return SDValue();
9580 }
9581
9582 namespace {
9583 /// \brief Helper structure used to slice a load in smaller loads.
9584 /// Basically a slice is obtained from the following sequence:
9585 /// Origin = load Ty1, Base
9586 /// Shift = srl Ty1 Origin, CstTy Amount
9587 /// Inst = trunc Shift to Ty2
9588 ///
9589 /// Then, it will be rewriten into:
9590 /// Slice = load SliceTy, Base + SliceOffset
9591 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9592 ///
9593 /// SliceTy is deduced from the number of bits that are actually used to
9594 /// build Inst.
9595 struct LoadedSlice {
9596   /// \brief Helper structure used to compute the cost of a slice.
9597   struct Cost {
9598     /// Are we optimizing for code size.
9599     bool ForCodeSize;
9600     /// Various cost.
9601     unsigned Loads;
9602     unsigned Truncates;
9603     unsigned CrossRegisterBanksCopies;
9604     unsigned ZExts;
9605     unsigned Shift;
9606
9607     Cost(bool ForCodeSize = false)
9608         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9609           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9610
9611     /// \brief Get the cost of one isolated slice.
9612     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9613         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9614           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9615       EVT TruncType = LS.Inst->getValueType(0);
9616       EVT LoadedType = LS.getLoadedType();
9617       if (TruncType != LoadedType &&
9618           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9619         ZExts = 1;
9620     }
9621
9622     /// \brief Account for slicing gain in the current cost.
9623     /// Slicing provide a few gains like removing a shift or a
9624     /// truncate. This method allows to grow the cost of the original
9625     /// load with the gain from this slice.
9626     void addSliceGain(const LoadedSlice &LS) {
9627       // Each slice saves a truncate.
9628       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9629       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9630                               LS.Inst->getOperand(0).getValueType()))
9631         ++Truncates;
9632       // If there is a shift amount, this slice gets rid of it.
9633       if (LS.Shift)
9634         ++Shift;
9635       // If this slice can merge a cross register bank copy, account for it.
9636       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9637         ++CrossRegisterBanksCopies;
9638     }
9639
9640     Cost &operator+=(const Cost &RHS) {
9641       Loads += RHS.Loads;
9642       Truncates += RHS.Truncates;
9643       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9644       ZExts += RHS.ZExts;
9645       Shift += RHS.Shift;
9646       return *this;
9647     }
9648
9649     bool operator==(const Cost &RHS) const {
9650       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9651              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9652              ZExts == RHS.ZExts && Shift == RHS.Shift;
9653     }
9654
9655     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9656
9657     bool operator<(const Cost &RHS) const {
9658       // Assume cross register banks copies are as expensive as loads.
9659       // FIXME: Do we want some more target hooks?
9660       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9661       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9662       // Unless we are optimizing for code size, consider the
9663       // expensive operation first.
9664       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9665         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9666       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9667              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9668     }
9669
9670     bool operator>(const Cost &RHS) const { return RHS < *this; }
9671
9672     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9673
9674     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9675   };
9676   // The last instruction that represent the slice. This should be a
9677   // truncate instruction.
9678   SDNode *Inst;
9679   // The original load instruction.
9680   LoadSDNode *Origin;
9681   // The right shift amount in bits from the original load.
9682   unsigned Shift;
9683   // The DAG from which Origin came from.
9684   // This is used to get some contextual information about legal types, etc.
9685   SelectionDAG *DAG;
9686
9687   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9688               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9689       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9690
9691   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9692   /// \return Result is \p BitWidth and has used bits set to 1 and
9693   ///         not used bits set to 0.
9694   APInt getUsedBits() const {
9695     // Reproduce the trunc(lshr) sequence:
9696     // - Start from the truncated value.
9697     // - Zero extend to the desired bit width.
9698     // - Shift left.
9699     assert(Origin && "No original load to compare against.");
9700     unsigned BitWidth = Origin->getValueSizeInBits(0);
9701     assert(Inst && "This slice is not bound to an instruction");
9702     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9703            "Extracted slice is bigger than the whole type!");
9704     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9705     UsedBits.setAllBits();
9706     UsedBits = UsedBits.zext(BitWidth);
9707     UsedBits <<= Shift;
9708     return UsedBits;
9709   }
9710
9711   /// \brief Get the size of the slice to be loaded in bytes.
9712   unsigned getLoadedSize() const {
9713     unsigned SliceSize = getUsedBits().countPopulation();
9714     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9715     return SliceSize / 8;
9716   }
9717
9718   /// \brief Get the type that will be loaded for this slice.
9719   /// Note: This may not be the final type for the slice.
9720   EVT getLoadedType() const {
9721     assert(DAG && "Missing context");
9722     LLVMContext &Ctxt = *DAG->getContext();
9723     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9724   }
9725
9726   /// \brief Get the alignment of the load used for this slice.
9727   unsigned getAlignment() const {
9728     unsigned Alignment = Origin->getAlignment();
9729     unsigned Offset = getOffsetFromBase();
9730     if (Offset != 0)
9731       Alignment = MinAlign(Alignment, Alignment + Offset);
9732     return Alignment;
9733   }
9734
9735   /// \brief Check if this slice can be rewritten with legal operations.
9736   bool isLegal() const {
9737     // An invalid slice is not legal.
9738     if (!Origin || !Inst || !DAG)
9739       return false;
9740
9741     // Offsets are for indexed load only, we do not handle that.
9742     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9743       return false;
9744
9745     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9746
9747     // Check that the type is legal.
9748     EVT SliceType = getLoadedType();
9749     if (!TLI.isTypeLegal(SliceType))
9750       return false;
9751
9752     // Check that the load is legal for this type.
9753     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9754       return false;
9755
9756     // Check that the offset can be computed.
9757     // 1. Check its type.
9758     EVT PtrType = Origin->getBasePtr().getValueType();
9759     if (PtrType == MVT::Untyped || PtrType.isExtended())
9760       return false;
9761
9762     // 2. Check that it fits in the immediate.
9763     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9764       return false;
9765
9766     // 3. Check that the computation is legal.
9767     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9768       return false;
9769
9770     // Check that the zext is legal if it needs one.
9771     EVT TruncateType = Inst->getValueType(0);
9772     if (TruncateType != SliceType &&
9773         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9774       return false;
9775
9776     return true;
9777   }
9778
9779   /// \brief Get the offset in bytes of this slice in the original chunk of
9780   /// bits.
9781   /// \pre DAG != nullptr.
9782   uint64_t getOffsetFromBase() const {
9783     assert(DAG && "Missing context.");
9784     bool IsBigEndian =
9785         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9786     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9787     uint64_t Offset = Shift / 8;
9788     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9789     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9790            "The size of the original loaded type is not a multiple of a"
9791            " byte.");
9792     // If Offset is bigger than TySizeInBytes, it means we are loading all
9793     // zeros. This should have been optimized before in the process.
9794     assert(TySizeInBytes > Offset &&
9795            "Invalid shift amount for given loaded size");
9796     if (IsBigEndian)
9797       Offset = TySizeInBytes - Offset - getLoadedSize();
9798     return Offset;
9799   }
9800
9801   /// \brief Generate the sequence of instructions to load the slice
9802   /// represented by this object and redirect the uses of this slice to
9803   /// this new sequence of instructions.
9804   /// \pre this->Inst && this->Origin are valid Instructions and this
9805   /// object passed the legal check: LoadedSlice::isLegal returned true.
9806   /// \return The last instruction of the sequence used to load the slice.
9807   SDValue loadSlice() const {
9808     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9809     const SDValue &OldBaseAddr = Origin->getBasePtr();
9810     SDValue BaseAddr = OldBaseAddr;
9811     // Get the offset in that chunk of bytes w.r.t. the endianess.
9812     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9813     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9814     if (Offset) {
9815       // BaseAddr = BaseAddr + Offset.
9816       EVT ArithType = BaseAddr.getValueType();
9817       SDLoc DL(Origin);
9818       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9819                               DAG->getConstant(Offset, DL, ArithType));
9820     }
9821
9822     // Create the type of the loaded slice according to its size.
9823     EVT SliceType = getLoadedType();
9824
9825     // Create the load for the slice.
9826     SDValue LastInst = DAG->getLoad(
9827         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9828         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9829         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9830     // If the final type is not the same as the loaded type, this means that
9831     // we have to pad with zero. Create a zero extend for that.
9832     EVT FinalType = Inst->getValueType(0);
9833     if (SliceType != FinalType)
9834       LastInst =
9835           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9836     return LastInst;
9837   }
9838
9839   /// \brief Check if this slice can be merged with an expensive cross register
9840   /// bank copy. E.g.,
9841   /// i = load i32
9842   /// f = bitcast i32 i to float
9843   bool canMergeExpensiveCrossRegisterBankCopy() const {
9844     if (!Inst || !Inst->hasOneUse())
9845       return false;
9846     SDNode *Use = *Inst->use_begin();
9847     if (Use->getOpcode() != ISD::BITCAST)
9848       return false;
9849     assert(DAG && "Missing context");
9850     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9851     EVT ResVT = Use->getValueType(0);
9852     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9853     const TargetRegisterClass *ArgRC =
9854         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9855     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9856       return false;
9857
9858     // At this point, we know that we perform a cross-register-bank copy.
9859     // Check if it is expensive.
9860     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9861     // Assume bitcasts are cheap, unless both register classes do not
9862     // explicitly share a common sub class.
9863     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9864       return false;
9865
9866     // Check if it will be merged with the load.
9867     // 1. Check the alignment constraint.
9868     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9869         ResVT.getTypeForEVT(*DAG->getContext()));
9870
9871     if (RequiredAlignment > getAlignment())
9872       return false;
9873
9874     // 2. Check that the load is a legal operation for that type.
9875     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9876       return false;
9877
9878     // 3. Check that we do not have a zext in the way.
9879     if (Inst->getValueType(0) != getLoadedType())
9880       return false;
9881
9882     return true;
9883   }
9884 };
9885 }
9886
9887 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9888 /// \p UsedBits looks like 0..0 1..1 0..0.
9889 static bool areUsedBitsDense(const APInt &UsedBits) {
9890   // If all the bits are one, this is dense!
9891   if (UsedBits.isAllOnesValue())
9892     return true;
9893
9894   // Get rid of the unused bits on the right.
9895   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9896   // Get rid of the unused bits on the left.
9897   if (NarrowedUsedBits.countLeadingZeros())
9898     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9899   // Check that the chunk of bits is completely used.
9900   return NarrowedUsedBits.isAllOnesValue();
9901 }
9902
9903 /// \brief Check whether or not \p First and \p Second are next to each other
9904 /// in memory. This means that there is no hole between the bits loaded
9905 /// by \p First and the bits loaded by \p Second.
9906 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9907                                      const LoadedSlice &Second) {
9908   assert(First.Origin == Second.Origin && First.Origin &&
9909          "Unable to match different memory origins.");
9910   APInt UsedBits = First.getUsedBits();
9911   assert((UsedBits & Second.getUsedBits()) == 0 &&
9912          "Slices are not supposed to overlap.");
9913   UsedBits |= Second.getUsedBits();
9914   return areUsedBitsDense(UsedBits);
9915 }
9916
9917 /// \brief Adjust the \p GlobalLSCost according to the target
9918 /// paring capabilities and the layout of the slices.
9919 /// \pre \p GlobalLSCost should account for at least as many loads as
9920 /// there is in the slices in \p LoadedSlices.
9921 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9922                                  LoadedSlice::Cost &GlobalLSCost) {
9923   unsigned NumberOfSlices = LoadedSlices.size();
9924   // If there is less than 2 elements, no pairing is possible.
9925   if (NumberOfSlices < 2)
9926     return;
9927
9928   // Sort the slices so that elements that are likely to be next to each
9929   // other in memory are next to each other in the list.
9930   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9931             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9932     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9933     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9934   });
9935   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9936   // First (resp. Second) is the first (resp. Second) potentially candidate
9937   // to be placed in a paired load.
9938   const LoadedSlice *First = nullptr;
9939   const LoadedSlice *Second = nullptr;
9940   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9941                 // Set the beginning of the pair.
9942                                                            First = Second) {
9943
9944     Second = &LoadedSlices[CurrSlice];
9945
9946     // If First is NULL, it means we start a new pair.
9947     // Get to the next slice.
9948     if (!First)
9949       continue;
9950
9951     EVT LoadedType = First->getLoadedType();
9952
9953     // If the types of the slices are different, we cannot pair them.
9954     if (LoadedType != Second->getLoadedType())
9955       continue;
9956
9957     // Check if the target supplies paired loads for this type.
9958     unsigned RequiredAlignment = 0;
9959     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9960       // move to the next pair, this type is hopeless.
9961       Second = nullptr;
9962       continue;
9963     }
9964     // Check if we meet the alignment requirement.
9965     if (RequiredAlignment > First->getAlignment())
9966       continue;
9967
9968     // Check that both loads are next to each other in memory.
9969     if (!areSlicesNextToEachOther(*First, *Second))
9970       continue;
9971
9972     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9973     --GlobalLSCost.Loads;
9974     // Move to the next pair.
9975     Second = nullptr;
9976   }
9977 }
9978
9979 /// \brief Check the profitability of all involved LoadedSlice.
9980 /// Currently, it is considered profitable if there is exactly two
9981 /// involved slices (1) which are (2) next to each other in memory, and
9982 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9983 ///
9984 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9985 /// the elements themselves.
9986 ///
9987 /// FIXME: When the cost model will be mature enough, we can relax
9988 /// constraints (1) and (2).
9989 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9990                                 const APInt &UsedBits, bool ForCodeSize) {
9991   unsigned NumberOfSlices = LoadedSlices.size();
9992   if (StressLoadSlicing)
9993     return NumberOfSlices > 1;
9994
9995   // Check (1).
9996   if (NumberOfSlices != 2)
9997     return false;
9998
9999   // Check (2).
10000   if (!areUsedBitsDense(UsedBits))
10001     return false;
10002
10003   // Check (3).
10004   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10005   // The original code has one big load.
10006   OrigCost.Loads = 1;
10007   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10008     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10009     // Accumulate the cost of all the slices.
10010     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10011     GlobalSlicingCost += SliceCost;
10012
10013     // Account as cost in the original configuration the gain obtained
10014     // with the current slices.
10015     OrigCost.addSliceGain(LS);
10016   }
10017
10018   // If the target supports paired load, adjust the cost accordingly.
10019   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10020   return OrigCost > GlobalSlicingCost;
10021 }
10022
10023 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10024 /// operations, split it in the various pieces being extracted.
10025 ///
10026 /// This sort of thing is introduced by SROA.
10027 /// This slicing takes care not to insert overlapping loads.
10028 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10029 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10030   if (Level < AfterLegalizeDAG)
10031     return false;
10032
10033   LoadSDNode *LD = cast<LoadSDNode>(N);
10034   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10035       !LD->getValueType(0).isInteger())
10036     return false;
10037
10038   // Keep track of already used bits to detect overlapping values.
10039   // In that case, we will just abort the transformation.
10040   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10041
10042   SmallVector<LoadedSlice, 4> LoadedSlices;
10043
10044   // Check if this load is used as several smaller chunks of bits.
10045   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10046   // of computation for each trunc.
10047   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10048        UI != UIEnd; ++UI) {
10049     // Skip the uses of the chain.
10050     if (UI.getUse().getResNo() != 0)
10051       continue;
10052
10053     SDNode *User = *UI;
10054     unsigned Shift = 0;
10055
10056     // Check if this is a trunc(lshr).
10057     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10058         isa<ConstantSDNode>(User->getOperand(1))) {
10059       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10060       User = *User->use_begin();
10061     }
10062
10063     // At this point, User is a Truncate, iff we encountered, trunc or
10064     // trunc(lshr).
10065     if (User->getOpcode() != ISD::TRUNCATE)
10066       return false;
10067
10068     // The width of the type must be a power of 2 and greater than 8-bits.
10069     // Otherwise the load cannot be represented in LLVM IR.
10070     // Moreover, if we shifted with a non-8-bits multiple, the slice
10071     // will be across several bytes. We do not support that.
10072     unsigned Width = User->getValueSizeInBits(0);
10073     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10074       return 0;
10075
10076     // Build the slice for this chain of computations.
10077     LoadedSlice LS(User, LD, Shift, &DAG);
10078     APInt CurrentUsedBits = LS.getUsedBits();
10079
10080     // Check if this slice overlaps with another.
10081     if ((CurrentUsedBits & UsedBits) != 0)
10082       return false;
10083     // Update the bits used globally.
10084     UsedBits |= CurrentUsedBits;
10085
10086     // Check if the new slice would be legal.
10087     if (!LS.isLegal())
10088       return false;
10089
10090     // Record the slice.
10091     LoadedSlices.push_back(LS);
10092   }
10093
10094   // Abort slicing if it does not seem to be profitable.
10095   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10096     return false;
10097
10098   ++SlicedLoads;
10099
10100   // Rewrite each chain to use an independent load.
10101   // By construction, each chain can be represented by a unique load.
10102
10103   // Prepare the argument for the new token factor for all the slices.
10104   SmallVector<SDValue, 8> ArgChains;
10105   for (SmallVectorImpl<LoadedSlice>::const_iterator
10106            LSIt = LoadedSlices.begin(),
10107            LSItEnd = LoadedSlices.end();
10108        LSIt != LSItEnd; ++LSIt) {
10109     SDValue SliceInst = LSIt->loadSlice();
10110     CombineTo(LSIt->Inst, SliceInst, true);
10111     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10112       SliceInst = SliceInst.getOperand(0);
10113     assert(SliceInst->getOpcode() == ISD::LOAD &&
10114            "It takes more than a zext to get to the loaded slice!!");
10115     ArgChains.push_back(SliceInst.getValue(1));
10116   }
10117
10118   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10119                               ArgChains);
10120   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10121   return true;
10122 }
10123
10124 /// Check to see if V is (and load (ptr), imm), where the load is having
10125 /// specific bytes cleared out.  If so, return the byte size being masked out
10126 /// and the shift amount.
10127 static std::pair<unsigned, unsigned>
10128 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10129   std::pair<unsigned, unsigned> Result(0, 0);
10130
10131   // Check for the structure we're looking for.
10132   if (V->getOpcode() != ISD::AND ||
10133       !isa<ConstantSDNode>(V->getOperand(1)) ||
10134       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10135     return Result;
10136
10137   // Check the chain and pointer.
10138   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10139   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10140
10141   // The store should be chained directly to the load or be an operand of a
10142   // tokenfactor.
10143   if (LD == Chain.getNode())
10144     ; // ok.
10145   else if (Chain->getOpcode() != ISD::TokenFactor)
10146     return Result; // Fail.
10147   else {
10148     bool isOk = false;
10149     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10150       if (Chain->getOperand(i).getNode() == LD) {
10151         isOk = true;
10152         break;
10153       }
10154     if (!isOk) return Result;
10155   }
10156
10157   // This only handles simple types.
10158   if (V.getValueType() != MVT::i16 &&
10159       V.getValueType() != MVT::i32 &&
10160       V.getValueType() != MVT::i64)
10161     return Result;
10162
10163   // Check the constant mask.  Invert it so that the bits being masked out are
10164   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10165   // follow the sign bit for uniformity.
10166   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10167   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10168   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10169   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10170   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10171   if (NotMaskLZ == 64) return Result;  // All zero mask.
10172
10173   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10174   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10175     return Result;
10176
10177   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10178   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10179     NotMaskLZ -= 64-V.getValueSizeInBits();
10180
10181   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10182   switch (MaskedBytes) {
10183   case 1:
10184   case 2:
10185   case 4: break;
10186   default: return Result; // All one mask, or 5-byte mask.
10187   }
10188
10189   // Verify that the first bit starts at a multiple of mask so that the access
10190   // is aligned the same as the access width.
10191   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10192
10193   Result.first = MaskedBytes;
10194   Result.second = NotMaskTZ/8;
10195   return Result;
10196 }
10197
10198
10199 /// Check to see if IVal is something that provides a value as specified by
10200 /// MaskInfo. If so, replace the specified store with a narrower store of
10201 /// truncated IVal.
10202 static SDNode *
10203 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10204                                 SDValue IVal, StoreSDNode *St,
10205                                 DAGCombiner *DC) {
10206   unsigned NumBytes = MaskInfo.first;
10207   unsigned ByteShift = MaskInfo.second;
10208   SelectionDAG &DAG = DC->getDAG();
10209
10210   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10211   // that uses this.  If not, this is not a replacement.
10212   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10213                                   ByteShift*8, (ByteShift+NumBytes)*8);
10214   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10215
10216   // Check that it is legal on the target to do this.  It is legal if the new
10217   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10218   // legalization.
10219   MVT VT = MVT::getIntegerVT(NumBytes*8);
10220   if (!DC->isTypeLegal(VT))
10221     return nullptr;
10222
10223   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10224   // shifted by ByteShift and truncated down to NumBytes.
10225   if (ByteShift) {
10226     SDLoc DL(IVal);
10227     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10228                        DAG.getConstant(ByteShift*8, DL,
10229                                     DC->getShiftAmountTy(IVal.getValueType())));
10230   }
10231
10232   // Figure out the offset for the store and the alignment of the access.
10233   unsigned StOffset;
10234   unsigned NewAlign = St->getAlignment();
10235
10236   if (DAG.getTargetLoweringInfo().isLittleEndian())
10237     StOffset = ByteShift;
10238   else
10239     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10240
10241   SDValue Ptr = St->getBasePtr();
10242   if (StOffset) {
10243     SDLoc DL(IVal);
10244     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10245                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10246     NewAlign = MinAlign(NewAlign, StOffset);
10247   }
10248
10249   // Truncate down to the new size.
10250   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10251
10252   ++OpsNarrowed;
10253   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10254                       St->getPointerInfo().getWithOffset(StOffset),
10255                       false, false, NewAlign).getNode();
10256 }
10257
10258
10259 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10260 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10261 /// narrowing the load and store if it would end up being a win for performance
10262 /// or code size.
10263 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10264   StoreSDNode *ST  = cast<StoreSDNode>(N);
10265   if (ST->isVolatile())
10266     return SDValue();
10267
10268   SDValue Chain = ST->getChain();
10269   SDValue Value = ST->getValue();
10270   SDValue Ptr   = ST->getBasePtr();
10271   EVT VT = Value.getValueType();
10272
10273   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10274     return SDValue();
10275
10276   unsigned Opc = Value.getOpcode();
10277
10278   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10279   // is a byte mask indicating a consecutive number of bytes, check to see if
10280   // Y is known to provide just those bytes.  If so, we try to replace the
10281   // load + replace + store sequence with a single (narrower) store, which makes
10282   // the load dead.
10283   if (Opc == ISD::OR) {
10284     std::pair<unsigned, unsigned> MaskedLoad;
10285     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10286     if (MaskedLoad.first)
10287       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10288                                                   Value.getOperand(1), ST,this))
10289         return SDValue(NewST, 0);
10290
10291     // Or is commutative, so try swapping X and Y.
10292     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10293     if (MaskedLoad.first)
10294       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10295                                                   Value.getOperand(0), ST,this))
10296         return SDValue(NewST, 0);
10297   }
10298
10299   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10300       Value.getOperand(1).getOpcode() != ISD::Constant)
10301     return SDValue();
10302
10303   SDValue N0 = Value.getOperand(0);
10304   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10305       Chain == SDValue(N0.getNode(), 1)) {
10306     LoadSDNode *LD = cast<LoadSDNode>(N0);
10307     if (LD->getBasePtr() != Ptr ||
10308         LD->getPointerInfo().getAddrSpace() !=
10309         ST->getPointerInfo().getAddrSpace())
10310       return SDValue();
10311
10312     // Find the type to narrow it the load / op / store to.
10313     SDValue N1 = Value.getOperand(1);
10314     unsigned BitWidth = N1.getValueSizeInBits();
10315     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10316     if (Opc == ISD::AND)
10317       Imm ^= APInt::getAllOnesValue(BitWidth);
10318     if (Imm == 0 || Imm.isAllOnesValue())
10319       return SDValue();
10320     unsigned ShAmt = Imm.countTrailingZeros();
10321     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10322     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10323     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10324     // The narrowing should be profitable, the load/store operation should be
10325     // legal (or custom) and the store size should be equal to the NewVT width.
10326     while (NewBW < BitWidth &&
10327            (NewVT.getStoreSizeInBits() != NewBW ||
10328             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10329             !TLI.isNarrowingProfitable(VT, NewVT))) {
10330       NewBW = NextPowerOf2(NewBW);
10331       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10332     }
10333     if (NewBW >= BitWidth)
10334       return SDValue();
10335
10336     // If the lsb changed does not start at the type bitwidth boundary,
10337     // start at the previous one.
10338     if (ShAmt % NewBW)
10339       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10340     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10341                                    std::min(BitWidth, ShAmt + NewBW));
10342     if ((Imm & Mask) == Imm) {
10343       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10344       if (Opc == ISD::AND)
10345         NewImm ^= APInt::getAllOnesValue(NewBW);
10346       uint64_t PtrOff = ShAmt / 8;
10347       // For big endian targets, we need to adjust the offset to the pointer to
10348       // load the correct bytes.
10349       if (TLI.isBigEndian())
10350         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10351
10352       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10353       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10354       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10355         return SDValue();
10356
10357       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10358                                    Ptr.getValueType(), Ptr,
10359                                    DAG.getConstant(PtrOff, SDLoc(LD),
10360                                                    Ptr.getValueType()));
10361       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10362                                   LD->getChain(), NewPtr,
10363                                   LD->getPointerInfo().getWithOffset(PtrOff),
10364                                   LD->isVolatile(), LD->isNonTemporal(),
10365                                   LD->isInvariant(), NewAlign,
10366                                   LD->getAAInfo());
10367       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10368                                    DAG.getConstant(NewImm, SDLoc(Value),
10369                                                    NewVT));
10370       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10371                                    NewVal, NewPtr,
10372                                    ST->getPointerInfo().getWithOffset(PtrOff),
10373                                    false, false, NewAlign);
10374
10375       AddToWorklist(NewPtr.getNode());
10376       AddToWorklist(NewLD.getNode());
10377       AddToWorklist(NewVal.getNode());
10378       WorklistRemover DeadNodes(*this);
10379       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10380       ++OpsNarrowed;
10381       return NewST;
10382     }
10383   }
10384
10385   return SDValue();
10386 }
10387
10388 /// For a given floating point load / store pair, if the load value isn't used
10389 /// by any other operations, then consider transforming the pair to integer
10390 /// load / store operations if the target deems the transformation profitable.
10391 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10392   StoreSDNode *ST  = cast<StoreSDNode>(N);
10393   SDValue Chain = ST->getChain();
10394   SDValue Value = ST->getValue();
10395   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10396       Value.hasOneUse() &&
10397       Chain == SDValue(Value.getNode(), 1)) {
10398     LoadSDNode *LD = cast<LoadSDNode>(Value);
10399     EVT VT = LD->getMemoryVT();
10400     if (!VT.isFloatingPoint() ||
10401         VT != ST->getMemoryVT() ||
10402         LD->isNonTemporal() ||
10403         ST->isNonTemporal() ||
10404         LD->getPointerInfo().getAddrSpace() != 0 ||
10405         ST->getPointerInfo().getAddrSpace() != 0)
10406       return SDValue();
10407
10408     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10409     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10410         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10411         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10412         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10413       return SDValue();
10414
10415     unsigned LDAlign = LD->getAlignment();
10416     unsigned STAlign = ST->getAlignment();
10417     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10418     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10419     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10420       return SDValue();
10421
10422     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10423                                 LD->getChain(), LD->getBasePtr(),
10424                                 LD->getPointerInfo(),
10425                                 false, false, false, LDAlign);
10426
10427     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10428                                  NewLD, ST->getBasePtr(),
10429                                  ST->getPointerInfo(),
10430                                  false, false, STAlign);
10431
10432     AddToWorklist(NewLD.getNode());
10433     AddToWorklist(NewST.getNode());
10434     WorklistRemover DeadNodes(*this);
10435     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10436     ++LdStFP2Int;
10437     return NewST;
10438   }
10439
10440   return SDValue();
10441 }
10442
10443 namespace {
10444 /// Helper struct to parse and store a memory address as base + index + offset.
10445 /// We ignore sign extensions when it is safe to do so.
10446 /// The following two expressions are not equivalent. To differentiate we need
10447 /// to store whether there was a sign extension involved in the index
10448 /// computation.
10449 ///  (load (i64 add (i64 copyfromreg %c)
10450 ///                 (i64 signextend (add (i8 load %index)
10451 ///                                      (i8 1))))
10452 /// vs
10453 ///
10454 /// (load (i64 add (i64 copyfromreg %c)
10455 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10456 ///                                         (i32 1)))))
10457 struct BaseIndexOffset {
10458   SDValue Base;
10459   SDValue Index;
10460   int64_t Offset;
10461   bool IsIndexSignExt;
10462
10463   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10464
10465   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10466                   bool IsIndexSignExt) :
10467     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10468
10469   bool equalBaseIndex(const BaseIndexOffset &Other) {
10470     return Other.Base == Base && Other.Index == Index &&
10471       Other.IsIndexSignExt == IsIndexSignExt;
10472   }
10473
10474   /// Parses tree in Ptr for base, index, offset addresses.
10475   static BaseIndexOffset match(SDValue Ptr) {
10476     bool IsIndexSignExt = false;
10477
10478     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10479     // instruction, then it could be just the BASE or everything else we don't
10480     // know how to handle. Just use Ptr as BASE and give up.
10481     if (Ptr->getOpcode() != ISD::ADD)
10482       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10483
10484     // We know that we have at least an ADD instruction. Try to pattern match
10485     // the simple case of BASE + OFFSET.
10486     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10487       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10488       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10489                               IsIndexSignExt);
10490     }
10491
10492     // Inside a loop the current BASE pointer is calculated using an ADD and a
10493     // MUL instruction. In this case Ptr is the actual BASE pointer.
10494     // (i64 add (i64 %array_ptr)
10495     //          (i64 mul (i64 %induction_var)
10496     //                   (i64 %element_size)))
10497     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10498       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10499
10500     // Look at Base + Index + Offset cases.
10501     SDValue Base = Ptr->getOperand(0);
10502     SDValue IndexOffset = Ptr->getOperand(1);
10503
10504     // Skip signextends.
10505     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10506       IndexOffset = IndexOffset->getOperand(0);
10507       IsIndexSignExt = true;
10508     }
10509
10510     // Either the case of Base + Index (no offset) or something else.
10511     if (IndexOffset->getOpcode() != ISD::ADD)
10512       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10513
10514     // Now we have the case of Base + Index + offset.
10515     SDValue Index = IndexOffset->getOperand(0);
10516     SDValue Offset = IndexOffset->getOperand(1);
10517
10518     if (!isa<ConstantSDNode>(Offset))
10519       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10520
10521     // Ignore signextends.
10522     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10523       Index = Index->getOperand(0);
10524       IsIndexSignExt = true;
10525     } else IsIndexSignExt = false;
10526
10527     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10528     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10529   }
10530 };
10531 } // namespace
10532
10533 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10534                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10535                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10536   // Make sure we have something to merge.
10537   if (NumElem < 2)
10538     return false;
10539
10540   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10541   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10542   unsigned LatestNodeUsed = 0;
10543
10544   for (unsigned i=0; i < NumElem; ++i) {
10545     // Find a chain for the new wide-store operand. Notice that some
10546     // of the store nodes that we found may not be selected for inclusion
10547     // in the wide store. The chain we use needs to be the chain of the
10548     // latest store node which is *used* and replaced by the wide store.
10549     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10550       LatestNodeUsed = i;
10551   }
10552
10553   // The latest Node in the DAG.
10554   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10555   SDLoc DL(StoreNodes[0].MemNode);
10556
10557   SDValue StoredVal;
10558   if (UseVector) {
10559     // Find a legal type for the vector store.
10560     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10561     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10562     if (IsConstantSrc) {
10563       // A vector store with a constant source implies that the constant is
10564       // zero; we only handle merging stores of constant zeros because the zero
10565       // can be materialized without a load.
10566       // It may be beneficial to loosen this restriction to allow non-zero
10567       // store merging.
10568       StoredVal = DAG.getConstant(0, DL, Ty);
10569     } else {
10570       SmallVector<SDValue, 8> Ops;
10571       for (unsigned i = 0; i < NumElem ; ++i) {
10572         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10573         SDValue Val = St->getValue();
10574         // All of the operands of a BUILD_VECTOR must have the same type.
10575         if (Val.getValueType() != MemVT)
10576           return false;
10577         Ops.push_back(Val);
10578       }
10579
10580       // Build the extracted vector elements back into a vector.
10581       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10582     }
10583   } else {
10584     // We should always use a vector store when merging extracted vector
10585     // elements, so this path implies a store of constants.
10586     assert(IsConstantSrc && "Merged vector elements should use vector store");
10587
10588     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10589     APInt StoreInt(StoreBW, 0);
10590
10591     // Construct a single integer constant which is made of the smaller
10592     // constant inputs.
10593     bool IsLE = TLI.isLittleEndian();
10594     for (unsigned i = 0; i < NumElem ; ++i) {
10595       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10596       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10597       SDValue Val = St->getValue();
10598       StoreInt <<= ElementSizeBytes*8;
10599       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10600         StoreInt |= C->getAPIntValue().zext(StoreBW);
10601       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10602         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10603       } else {
10604         llvm_unreachable("Invalid constant element type");
10605       }
10606     }
10607
10608     // Create the new Load and Store operations.
10609     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10610     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10611   }
10612
10613   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10614                                   FirstInChain->getBasePtr(),
10615                                   FirstInChain->getPointerInfo(),
10616                                   false, false,
10617                                   FirstInChain->getAlignment());
10618
10619   // Replace the last store with the new store
10620   CombineTo(LatestOp, NewStore);
10621   // Erase all other stores.
10622   for (unsigned i = 0; i < NumElem ; ++i) {
10623     if (StoreNodes[i].MemNode == LatestOp)
10624       continue;
10625     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10626     // ReplaceAllUsesWith will replace all uses that existed when it was
10627     // called, but graph optimizations may cause new ones to appear. For
10628     // example, the case in pr14333 looks like
10629     //
10630     //  St's chain -> St -> another store -> X
10631     //
10632     // And the only difference from St to the other store is the chain.
10633     // When we change it's chain to be St's chain they become identical,
10634     // get CSEed and the net result is that X is now a use of St.
10635     // Since we know that St is redundant, just iterate.
10636     while (!St->use_empty())
10637       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10638     deleteAndRecombine(St);
10639   }
10640
10641   return true;
10642 }
10643
10644 static bool allowableAlignment(const SelectionDAG &DAG,
10645                                const TargetLowering &TLI, EVT EVTTy,
10646                                unsigned AS, unsigned Align) {
10647   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10648     return true;
10649
10650   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10651   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10652   return (Align >= ABIAlignment);
10653 }
10654
10655 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10656   if (OptLevel == CodeGenOpt::None)
10657     return false;
10658
10659   EVT MemVT = St->getMemoryVT();
10660   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10661   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10662       Attribute::NoImplicitFloat);
10663
10664   // This function cannot currently deal with non-byte-sized memory sizes.
10665   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10666     return false;
10667
10668   // Don't merge vectors into wider inputs.
10669   if (MemVT.isVector() || !MemVT.isSimple())
10670     return false;
10671
10672   // Perform an early exit check. Do not bother looking at stored values that
10673   // are not constants, loads, or extracted vector elements.
10674   SDValue StoredVal = St->getValue();
10675   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10676   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10677                        isa<ConstantFPSDNode>(StoredVal);
10678   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10679
10680   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10681     return false;
10682
10683   // Only look at ends of store sequences.
10684   SDValue Chain = SDValue(St, 0);
10685   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10686     return false;
10687
10688   // This holds the base pointer, index, and the offset in bytes from the base
10689   // pointer.
10690   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10691
10692   // We must have a base and an offset.
10693   if (!BasePtr.Base.getNode())
10694     return false;
10695
10696   // Do not handle stores to undef base pointers.
10697   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10698     return false;
10699
10700   // Save the LoadSDNodes that we find in the chain.
10701   // We need to make sure that these nodes do not interfere with
10702   // any of the store nodes.
10703   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10704
10705   // Save the StoreSDNodes that we find in the chain.
10706   SmallVector<MemOpLink, 8> StoreNodes;
10707
10708   // Walk up the chain and look for nodes with offsets from the same
10709   // base pointer. Stop when reaching an instruction with a different kind
10710   // or instruction which has a different base pointer.
10711   unsigned Seq = 0;
10712   StoreSDNode *Index = St;
10713   while (Index) {
10714     // If the chain has more than one use, then we can't reorder the mem ops.
10715     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10716       break;
10717
10718     // Find the base pointer and offset for this memory node.
10719     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10720
10721     // Check that the base pointer is the same as the original one.
10722     if (!Ptr.equalBaseIndex(BasePtr))
10723       break;
10724
10725     // The memory operands must not be volatile.
10726     if (Index->isVolatile() || Index->isIndexed())
10727       break;
10728
10729     // No truncation.
10730     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10731       if (St->isTruncatingStore())
10732         break;
10733
10734     // The stored memory type must be the same.
10735     if (Index->getMemoryVT() != MemVT)
10736       break;
10737
10738     // We found a potential memory operand to merge.
10739     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10740
10741     // Find the next memory operand in the chain. If the next operand in the
10742     // chain is a store then move up and continue the scan with the next
10743     // memory operand. If the next operand is a load save it and use alias
10744     // information to check if it interferes with anything.
10745     SDNode *NextInChain = Index->getChain().getNode();
10746     while (1) {
10747       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10748         // We found a store node. Use it for the next iteration.
10749         Index = STn;
10750         break;
10751       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10752         if (Ldn->isVolatile()) {
10753           Index = nullptr;
10754           break;
10755         }
10756
10757         // Save the load node for later. Continue the scan.
10758         AliasLoadNodes.push_back(Ldn);
10759         NextInChain = Ldn->getChain().getNode();
10760         continue;
10761       } else {
10762         Index = nullptr;
10763         break;
10764       }
10765     }
10766   }
10767
10768   // Check if there is anything to merge.
10769   if (StoreNodes.size() < 2)
10770     return false;
10771
10772   // Sort the memory operands according to their distance from the base pointer.
10773   std::sort(StoreNodes.begin(), StoreNodes.end(),
10774             [](MemOpLink LHS, MemOpLink RHS) {
10775     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10776            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10777             LHS.SequenceNum > RHS.SequenceNum);
10778   });
10779
10780   // Scan the memory operations on the chain and find the first non-consecutive
10781   // store memory address.
10782   unsigned LastConsecutiveStore = 0;
10783   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10784   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10785
10786     // Check that the addresses are consecutive starting from the second
10787     // element in the list of stores.
10788     if (i > 0) {
10789       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10790       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10791         break;
10792     }
10793
10794     bool Alias = false;
10795     // Check if this store interferes with any of the loads that we found.
10796     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10797       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10798         Alias = true;
10799         break;
10800       }
10801     // We found a load that alias with this store. Stop the sequence.
10802     if (Alias)
10803       break;
10804
10805     // Mark this node as useful.
10806     LastConsecutiveStore = i;
10807   }
10808
10809   // The node with the lowest store address.
10810   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10811   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10812   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10813
10814   // Store the constants into memory as one consecutive store.
10815   if (IsConstantSrc) {
10816     unsigned LastLegalType = 0;
10817     unsigned LastLegalVectorType = 0;
10818     bool NonZero = false;
10819     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10820       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10821       SDValue StoredVal = St->getValue();
10822
10823       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10824         NonZero |= !C->isNullValue();
10825       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10826         NonZero |= !C->getConstantFPValue()->isNullValue();
10827       } else {
10828         // Non-constant.
10829         break;
10830       }
10831
10832       // Find a legal type for the constant store.
10833       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10834       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10835       if (TLI.isTypeLegal(StoreTy) &&
10836           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10837                              FirstStoreAlign)) {
10838         LastLegalType = i+1;
10839       // Or check whether a truncstore is legal.
10840       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10841                  TargetLowering::TypePromoteInteger) {
10842         EVT LegalizedStoredValueTy =
10843           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10844         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10845             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10846                                FirstStoreAlign)) {
10847           LastLegalType = i + 1;
10848         }
10849       }
10850
10851       // Find a legal type for the vector store.
10852       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10853       if (TLI.isTypeLegal(Ty) &&
10854           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10855         LastLegalVectorType = i + 1;
10856       }
10857     }
10858
10859     // We only use vectors if the constant is known to be zero and the
10860     // function is not marked with the noimplicitfloat attribute.
10861     if (NonZero || NoVectors)
10862       LastLegalVectorType = 0;
10863
10864     // Check if we found a legal integer type to store.
10865     if (LastLegalType == 0 && LastLegalVectorType == 0)
10866       return false;
10867
10868     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10869     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10870
10871     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10872                                            true, UseVector);
10873   }
10874
10875   // When extracting multiple vector elements, try to store them
10876   // in one vector store rather than a sequence of scalar stores.
10877   if (IsExtractVecEltSrc) {
10878     unsigned NumElem = 0;
10879     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10880       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10881       SDValue StoredVal = St->getValue();
10882       // This restriction could be loosened.
10883       // Bail out if any stored values are not elements extracted from a vector.
10884       // It should be possible to handle mixed sources, but load sources need
10885       // more careful handling (see the block of code below that handles
10886       // consecutive loads).
10887       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10888         return false;
10889
10890       // Find a legal type for the vector store.
10891       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10892       if (TLI.isTypeLegal(Ty) &&
10893           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10894         NumElem = i + 1;
10895     }
10896
10897     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10898                                            false, true);
10899   }
10900
10901   // Below we handle the case of multiple consecutive stores that
10902   // come from multiple consecutive loads. We merge them into a single
10903   // wide load and a single wide store.
10904
10905   // Look for load nodes which are used by the stored values.
10906   SmallVector<MemOpLink, 8> LoadNodes;
10907
10908   // Find acceptable loads. Loads need to have the same chain (token factor),
10909   // must not be zext, volatile, indexed, and they must be consecutive.
10910   BaseIndexOffset LdBasePtr;
10911   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10912     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10913     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10914     if (!Ld) break;
10915
10916     // Loads must only have one use.
10917     if (!Ld->hasNUsesOfValue(1, 0))
10918       break;
10919
10920     // The memory operands must not be volatile.
10921     if (Ld->isVolatile() || Ld->isIndexed())
10922       break;
10923
10924     // We do not accept ext loads.
10925     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10926       break;
10927
10928     // The stored memory type must be the same.
10929     if (Ld->getMemoryVT() != MemVT)
10930       break;
10931
10932     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10933     // If this is not the first ptr that we check.
10934     if (LdBasePtr.Base.getNode()) {
10935       // The base ptr must be the same.
10936       if (!LdPtr.equalBaseIndex(LdBasePtr))
10937         break;
10938     } else {
10939       // Check that all other base pointers are the same as this one.
10940       LdBasePtr = LdPtr;
10941     }
10942
10943     // We found a potential memory operand to merge.
10944     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10945   }
10946
10947   if (LoadNodes.size() < 2)
10948     return false;
10949
10950   // If we have load/store pair instructions and we only have two values,
10951   // don't bother.
10952   unsigned RequiredAlignment;
10953   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10954       St->getAlignment() >= RequiredAlignment)
10955     return false;
10956
10957   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10958   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10959   unsigned FirstLoadAlign = FirstLoad->getAlignment();
10960
10961   // Scan the memory operations on the chain and find the first non-consecutive
10962   // load memory address. These variables hold the index in the store node
10963   // array.
10964   unsigned LastConsecutiveLoad = 0;
10965   // This variable refers to the size and not index in the array.
10966   unsigned LastLegalVectorType = 0;
10967   unsigned LastLegalIntegerType = 0;
10968   StartAddress = LoadNodes[0].OffsetFromBase;
10969   SDValue FirstChain = FirstLoad->getChain();
10970   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10971     // All loads much share the same chain.
10972     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10973       break;
10974
10975     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10976     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10977       break;
10978     LastConsecutiveLoad = i;
10979
10980     // Find a legal type for the vector store.
10981     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10982     if (TLI.isTypeLegal(StoreTy) &&
10983         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10984         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
10985       LastLegalVectorType = i + 1;
10986     }
10987
10988     // Find a legal type for the integer store.
10989     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10990     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10991     if (TLI.isTypeLegal(StoreTy) &&
10992         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10993         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
10994       LastLegalIntegerType = i + 1;
10995     // Or check whether a truncstore and extload is legal.
10996     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10997              TargetLowering::TypePromoteInteger) {
10998       EVT LegalizedStoredValueTy =
10999         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11000       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11001           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11002           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11003           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11004           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11005                              FirstStoreAlign) &&
11006           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11007                              FirstLoadAlign))
11008         LastLegalIntegerType = i+1;
11009     }
11010   }
11011
11012   // Only use vector types if the vector type is larger than the integer type.
11013   // If they are the same, use integers.
11014   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11015   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11016
11017   // We add +1 here because the LastXXX variables refer to location while
11018   // the NumElem refers to array/index size.
11019   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11020   NumElem = std::min(LastLegalType, NumElem);
11021
11022   if (NumElem < 2)
11023     return false;
11024
11025   // The latest Node in the DAG.
11026   unsigned LatestNodeUsed = 0;
11027   for (unsigned i=1; i<NumElem; ++i) {
11028     // Find a chain for the new wide-store operand. Notice that some
11029     // of the store nodes that we found may not be selected for inclusion
11030     // in the wide store. The chain we use needs to be the chain of the
11031     // latest store node which is *used* and replaced by the wide store.
11032     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11033       LatestNodeUsed = i;
11034   }
11035
11036   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11037
11038   // Find if it is better to use vectors or integers to load and store
11039   // to memory.
11040   EVT JointMemOpVT;
11041   if (UseVectorTy) {
11042     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11043   } else {
11044     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11045     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11046   }
11047
11048   SDLoc LoadDL(LoadNodes[0].MemNode);
11049   SDLoc StoreDL(StoreNodes[0].MemNode);
11050
11051   SDValue NewLoad = DAG.getLoad(
11052       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11053       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11054
11055   SDValue NewStore = DAG.getStore(
11056       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11057       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11058
11059   // Replace one of the loads with the new load.
11060   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11061   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11062                                 SDValue(NewLoad.getNode(), 1));
11063
11064   // Remove the rest of the load chains.
11065   for (unsigned i = 1; i < NumElem ; ++i) {
11066     // Replace all chain users of the old load nodes with the chain of the new
11067     // load node.
11068     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11069     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11070   }
11071
11072   // Replace the last store with the new store.
11073   CombineTo(LatestOp, NewStore);
11074   // Erase all other stores.
11075   for (unsigned i = 0; i < NumElem ; ++i) {
11076     // Remove all Store nodes.
11077     if (StoreNodes[i].MemNode == LatestOp)
11078       continue;
11079     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11080     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11081     deleteAndRecombine(St);
11082   }
11083
11084   return true;
11085 }
11086
11087 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11088   StoreSDNode *ST  = cast<StoreSDNode>(N);
11089   SDValue Chain = ST->getChain();
11090   SDValue Value = ST->getValue();
11091   SDValue Ptr   = ST->getBasePtr();
11092
11093   // If this is a store of a bit convert, store the input value if the
11094   // resultant store does not need a higher alignment than the original.
11095   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11096       ST->isUnindexed()) {
11097     unsigned OrigAlign = ST->getAlignment();
11098     EVT SVT = Value.getOperand(0).getValueType();
11099     unsigned Align = TLI.getDataLayout()->
11100       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11101     if (Align <= OrigAlign &&
11102         ((!LegalOperations && !ST->isVolatile()) ||
11103          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11104       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11105                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11106                           ST->isNonTemporal(), OrigAlign,
11107                           ST->getAAInfo());
11108   }
11109
11110   // Turn 'store undef, Ptr' -> nothing.
11111   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11112     return Chain;
11113
11114   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11115   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11116     // NOTE: If the original store is volatile, this transform must not increase
11117     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11118     // processor operation but an i64 (which is not legal) requires two.  So the
11119     // transform should not be done in this case.
11120     if (Value.getOpcode() != ISD::TargetConstantFP) {
11121       SDValue Tmp;
11122       switch (CFP->getSimpleValueType(0).SimpleTy) {
11123       default: llvm_unreachable("Unknown FP type");
11124       case MVT::f16:    // We don't do this for these yet.
11125       case MVT::f80:
11126       case MVT::f128:
11127       case MVT::ppcf128:
11128         break;
11129       case MVT::f32:
11130         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11131             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11132           ;
11133           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11134                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11135                               MVT::i32);
11136           return DAG.getStore(Chain, SDLoc(N), Tmp,
11137                               Ptr, ST->getMemOperand());
11138         }
11139         break;
11140       case MVT::f64:
11141         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11142              !ST->isVolatile()) ||
11143             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11144           ;
11145           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11146                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11147           return DAG.getStore(Chain, SDLoc(N), Tmp,
11148                               Ptr, ST->getMemOperand());
11149         }
11150
11151         if (!ST->isVolatile() &&
11152             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11153           // Many FP stores are not made apparent until after legalize, e.g. for
11154           // argument passing.  Since this is so common, custom legalize the
11155           // 64-bit integer store into two 32-bit stores.
11156           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11157           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11158           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11159           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11160
11161           unsigned Alignment = ST->getAlignment();
11162           bool isVolatile = ST->isVolatile();
11163           bool isNonTemporal = ST->isNonTemporal();
11164           AAMDNodes AAInfo = ST->getAAInfo();
11165
11166           SDLoc DL(N);
11167
11168           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11169                                      Ptr, ST->getPointerInfo(),
11170                                      isVolatile, isNonTemporal,
11171                                      ST->getAlignment(), AAInfo);
11172           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11173                             DAG.getConstant(4, DL, Ptr.getValueType()));
11174           Alignment = MinAlign(Alignment, 4U);
11175           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11176                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11177                                      isVolatile, isNonTemporal,
11178                                      Alignment, AAInfo);
11179           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11180                              St0, St1);
11181         }
11182
11183         break;
11184       }
11185     }
11186   }
11187
11188   // Try to infer better alignment information than the store already has.
11189   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11190     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11191       if (Align > ST->getAlignment()) {
11192         SDValue NewStore =
11193                DAG.getTruncStore(Chain, SDLoc(N), Value,
11194                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11195                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11196                                  ST->getAAInfo());
11197         if (NewStore.getNode() != N)
11198           return CombineTo(ST, NewStore, true);
11199       }
11200     }
11201   }
11202
11203   // Try transforming a pair floating point load / store ops to integer
11204   // load / store ops.
11205   SDValue NewST = TransformFPLoadStorePair(N);
11206   if (NewST.getNode())
11207     return NewST;
11208
11209   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11210                                                   : DAG.getSubtarget().useAA();
11211 #ifndef NDEBUG
11212   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11213       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11214     UseAA = false;
11215 #endif
11216   if (UseAA && ST->isUnindexed()) {
11217     // Walk up chain skipping non-aliasing memory nodes.
11218     SDValue BetterChain = FindBetterChain(N, Chain);
11219
11220     // If there is a better chain.
11221     if (Chain != BetterChain) {
11222       SDValue ReplStore;
11223
11224       // Replace the chain to avoid dependency.
11225       if (ST->isTruncatingStore()) {
11226         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11227                                       ST->getMemoryVT(), ST->getMemOperand());
11228       } else {
11229         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11230                                  ST->getMemOperand());
11231       }
11232
11233       // Create token to keep both nodes around.
11234       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11235                                   MVT::Other, Chain, ReplStore);
11236
11237       // Make sure the new and old chains are cleaned up.
11238       AddToWorklist(Token.getNode());
11239
11240       // Don't add users to work list.
11241       return CombineTo(N, Token, false);
11242     }
11243   }
11244
11245   // Try transforming N to an indexed store.
11246   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11247     return SDValue(N, 0);
11248
11249   // FIXME: is there such a thing as a truncating indexed store?
11250   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11251       Value.getValueType().isInteger()) {
11252     // See if we can simplify the input to this truncstore with knowledge that
11253     // only the low bits are being used.  For example:
11254     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11255     SDValue Shorter =
11256       GetDemandedBits(Value,
11257                       APInt::getLowBitsSet(
11258                         Value.getValueType().getScalarType().getSizeInBits(),
11259                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11260     AddToWorklist(Value.getNode());
11261     if (Shorter.getNode())
11262       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11263                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11264
11265     // Otherwise, see if we can simplify the operation with
11266     // SimplifyDemandedBits, which only works if the value has a single use.
11267     if (SimplifyDemandedBits(Value,
11268                         APInt::getLowBitsSet(
11269                           Value.getValueType().getScalarType().getSizeInBits(),
11270                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11271       return SDValue(N, 0);
11272   }
11273
11274   // If this is a load followed by a store to the same location, then the store
11275   // is dead/noop.
11276   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11277     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11278         ST->isUnindexed() && !ST->isVolatile() &&
11279         // There can't be any side effects between the load and store, such as
11280         // a call or store.
11281         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11282       // The store is dead, remove it.
11283       return Chain;
11284     }
11285   }
11286
11287   // If this is a store followed by a store with the same value to the same
11288   // location, then the store is dead/noop.
11289   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11290     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11291         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11292         ST1->isUnindexed() && !ST1->isVolatile()) {
11293       // The store is dead, remove it.
11294       return Chain;
11295     }
11296   }
11297
11298   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11299   // truncating store.  We can do this even if this is already a truncstore.
11300   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11301       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11302       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11303                             ST->getMemoryVT())) {
11304     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11305                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11306   }
11307
11308   // Only perform this optimization before the types are legal, because we
11309   // don't want to perform this optimization on every DAGCombine invocation.
11310   if (!LegalTypes) {
11311     bool EverChanged = false;
11312
11313     do {
11314       // There can be multiple store sequences on the same chain.
11315       // Keep trying to merge store sequences until we are unable to do so
11316       // or until we merge the last store on the chain.
11317       bool Changed = MergeConsecutiveStores(ST);
11318       EverChanged |= Changed;
11319       if (!Changed) break;
11320     } while (ST->getOpcode() != ISD::DELETED_NODE);
11321
11322     if (EverChanged)
11323       return SDValue(N, 0);
11324   }
11325
11326   return ReduceLoadOpStoreWidth(N);
11327 }
11328
11329 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11330   SDValue InVec = N->getOperand(0);
11331   SDValue InVal = N->getOperand(1);
11332   SDValue EltNo = N->getOperand(2);
11333   SDLoc dl(N);
11334
11335   // If the inserted element is an UNDEF, just use the input vector.
11336   if (InVal.getOpcode() == ISD::UNDEF)
11337     return InVec;
11338
11339   EVT VT = InVec.getValueType();
11340
11341   // If we can't generate a legal BUILD_VECTOR, exit
11342   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11343     return SDValue();
11344
11345   // Check that we know which element is being inserted
11346   if (!isa<ConstantSDNode>(EltNo))
11347     return SDValue();
11348   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11349
11350   // Canonicalize insert_vector_elt dag nodes.
11351   // Example:
11352   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11353   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11354   //
11355   // Do this only if the child insert_vector node has one use; also
11356   // do this only if indices are both constants and Idx1 < Idx0.
11357   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11358       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11359     unsigned OtherElt =
11360       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11361     if (Elt < OtherElt) {
11362       // Swap nodes.
11363       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11364                                   InVec.getOperand(0), InVal, EltNo);
11365       AddToWorklist(NewOp.getNode());
11366       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11367                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11368     }
11369   }
11370
11371   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11372   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11373   // vector elements.
11374   SmallVector<SDValue, 8> Ops;
11375   // Do not combine these two vectors if the output vector will not replace
11376   // the input vector.
11377   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11378     Ops.append(InVec.getNode()->op_begin(),
11379                InVec.getNode()->op_end());
11380   } else if (InVec.getOpcode() == ISD::UNDEF) {
11381     unsigned NElts = VT.getVectorNumElements();
11382     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11383   } else {
11384     return SDValue();
11385   }
11386
11387   // Insert the element
11388   if (Elt < Ops.size()) {
11389     // All the operands of BUILD_VECTOR must have the same type;
11390     // we enforce that here.
11391     EVT OpVT = Ops[0].getValueType();
11392     if (InVal.getValueType() != OpVT)
11393       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11394                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11395                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11396     Ops[Elt] = InVal;
11397   }
11398
11399   // Return the new vector
11400   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11401 }
11402
11403 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11404     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11405   EVT ResultVT = EVE->getValueType(0);
11406   EVT VecEltVT = InVecVT.getVectorElementType();
11407   unsigned Align = OriginalLoad->getAlignment();
11408   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11409       VecEltVT.getTypeForEVT(*DAG.getContext()));
11410
11411   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11412     return SDValue();
11413
11414   Align = NewAlign;
11415
11416   SDValue NewPtr = OriginalLoad->getBasePtr();
11417   SDValue Offset;
11418   EVT PtrType = NewPtr.getValueType();
11419   MachinePointerInfo MPI;
11420   SDLoc DL(EVE);
11421   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11422     int Elt = ConstEltNo->getZExtValue();
11423     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11424     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11425     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11426   } else {
11427     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11428     Offset = DAG.getNode(
11429         ISD::MUL, DL, PtrType, Offset,
11430         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11431     MPI = OriginalLoad->getPointerInfo();
11432   }
11433   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11434
11435   // The replacement we need to do here is a little tricky: we need to
11436   // replace an extractelement of a load with a load.
11437   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11438   // Note that this replacement assumes that the extractvalue is the only
11439   // use of the load; that's okay because we don't want to perform this
11440   // transformation in other cases anyway.
11441   SDValue Load;
11442   SDValue Chain;
11443   if (ResultVT.bitsGT(VecEltVT)) {
11444     // If the result type of vextract is wider than the load, then issue an
11445     // extending load instead.
11446     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11447                                                   VecEltVT)
11448                                    ? ISD::ZEXTLOAD
11449                                    : ISD::EXTLOAD;
11450     Load = DAG.getExtLoad(
11451         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11452         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11453         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11454     Chain = Load.getValue(1);
11455   } else {
11456     Load = DAG.getLoad(
11457         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11458         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11459         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11460     Chain = Load.getValue(1);
11461     if (ResultVT.bitsLT(VecEltVT))
11462       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11463     else
11464       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11465   }
11466   WorklistRemover DeadNodes(*this);
11467   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11468   SDValue To[] = { Load, Chain };
11469   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11470   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11471   // worklist explicitly as well.
11472   AddToWorklist(Load.getNode());
11473   AddUsersToWorklist(Load.getNode()); // Add users too
11474   // Make sure to revisit this node to clean it up; it will usually be dead.
11475   AddToWorklist(EVE);
11476   ++OpsNarrowed;
11477   return SDValue(EVE, 0);
11478 }
11479
11480 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11481   // (vextract (scalar_to_vector val, 0) -> val
11482   SDValue InVec = N->getOperand(0);
11483   EVT VT = InVec.getValueType();
11484   EVT NVT = N->getValueType(0);
11485
11486   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11487     // Check if the result type doesn't match the inserted element type. A
11488     // SCALAR_TO_VECTOR may truncate the inserted element and the
11489     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11490     SDValue InOp = InVec.getOperand(0);
11491     if (InOp.getValueType() != NVT) {
11492       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11493       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11494     }
11495     return InOp;
11496   }
11497
11498   SDValue EltNo = N->getOperand(1);
11499   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11500
11501   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11502   // We only perform this optimization before the op legalization phase because
11503   // we may introduce new vector instructions which are not backed by TD
11504   // patterns. For example on AVX, extracting elements from a wide vector
11505   // without using extract_subvector. However, if we can find an underlying
11506   // scalar value, then we can always use that.
11507   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11508       && ConstEltNo) {
11509     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11510     int NumElem = VT.getVectorNumElements();
11511     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11512     // Find the new index to extract from.
11513     int OrigElt = SVOp->getMaskElt(Elt);
11514
11515     // Extracting an undef index is undef.
11516     if (OrigElt == -1)
11517       return DAG.getUNDEF(NVT);
11518
11519     // Select the right vector half to extract from.
11520     SDValue SVInVec;
11521     if (OrigElt < NumElem) {
11522       SVInVec = InVec->getOperand(0);
11523     } else {
11524       SVInVec = InVec->getOperand(1);
11525       OrigElt -= NumElem;
11526     }
11527
11528     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11529       SDValue InOp = SVInVec.getOperand(OrigElt);
11530       if (InOp.getValueType() != NVT) {
11531         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11532         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11533       }
11534
11535       return InOp;
11536     }
11537
11538     // FIXME: We should handle recursing on other vector shuffles and
11539     // scalar_to_vector here as well.
11540
11541     if (!LegalOperations) {
11542       EVT IndexTy = TLI.getVectorIdxTy();
11543       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11544                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11545     }
11546   }
11547
11548   bool BCNumEltsChanged = false;
11549   EVT ExtVT = VT.getVectorElementType();
11550   EVT LVT = ExtVT;
11551
11552   // If the result of load has to be truncated, then it's not necessarily
11553   // profitable.
11554   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11555     return SDValue();
11556
11557   if (InVec.getOpcode() == ISD::BITCAST) {
11558     // Don't duplicate a load with other uses.
11559     if (!InVec.hasOneUse())
11560       return SDValue();
11561
11562     EVT BCVT = InVec.getOperand(0).getValueType();
11563     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11564       return SDValue();
11565     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11566       BCNumEltsChanged = true;
11567     InVec = InVec.getOperand(0);
11568     ExtVT = BCVT.getVectorElementType();
11569   }
11570
11571   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11572   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11573       ISD::isNormalLoad(InVec.getNode()) &&
11574       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11575     SDValue Index = N->getOperand(1);
11576     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11577       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11578                                                            OrigLoad);
11579   }
11580
11581   // Perform only after legalization to ensure build_vector / vector_shuffle
11582   // optimizations have already been done.
11583   if (!LegalOperations) return SDValue();
11584
11585   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11586   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11587   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11588
11589   if (ConstEltNo) {
11590     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11591
11592     LoadSDNode *LN0 = nullptr;
11593     const ShuffleVectorSDNode *SVN = nullptr;
11594     if (ISD::isNormalLoad(InVec.getNode())) {
11595       LN0 = cast<LoadSDNode>(InVec);
11596     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11597                InVec.getOperand(0).getValueType() == ExtVT &&
11598                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11599       // Don't duplicate a load with other uses.
11600       if (!InVec.hasOneUse())
11601         return SDValue();
11602
11603       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11604     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11605       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11606       // =>
11607       // (load $addr+1*size)
11608
11609       // Don't duplicate a load with other uses.
11610       if (!InVec.hasOneUse())
11611         return SDValue();
11612
11613       // If the bit convert changed the number of elements, it is unsafe
11614       // to examine the mask.
11615       if (BCNumEltsChanged)
11616         return SDValue();
11617
11618       // Select the input vector, guarding against out of range extract vector.
11619       unsigned NumElems = VT.getVectorNumElements();
11620       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11621       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11622
11623       if (InVec.getOpcode() == ISD::BITCAST) {
11624         // Don't duplicate a load with other uses.
11625         if (!InVec.hasOneUse())
11626           return SDValue();
11627
11628         InVec = InVec.getOperand(0);
11629       }
11630       if (ISD::isNormalLoad(InVec.getNode())) {
11631         LN0 = cast<LoadSDNode>(InVec);
11632         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11633         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11634       }
11635     }
11636
11637     // Make sure we found a non-volatile load and the extractelement is
11638     // the only use.
11639     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11640       return SDValue();
11641
11642     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11643     if (Elt == -1)
11644       return DAG.getUNDEF(LVT);
11645
11646     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11647   }
11648
11649   return SDValue();
11650 }
11651
11652 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11653 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11654   // We perform this optimization post type-legalization because
11655   // the type-legalizer often scalarizes integer-promoted vectors.
11656   // Performing this optimization before may create bit-casts which
11657   // will be type-legalized to complex code sequences.
11658   // We perform this optimization only before the operation legalizer because we
11659   // may introduce illegal operations.
11660   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11661     return SDValue();
11662
11663   unsigned NumInScalars = N->getNumOperands();
11664   SDLoc dl(N);
11665   EVT VT = N->getValueType(0);
11666
11667   // Check to see if this is a BUILD_VECTOR of a bunch of values
11668   // which come from any_extend or zero_extend nodes. If so, we can create
11669   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11670   // optimizations. We do not handle sign-extend because we can't fill the sign
11671   // using shuffles.
11672   EVT SourceType = MVT::Other;
11673   bool AllAnyExt = true;
11674
11675   for (unsigned i = 0; i != NumInScalars; ++i) {
11676     SDValue In = N->getOperand(i);
11677     // Ignore undef inputs.
11678     if (In.getOpcode() == ISD::UNDEF) continue;
11679
11680     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11681     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11682
11683     // Abort if the element is not an extension.
11684     if (!ZeroExt && !AnyExt) {
11685       SourceType = MVT::Other;
11686       break;
11687     }
11688
11689     // The input is a ZeroExt or AnyExt. Check the original type.
11690     EVT InTy = In.getOperand(0).getValueType();
11691
11692     // Check that all of the widened source types are the same.
11693     if (SourceType == MVT::Other)
11694       // First time.
11695       SourceType = InTy;
11696     else if (InTy != SourceType) {
11697       // Multiple income types. Abort.
11698       SourceType = MVT::Other;
11699       break;
11700     }
11701
11702     // Check if all of the extends are ANY_EXTENDs.
11703     AllAnyExt &= AnyExt;
11704   }
11705
11706   // In order to have valid types, all of the inputs must be extended from the
11707   // same source type and all of the inputs must be any or zero extend.
11708   // Scalar sizes must be a power of two.
11709   EVT OutScalarTy = VT.getScalarType();
11710   bool ValidTypes = SourceType != MVT::Other &&
11711                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11712                  isPowerOf2_32(SourceType.getSizeInBits());
11713
11714   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11715   // turn into a single shuffle instruction.
11716   if (!ValidTypes)
11717     return SDValue();
11718
11719   bool isLE = TLI.isLittleEndian();
11720   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11721   assert(ElemRatio > 1 && "Invalid element size ratio");
11722   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11723                                DAG.getConstant(0, SDLoc(N), SourceType);
11724
11725   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11726   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11727
11728   // Populate the new build_vector
11729   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11730     SDValue Cast = N->getOperand(i);
11731     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11732             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11733             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11734     SDValue In;
11735     if (Cast.getOpcode() == ISD::UNDEF)
11736       In = DAG.getUNDEF(SourceType);
11737     else
11738       In = Cast->getOperand(0);
11739     unsigned Index = isLE ? (i * ElemRatio) :
11740                             (i * ElemRatio + (ElemRatio - 1));
11741
11742     assert(Index < Ops.size() && "Invalid index");
11743     Ops[Index] = In;
11744   }
11745
11746   // The type of the new BUILD_VECTOR node.
11747   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11748   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11749          "Invalid vector size");
11750   // Check if the new vector type is legal.
11751   if (!isTypeLegal(VecVT)) return SDValue();
11752
11753   // Make the new BUILD_VECTOR.
11754   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11755
11756   // The new BUILD_VECTOR node has the potential to be further optimized.
11757   AddToWorklist(BV.getNode());
11758   // Bitcast to the desired type.
11759   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11760 }
11761
11762 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11763   EVT VT = N->getValueType(0);
11764
11765   unsigned NumInScalars = N->getNumOperands();
11766   SDLoc dl(N);
11767
11768   EVT SrcVT = MVT::Other;
11769   unsigned Opcode = ISD::DELETED_NODE;
11770   unsigned NumDefs = 0;
11771
11772   for (unsigned i = 0; i != NumInScalars; ++i) {
11773     SDValue In = N->getOperand(i);
11774     unsigned Opc = In.getOpcode();
11775
11776     if (Opc == ISD::UNDEF)
11777       continue;
11778
11779     // If all scalar values are floats and converted from integers.
11780     if (Opcode == ISD::DELETED_NODE &&
11781         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11782       Opcode = Opc;
11783     }
11784
11785     if (Opc != Opcode)
11786       return SDValue();
11787
11788     EVT InVT = In.getOperand(0).getValueType();
11789
11790     // If all scalar values are typed differently, bail out. It's chosen to
11791     // simplify BUILD_VECTOR of integer types.
11792     if (SrcVT == MVT::Other)
11793       SrcVT = InVT;
11794     if (SrcVT != InVT)
11795       return SDValue();
11796     NumDefs++;
11797   }
11798
11799   // If the vector has just one element defined, it's not worth to fold it into
11800   // a vectorized one.
11801   if (NumDefs < 2)
11802     return SDValue();
11803
11804   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11805          && "Should only handle conversion from integer to float.");
11806   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11807
11808   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11809
11810   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11811     return SDValue();
11812
11813   // Just because the floating-point vector type is legal does not necessarily
11814   // mean that the corresponding integer vector type is.
11815   if (!isTypeLegal(NVT))
11816     return SDValue();
11817
11818   SmallVector<SDValue, 8> Opnds;
11819   for (unsigned i = 0; i != NumInScalars; ++i) {
11820     SDValue In = N->getOperand(i);
11821
11822     if (In.getOpcode() == ISD::UNDEF)
11823       Opnds.push_back(DAG.getUNDEF(SrcVT));
11824     else
11825       Opnds.push_back(In.getOperand(0));
11826   }
11827   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11828   AddToWorklist(BV.getNode());
11829
11830   return DAG.getNode(Opcode, dl, VT, BV);
11831 }
11832
11833 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11834   unsigned NumInScalars = N->getNumOperands();
11835   SDLoc dl(N);
11836   EVT VT = N->getValueType(0);
11837
11838   // A vector built entirely of undefs is undef.
11839   if (ISD::allOperandsUndef(N))
11840     return DAG.getUNDEF(VT);
11841
11842   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11843     return V;
11844
11845   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11846     return V;
11847
11848   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11849   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11850   // at most two distinct vectors, turn this into a shuffle node.
11851
11852   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11853   if (!isTypeLegal(VT))
11854     return SDValue();
11855
11856   // May only combine to shuffle after legalize if shuffle is legal.
11857   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11858     return SDValue();
11859
11860   SDValue VecIn1, VecIn2;
11861   bool UsesZeroVector = false;
11862   for (unsigned i = 0; i != NumInScalars; ++i) {
11863     SDValue Op = N->getOperand(i);
11864     // Ignore undef inputs.
11865     if (Op.getOpcode() == ISD::UNDEF) continue;
11866
11867     // See if we can combine this build_vector into a blend with a zero vector.
11868     if (!VecIn2.getNode() && (isNullConstant(Op) ||
11869         (Op.getOpcode() == ISD::ConstantFP &&
11870         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11871       UsesZeroVector = true;
11872       continue;
11873     }
11874
11875     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11876     // constant index, bail out.
11877     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11878         !isa<ConstantSDNode>(Op.getOperand(1))) {
11879       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11880       break;
11881     }
11882
11883     // We allow up to two distinct input vectors.
11884     SDValue ExtractedFromVec = Op.getOperand(0);
11885     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11886       continue;
11887
11888     if (!VecIn1.getNode()) {
11889       VecIn1 = ExtractedFromVec;
11890     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11891       VecIn2 = ExtractedFromVec;
11892     } else {
11893       // Too many inputs.
11894       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11895       break;
11896     }
11897   }
11898
11899   // If everything is good, we can make a shuffle operation.
11900   if (VecIn1.getNode()) {
11901     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11902     SmallVector<int, 8> Mask;
11903     for (unsigned i = 0; i != NumInScalars; ++i) {
11904       unsigned Opcode = N->getOperand(i).getOpcode();
11905       if (Opcode == ISD::UNDEF) {
11906         Mask.push_back(-1);
11907         continue;
11908       }
11909
11910       // Operands can also be zero.
11911       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11912         assert(UsesZeroVector &&
11913                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11914                "Unexpected node found!");
11915         Mask.push_back(NumInScalars+i);
11916         continue;
11917       }
11918
11919       // If extracting from the first vector, just use the index directly.
11920       SDValue Extract = N->getOperand(i);
11921       SDValue ExtVal = Extract.getOperand(1);
11922       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11923       if (Extract.getOperand(0) == VecIn1) {
11924         Mask.push_back(ExtIndex);
11925         continue;
11926       }
11927
11928       // Otherwise, use InIdx + InputVecSize
11929       Mask.push_back(InNumElements + ExtIndex);
11930     }
11931
11932     // Avoid introducing illegal shuffles with zero.
11933     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11934       return SDValue();
11935
11936     // We can't generate a shuffle node with mismatched input and output types.
11937     // Attempt to transform a single input vector to the correct type.
11938     if ((VT != VecIn1.getValueType())) {
11939       // If the input vector type has a different base type to the output
11940       // vector type, bail out.
11941       EVT VTElemType = VT.getVectorElementType();
11942       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11943           (VecIn2.getNode() &&
11944            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11945         return SDValue();
11946
11947       // If the input vector is too small, widen it.
11948       // We only support widening of vectors which are half the size of the
11949       // output registers. For example XMM->YMM widening on X86 with AVX.
11950       EVT VecInT = VecIn1.getValueType();
11951       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11952         // If we only have one small input, widen it by adding undef values.
11953         if (!VecIn2.getNode())
11954           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11955                                DAG.getUNDEF(VecIn1.getValueType()));
11956         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11957           // If we have two small inputs of the same type, try to concat them.
11958           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11959           VecIn2 = SDValue(nullptr, 0);
11960         } else
11961           return SDValue();
11962       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11963         // If the input vector is too large, try to split it.
11964         // We don't support having two input vectors that are too large.
11965         // If the zero vector was used, we can not split the vector,
11966         // since we'd need 3 inputs.
11967         if (UsesZeroVector || VecIn2.getNode())
11968           return SDValue();
11969
11970         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11971           return SDValue();
11972
11973         // Try to replace VecIn1 with two extract_subvectors
11974         // No need to update the masks, they should still be correct.
11975         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11976           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11977         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11978           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11979       } else
11980         return SDValue();
11981     }
11982
11983     if (UsesZeroVector)
11984       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11985                                 DAG.getConstantFP(0.0, dl, VT);
11986     else
11987       // If VecIn2 is unused then change it to undef.
11988       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11989
11990     // Check that we were able to transform all incoming values to the same
11991     // type.
11992     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11993         VecIn1.getValueType() != VT)
11994           return SDValue();
11995
11996     // Return the new VECTOR_SHUFFLE node.
11997     SDValue Ops[2];
11998     Ops[0] = VecIn1;
11999     Ops[1] = VecIn2;
12000     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12001   }
12002
12003   return SDValue();
12004 }
12005
12006 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12008   EVT OpVT = N->getOperand(0).getValueType();
12009
12010   // If the operands are legal vectors, leave them alone.
12011   if (TLI.isTypeLegal(OpVT))
12012     return SDValue();
12013
12014   SDLoc DL(N);
12015   EVT VT = N->getValueType(0);
12016   SmallVector<SDValue, 8> Ops;
12017
12018   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12019   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12020
12021   // Keep track of what we encounter.
12022   bool AnyInteger = false;
12023   bool AnyFP = false;
12024   for (const SDValue &Op : N->ops()) {
12025     if (ISD::BITCAST == Op.getOpcode() &&
12026         !Op.getOperand(0).getValueType().isVector())
12027       Ops.push_back(Op.getOperand(0));
12028     else if (ISD::UNDEF == Op.getOpcode())
12029       Ops.push_back(ScalarUndef);
12030     else
12031       return SDValue();
12032
12033     // Note whether we encounter an integer or floating point scalar.
12034     // If it's neither, bail out, it could be something weird like x86mmx.
12035     EVT LastOpVT = Ops.back().getValueType();
12036     if (LastOpVT.isFloatingPoint())
12037       AnyFP = true;
12038     else if (LastOpVT.isInteger())
12039       AnyInteger = true;
12040     else
12041       return SDValue();
12042   }
12043
12044   // If any of the operands is a floating point scalar bitcast to a vector,
12045   // use floating point types throughout, and bitcast everything.  
12046   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12047   if (AnyFP) {
12048     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12049     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12050     if (AnyInteger) {
12051       for (SDValue &Op : Ops) {
12052         if (Op.getValueType() == SVT)
12053           continue;
12054         if (Op.getOpcode() == ISD::UNDEF)
12055           Op = ScalarUndef;
12056         else
12057           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12058       }
12059     }
12060   }
12061
12062   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12063                                VT.getSizeInBits() / SVT.getSizeInBits());
12064   return DAG.getNode(ISD::BITCAST, DL, VT,
12065                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12066 }
12067
12068 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12069   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12070   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12071   // inputs come from at most two distinct vectors, turn this into a shuffle
12072   // node.
12073
12074   // If we only have one input vector, we don't need to do any concatenation.
12075   if (N->getNumOperands() == 1)
12076     return N->getOperand(0);
12077
12078   // Check if all of the operands are undefs.
12079   EVT VT = N->getValueType(0);
12080   if (ISD::allOperandsUndef(N))
12081     return DAG.getUNDEF(VT);
12082
12083   // Optimize concat_vectors where all but the first of the vectors are undef.
12084   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12085         return Op.getOpcode() == ISD::UNDEF;
12086       })) {
12087     SDValue In = N->getOperand(0);
12088     assert(In.getValueType().isVector() && "Must concat vectors");
12089
12090     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12091     if (In->getOpcode() == ISD::BITCAST &&
12092         !In->getOperand(0)->getValueType(0).isVector()) {
12093       SDValue Scalar = In->getOperand(0);
12094
12095       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12096       // look through the trunc so we can still do the transform:
12097       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12098       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12099           !TLI.isTypeLegal(Scalar.getValueType()) &&
12100           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12101         Scalar = Scalar->getOperand(0);
12102
12103       EVT SclTy = Scalar->getValueType(0);
12104
12105       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12106         return SDValue();
12107
12108       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12109                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12110       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12111         return SDValue();
12112
12113       SDLoc dl = SDLoc(N);
12114       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12115       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12116     }
12117   }
12118
12119   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12120   // We have already tested above for an UNDEF only concatenation.
12121   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12122   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12123   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12124     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12125   };
12126   bool AllBuildVectorsOrUndefs =
12127       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12128   if (AllBuildVectorsOrUndefs) {
12129     SmallVector<SDValue, 8> Opnds;
12130     EVT SVT = VT.getScalarType();
12131
12132     EVT MinVT = SVT;
12133     if (!SVT.isFloatingPoint()) {
12134       // If BUILD_VECTOR are from built from integer, they may have different
12135       // operand types. Get the smallest type and truncate all operands to it.
12136       bool FoundMinVT = false;
12137       for (const SDValue &Op : N->ops())
12138         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12139           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12140           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12141           FoundMinVT = true;
12142         }
12143       assert(FoundMinVT && "Concat vector type mismatch");
12144     }
12145
12146     for (const SDValue &Op : N->ops()) {
12147       EVT OpVT = Op.getValueType();
12148       unsigned NumElts = OpVT.getVectorNumElements();
12149
12150       if (ISD::UNDEF == Op.getOpcode())
12151         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12152
12153       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12154         if (SVT.isFloatingPoint()) {
12155           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12156           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12157         } else {
12158           for (unsigned i = 0; i != NumElts; ++i)
12159             Opnds.push_back(
12160                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12161         }
12162       }
12163     }
12164
12165     assert(VT.getVectorNumElements() == Opnds.size() &&
12166            "Concat vector type mismatch");
12167     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12168   }
12169
12170   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12171   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12172     return V;
12173
12174   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12175   // nodes often generate nop CONCAT_VECTOR nodes.
12176   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12177   // place the incoming vectors at the exact same location.
12178   SDValue SingleSource = SDValue();
12179   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12180
12181   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12182     SDValue Op = N->getOperand(i);
12183
12184     if (Op.getOpcode() == ISD::UNDEF)
12185       continue;
12186
12187     // Check if this is the identity extract:
12188     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12189       return SDValue();
12190
12191     // Find the single incoming vector for the extract_subvector.
12192     if (SingleSource.getNode()) {
12193       if (Op.getOperand(0) != SingleSource)
12194         return SDValue();
12195     } else {
12196       SingleSource = Op.getOperand(0);
12197
12198       // Check the source type is the same as the type of the result.
12199       // If not, this concat may extend the vector, so we can not
12200       // optimize it away.
12201       if (SingleSource.getValueType() != N->getValueType(0))
12202         return SDValue();
12203     }
12204
12205     unsigned IdentityIndex = i * PartNumElem;
12206     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12207     // The extract index must be constant.
12208     if (!CS)
12209       return SDValue();
12210
12211     // Check that we are reading from the identity index.
12212     if (CS->getZExtValue() != IdentityIndex)
12213       return SDValue();
12214   }
12215
12216   if (SingleSource.getNode())
12217     return SingleSource;
12218
12219   return SDValue();
12220 }
12221
12222 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12223   EVT NVT = N->getValueType(0);
12224   SDValue V = N->getOperand(0);
12225
12226   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12227     // Combine:
12228     //    (extract_subvec (concat V1, V2, ...), i)
12229     // Into:
12230     //    Vi if possible
12231     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12232     // type.
12233     if (V->getOperand(0).getValueType() != NVT)
12234       return SDValue();
12235     unsigned Idx = N->getConstantOperandVal(1);
12236     unsigned NumElems = NVT.getVectorNumElements();
12237     assert((Idx % NumElems) == 0 &&
12238            "IDX in concat is not a multiple of the result vector length.");
12239     return V->getOperand(Idx / NumElems);
12240   }
12241
12242   // Skip bitcasting
12243   if (V->getOpcode() == ISD::BITCAST)
12244     V = V.getOperand(0);
12245
12246   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12247     SDLoc dl(N);
12248     // Handle only simple case where vector being inserted and vector
12249     // being extracted are of same type, and are half size of larger vectors.
12250     EVT BigVT = V->getOperand(0).getValueType();
12251     EVT SmallVT = V->getOperand(1).getValueType();
12252     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12253       return SDValue();
12254
12255     // Only handle cases where both indexes are constants with the same type.
12256     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12257     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12258
12259     if (InsIdx && ExtIdx &&
12260         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12261         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12262       // Combine:
12263       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12264       // Into:
12265       //    indices are equal or bit offsets are equal => V1
12266       //    otherwise => (extract_subvec V1, ExtIdx)
12267       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12268           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12269         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12270       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12271                          DAG.getNode(ISD::BITCAST, dl,
12272                                      N->getOperand(0).getValueType(),
12273                                      V->getOperand(0)), N->getOperand(1));
12274     }
12275   }
12276
12277   return SDValue();
12278 }
12279
12280 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12281                                                  SDValue V, SelectionDAG &DAG) {
12282   SDLoc DL(V);
12283   EVT VT = V.getValueType();
12284
12285   switch (V.getOpcode()) {
12286   default:
12287     return V;
12288
12289   case ISD::CONCAT_VECTORS: {
12290     EVT OpVT = V->getOperand(0).getValueType();
12291     int OpSize = OpVT.getVectorNumElements();
12292     SmallBitVector OpUsedElements(OpSize, false);
12293     bool FoundSimplification = false;
12294     SmallVector<SDValue, 4> NewOps;
12295     NewOps.reserve(V->getNumOperands());
12296     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12297       SDValue Op = V->getOperand(i);
12298       bool OpUsed = false;
12299       for (int j = 0; j < OpSize; ++j)
12300         if (UsedElements[i * OpSize + j]) {
12301           OpUsedElements[j] = true;
12302           OpUsed = true;
12303         }
12304       NewOps.push_back(
12305           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12306                  : DAG.getUNDEF(OpVT));
12307       FoundSimplification |= Op == NewOps.back();
12308       OpUsedElements.reset();
12309     }
12310     if (FoundSimplification)
12311       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12312     return V;
12313   }
12314
12315   case ISD::INSERT_SUBVECTOR: {
12316     SDValue BaseV = V->getOperand(0);
12317     SDValue SubV = V->getOperand(1);
12318     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12319     if (!IdxN)
12320       return V;
12321
12322     int SubSize = SubV.getValueType().getVectorNumElements();
12323     int Idx = IdxN->getZExtValue();
12324     bool SubVectorUsed = false;
12325     SmallBitVector SubUsedElements(SubSize, false);
12326     for (int i = 0; i < SubSize; ++i)
12327       if (UsedElements[i + Idx]) {
12328         SubVectorUsed = true;
12329         SubUsedElements[i] = true;
12330         UsedElements[i + Idx] = false;
12331       }
12332
12333     // Now recurse on both the base and sub vectors.
12334     SDValue SimplifiedSubV =
12335         SubVectorUsed
12336             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12337             : DAG.getUNDEF(SubV.getValueType());
12338     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12339     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12340       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12341                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12342     return V;
12343   }
12344   }
12345 }
12346
12347 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12348                                        SDValue N1, SelectionDAG &DAG) {
12349   EVT VT = SVN->getValueType(0);
12350   int NumElts = VT.getVectorNumElements();
12351   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12352   for (int M : SVN->getMask())
12353     if (M >= 0 && M < NumElts)
12354       N0UsedElements[M] = true;
12355     else if (M >= NumElts)
12356       N1UsedElements[M - NumElts] = true;
12357
12358   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12359   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12360   if (S0 == N0 && S1 == N1)
12361     return SDValue();
12362
12363   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12364 }
12365
12366 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12367 // or turn a shuffle of a single concat into simpler shuffle then concat.
12368 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12369   EVT VT = N->getValueType(0);
12370   unsigned NumElts = VT.getVectorNumElements();
12371
12372   SDValue N0 = N->getOperand(0);
12373   SDValue N1 = N->getOperand(1);
12374   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12375
12376   SmallVector<SDValue, 4> Ops;
12377   EVT ConcatVT = N0.getOperand(0).getValueType();
12378   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12379   unsigned NumConcats = NumElts / NumElemsPerConcat;
12380
12381   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12382   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12383   // half vector elements.
12384   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12385       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12386                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12387     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12388                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12389     N1 = DAG.getUNDEF(ConcatVT);
12390     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12391   }
12392
12393   // Look at every vector that's inserted. We're looking for exact
12394   // subvector-sized copies from a concatenated vector
12395   for (unsigned I = 0; I != NumConcats; ++I) {
12396     // Make sure we're dealing with a copy.
12397     unsigned Begin = I * NumElemsPerConcat;
12398     bool AllUndef = true, NoUndef = true;
12399     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12400       if (SVN->getMaskElt(J) >= 0)
12401         AllUndef = false;
12402       else
12403         NoUndef = false;
12404     }
12405
12406     if (NoUndef) {
12407       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12408         return SDValue();
12409
12410       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12411         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12412           return SDValue();
12413
12414       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12415       if (FirstElt < N0.getNumOperands())
12416         Ops.push_back(N0.getOperand(FirstElt));
12417       else
12418         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12419
12420     } else if (AllUndef) {
12421       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12422     } else { // Mixed with general masks and undefs, can't do optimization.
12423       return SDValue();
12424     }
12425   }
12426
12427   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12428 }
12429
12430 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12431   EVT VT = N->getValueType(0);
12432   unsigned NumElts = VT.getVectorNumElements();
12433
12434   SDValue N0 = N->getOperand(0);
12435   SDValue N1 = N->getOperand(1);
12436
12437   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12438
12439   // Canonicalize shuffle undef, undef -> undef
12440   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12441     return DAG.getUNDEF(VT);
12442
12443   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12444
12445   // Canonicalize shuffle v, v -> v, undef
12446   if (N0 == N1) {
12447     SmallVector<int, 8> NewMask;
12448     for (unsigned i = 0; i != NumElts; ++i) {
12449       int Idx = SVN->getMaskElt(i);
12450       if (Idx >= (int)NumElts) Idx -= NumElts;
12451       NewMask.push_back(Idx);
12452     }
12453     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12454                                 &NewMask[0]);
12455   }
12456
12457   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12458   if (N0.getOpcode() == ISD::UNDEF) {
12459     SmallVector<int, 8> NewMask;
12460     for (unsigned i = 0; i != NumElts; ++i) {
12461       int Idx = SVN->getMaskElt(i);
12462       if (Idx >= 0) {
12463         if (Idx >= (int)NumElts)
12464           Idx -= NumElts;
12465         else
12466           Idx = -1; // remove reference to lhs
12467       }
12468       NewMask.push_back(Idx);
12469     }
12470     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12471                                 &NewMask[0]);
12472   }
12473
12474   // Remove references to rhs if it is undef
12475   if (N1.getOpcode() == ISD::UNDEF) {
12476     bool Changed = false;
12477     SmallVector<int, 8> NewMask;
12478     for (unsigned i = 0; i != NumElts; ++i) {
12479       int Idx = SVN->getMaskElt(i);
12480       if (Idx >= (int)NumElts) {
12481         Idx = -1;
12482         Changed = true;
12483       }
12484       NewMask.push_back(Idx);
12485     }
12486     if (Changed)
12487       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12488   }
12489
12490   // If it is a splat, check if the argument vector is another splat or a
12491   // build_vector.
12492   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12493     SDNode *V = N0.getNode();
12494
12495     // If this is a bit convert that changes the element type of the vector but
12496     // not the number of vector elements, look through it.  Be careful not to
12497     // look though conversions that change things like v4f32 to v2f64.
12498     if (V->getOpcode() == ISD::BITCAST) {
12499       SDValue ConvInput = V->getOperand(0);
12500       if (ConvInput.getValueType().isVector() &&
12501           ConvInput.getValueType().getVectorNumElements() == NumElts)
12502         V = ConvInput.getNode();
12503     }
12504
12505     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12506       assert(V->getNumOperands() == NumElts &&
12507              "BUILD_VECTOR has wrong number of operands");
12508       SDValue Base;
12509       bool AllSame = true;
12510       for (unsigned i = 0; i != NumElts; ++i) {
12511         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12512           Base = V->getOperand(i);
12513           break;
12514         }
12515       }
12516       // Splat of <u, u, u, u>, return <u, u, u, u>
12517       if (!Base.getNode())
12518         return N0;
12519       for (unsigned i = 0; i != NumElts; ++i) {
12520         if (V->getOperand(i) != Base) {
12521           AllSame = false;
12522           break;
12523         }
12524       }
12525       // Splat of <x, x, x, x>, return <x, x, x, x>
12526       if (AllSame)
12527         return N0;
12528
12529       // Canonicalize any other splat as a build_vector.
12530       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12531       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12532       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12533                                   V->getValueType(0), Ops);
12534
12535       // We may have jumped through bitcasts, so the type of the
12536       // BUILD_VECTOR may not match the type of the shuffle.
12537       if (V->getValueType(0) != VT)
12538         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12539       return NewBV;
12540     }
12541   }
12542
12543   // There are various patterns used to build up a vector from smaller vectors,
12544   // subvectors, or elements. Scan chains of these and replace unused insertions
12545   // or components with undef.
12546   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12547     return S;
12548
12549   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12550       Level < AfterLegalizeVectorOps &&
12551       (N1.getOpcode() == ISD::UNDEF ||
12552       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12553        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12554     SDValue V = partitionShuffleOfConcats(N, DAG);
12555
12556     if (V.getNode())
12557       return V;
12558   }
12559
12560   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12561   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12562   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12563     SmallVector<SDValue, 8> Ops;
12564     for (int M : SVN->getMask()) {
12565       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12566       if (M >= 0) {
12567         int Idx = M % NumElts;
12568         SDValue &S = (M < (int)NumElts ? N0 : N1);
12569         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12570           Op = S.getOperand(Idx);
12571         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12572           if (Idx == 0)
12573             Op = S.getOperand(0);
12574         } else {
12575           // Operand can't be combined - bail out.
12576           break;
12577         }
12578       }
12579       Ops.push_back(Op);
12580     }
12581     if (Ops.size() == VT.getVectorNumElements()) {
12582       // BUILD_VECTOR requires all inputs to be of the same type, find the
12583       // maximum type and extend them all.
12584       EVT SVT = VT.getScalarType();
12585       if (SVT.isInteger())
12586         for (SDValue &Op : Ops)
12587           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12588       if (SVT != VT.getScalarType())
12589         for (SDValue &Op : Ops)
12590           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12591                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12592                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12593       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12594     }
12595   }
12596
12597   // If this shuffle only has a single input that is a bitcasted shuffle,
12598   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12599   // back to their original types.
12600   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12601       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12602       TLI.isTypeLegal(VT)) {
12603
12604     // Peek through the bitcast only if there is one user.
12605     SDValue BC0 = N0;
12606     while (BC0.getOpcode() == ISD::BITCAST) {
12607       if (!BC0.hasOneUse())
12608         break;
12609       BC0 = BC0.getOperand(0);
12610     }
12611
12612     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12613       if (Scale == 1)
12614         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12615
12616       SmallVector<int, 8> NewMask;
12617       for (int M : Mask)
12618         for (int s = 0; s != Scale; ++s)
12619           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12620       return NewMask;
12621     };
12622
12623     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12624       EVT SVT = VT.getScalarType();
12625       EVT InnerVT = BC0->getValueType(0);
12626       EVT InnerSVT = InnerVT.getScalarType();
12627
12628       // Determine which shuffle works with the smaller scalar type.
12629       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12630       EVT ScaleSVT = ScaleVT.getScalarType();
12631
12632       if (TLI.isTypeLegal(ScaleVT) &&
12633           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12634           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12635
12636         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12637         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12638
12639         // Scale the shuffle masks to the smaller scalar type.
12640         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12641         SmallVector<int, 8> InnerMask =
12642             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12643         SmallVector<int, 8> OuterMask =
12644             ScaleShuffleMask(SVN->getMask(), OuterScale);
12645
12646         // Merge the shuffle masks.
12647         SmallVector<int, 8> NewMask;
12648         for (int M : OuterMask)
12649           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12650
12651         // Test for shuffle mask legality over both commutations.
12652         SDValue SV0 = BC0->getOperand(0);
12653         SDValue SV1 = BC0->getOperand(1);
12654         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12655         if (!LegalMask) {
12656           std::swap(SV0, SV1);
12657           ShuffleVectorSDNode::commuteMask(NewMask);
12658           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12659         }
12660
12661         if (LegalMask) {
12662           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12663           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12664           return DAG.getNode(
12665               ISD::BITCAST, SDLoc(N), VT,
12666               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12667         }
12668       }
12669     }
12670   }
12671
12672   // Canonicalize shuffles according to rules:
12673   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12674   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12675   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12676   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12677       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12678       TLI.isTypeLegal(VT)) {
12679     // The incoming shuffle must be of the same type as the result of the
12680     // current shuffle.
12681     assert(N1->getOperand(0).getValueType() == VT &&
12682            "Shuffle types don't match");
12683
12684     SDValue SV0 = N1->getOperand(0);
12685     SDValue SV1 = N1->getOperand(1);
12686     bool HasSameOp0 = N0 == SV0;
12687     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12688     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12689       // Commute the operands of this shuffle so that next rule
12690       // will trigger.
12691       return DAG.getCommutedVectorShuffle(*SVN);
12692   }
12693
12694   // Try to fold according to rules:
12695   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12696   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12697   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12698   // Don't try to fold shuffles with illegal type.
12699   // Only fold if this shuffle is the only user of the other shuffle.
12700   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12701       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12702     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12703
12704     // The incoming shuffle must be of the same type as the result of the
12705     // current shuffle.
12706     assert(OtherSV->getOperand(0).getValueType() == VT &&
12707            "Shuffle types don't match");
12708
12709     SDValue SV0, SV1;
12710     SmallVector<int, 4> Mask;
12711     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12712     // operand, and SV1 as the second operand.
12713     for (unsigned i = 0; i != NumElts; ++i) {
12714       int Idx = SVN->getMaskElt(i);
12715       if (Idx < 0) {
12716         // Propagate Undef.
12717         Mask.push_back(Idx);
12718         continue;
12719       }
12720
12721       SDValue CurrentVec;
12722       if (Idx < (int)NumElts) {
12723         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12724         // shuffle mask to identify which vector is actually referenced.
12725         Idx = OtherSV->getMaskElt(Idx);
12726         if (Idx < 0) {
12727           // Propagate Undef.
12728           Mask.push_back(Idx);
12729           continue;
12730         }
12731
12732         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12733                                            : OtherSV->getOperand(1);
12734       } else {
12735         // This shuffle index references an element within N1.
12736         CurrentVec = N1;
12737       }
12738
12739       // Simple case where 'CurrentVec' is UNDEF.
12740       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12741         Mask.push_back(-1);
12742         continue;
12743       }
12744
12745       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12746       // will be the first or second operand of the combined shuffle.
12747       Idx = Idx % NumElts;
12748       if (!SV0.getNode() || SV0 == CurrentVec) {
12749         // Ok. CurrentVec is the left hand side.
12750         // Update the mask accordingly.
12751         SV0 = CurrentVec;
12752         Mask.push_back(Idx);
12753         continue;
12754       }
12755
12756       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12757       if (SV1.getNode() && SV1 != CurrentVec)
12758         return SDValue();
12759
12760       // Ok. CurrentVec is the right hand side.
12761       // Update the mask accordingly.
12762       SV1 = CurrentVec;
12763       Mask.push_back(Idx + NumElts);
12764     }
12765
12766     // Check if all indices in Mask are Undef. In case, propagate Undef.
12767     bool isUndefMask = true;
12768     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12769       isUndefMask &= Mask[i] < 0;
12770
12771     if (isUndefMask)
12772       return DAG.getUNDEF(VT);
12773
12774     if (!SV0.getNode())
12775       SV0 = DAG.getUNDEF(VT);
12776     if (!SV1.getNode())
12777       SV1 = DAG.getUNDEF(VT);
12778
12779     // Avoid introducing shuffles with illegal mask.
12780     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12781       ShuffleVectorSDNode::commuteMask(Mask);
12782
12783       if (!TLI.isShuffleMaskLegal(Mask, VT))
12784         return SDValue();
12785
12786       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12787       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12788       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12789       std::swap(SV0, SV1);
12790     }
12791
12792     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12793     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12794     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12795     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12796   }
12797
12798   return SDValue();
12799 }
12800
12801 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12802   SDValue InVal = N->getOperand(0);
12803   EVT VT = N->getValueType(0);
12804
12805   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12806   // with a VECTOR_SHUFFLE.
12807   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12808     SDValue InVec = InVal->getOperand(0);
12809     SDValue EltNo = InVal->getOperand(1);
12810
12811     // FIXME: We could support implicit truncation if the shuffle can be
12812     // scaled to a smaller vector scalar type.
12813     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12814     if (C0 && VT == InVec.getValueType() &&
12815         VT.getScalarType() == InVal.getValueType()) {
12816       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12817       int Elt = C0->getZExtValue();
12818       NewMask[0] = Elt;
12819
12820       if (TLI.isShuffleMaskLegal(NewMask, VT))
12821         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12822                                     NewMask);
12823     }
12824   }
12825
12826   return SDValue();
12827 }
12828
12829 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12830   SDValue N0 = N->getOperand(0);
12831   SDValue N2 = N->getOperand(2);
12832
12833   // If the input vector is a concatenation, and the insert replaces
12834   // one of the halves, we can optimize into a single concat_vectors.
12835   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12836       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12837     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12838     EVT VT = N->getValueType(0);
12839
12840     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12841     // (concat_vectors Z, Y)
12842     if (InsIdx == 0)
12843       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12844                          N->getOperand(1), N0.getOperand(1));
12845
12846     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12847     // (concat_vectors X, Z)
12848     if (InsIdx == VT.getVectorNumElements()/2)
12849       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12850                          N0.getOperand(0), N->getOperand(1));
12851   }
12852
12853   return SDValue();
12854 }
12855
12856 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12857   SDValue N0 = N->getOperand(0);
12858
12859   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12860   if (N0->getOpcode() == ISD::FP16_TO_FP)
12861     return N0->getOperand(0);
12862
12863   return SDValue();
12864 }
12865
12866 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12867 /// with the destination vector and a zero vector.
12868 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12869 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12870 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12871   EVT VT = N->getValueType(0);
12872   SDValue LHS = N->getOperand(0);
12873   SDValue RHS = N->getOperand(1);
12874   SDLoc dl(N);
12875
12876   // Make sure we're not running after operation legalization where it 
12877   // may have custom lowered the vector shuffles.
12878   if (LegalOperations)
12879     return SDValue();
12880
12881   if (N->getOpcode() != ISD::AND)
12882     return SDValue();
12883
12884   if (RHS.getOpcode() == ISD::BITCAST)
12885     RHS = RHS.getOperand(0);
12886
12887   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12888     SmallVector<int, 8> Indices;
12889     unsigned NumElts = RHS.getNumOperands();
12890
12891     for (unsigned i = 0; i != NumElts; ++i) {
12892       SDValue Elt = RHS.getOperand(i);
12893       if (isAllOnesConstant(Elt))
12894         Indices.push_back(i);
12895       else if (isNullConstant(Elt))
12896         Indices.push_back(NumElts+i);
12897       else
12898         return SDValue();
12899     }
12900
12901     // Let's see if the target supports this vector_shuffle.
12902     EVT RVT = RHS.getValueType();
12903     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12904       return SDValue();
12905
12906     // Return the new VECTOR_SHUFFLE node.
12907     EVT EltVT = RVT.getVectorElementType();
12908     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12909                                    DAG.getConstant(0, dl, EltVT));
12910     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12911     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12912     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12913     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12914   }
12915
12916   return SDValue();
12917 }
12918
12919 /// Visit a binary vector operation, like ADD.
12920 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12921   assert(N->getValueType(0).isVector() &&
12922          "SimplifyVBinOp only works on vectors!");
12923
12924   SDValue LHS = N->getOperand(0);
12925   SDValue RHS = N->getOperand(1);
12926
12927   if (SDValue Shuffle = XformToShuffleWithZero(N))
12928     return Shuffle;
12929
12930   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12931   // this operation.
12932   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12933       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12934     // Check if both vectors are constants. If not bail out.
12935     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12936           cast<BuildVectorSDNode>(RHS)->isConstant()))
12937       return SDValue();
12938
12939     SmallVector<SDValue, 8> Ops;
12940     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12941       SDValue LHSOp = LHS.getOperand(i);
12942       SDValue RHSOp = RHS.getOperand(i);
12943
12944       // Can't fold divide by zero.
12945       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12946           N->getOpcode() == ISD::FDIV) {
12947         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12948              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12949           break;
12950       }
12951
12952       EVT VT = LHSOp.getValueType();
12953       EVT RVT = RHSOp.getValueType();
12954       if (RVT != VT) {
12955         // Integer BUILD_VECTOR operands may have types larger than the element
12956         // size (e.g., when the element type is not legal).  Prior to type
12957         // legalization, the types may not match between the two BUILD_VECTORS.
12958         // Truncate one of the operands to make them match.
12959         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12960           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12961         } else {
12962           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12963           VT = RVT;
12964         }
12965       }
12966       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12967                                    LHSOp, RHSOp);
12968       if (FoldOp.getOpcode() != ISD::UNDEF &&
12969           FoldOp.getOpcode() != ISD::Constant &&
12970           FoldOp.getOpcode() != ISD::ConstantFP)
12971         break;
12972       Ops.push_back(FoldOp);
12973       AddToWorklist(FoldOp.getNode());
12974     }
12975
12976     if (Ops.size() == LHS.getNumOperands())
12977       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12978   }
12979
12980   // Type legalization might introduce new shuffles in the DAG.
12981   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12982   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12983   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12984       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12985       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12986       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12987     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12988     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12989
12990     if (SVN0->getMask().equals(SVN1->getMask())) {
12991       EVT VT = N->getValueType(0);
12992       SDValue UndefVector = LHS.getOperand(1);
12993       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12994                                      LHS.getOperand(0), RHS.getOperand(0));
12995       AddUsersToWorklist(N);
12996       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12997                                   &SVN0->getMask()[0]);
12998     }
12999   }
13000
13001   return SDValue();
13002 }
13003
13004 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13005                                     SDValue N1, SDValue N2){
13006   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13007
13008   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13009                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13010
13011   // If we got a simplified select_cc node back from SimplifySelectCC, then
13012   // break it down into a new SETCC node, and a new SELECT node, and then return
13013   // the SELECT node, since we were called with a SELECT node.
13014   if (SCC.getNode()) {
13015     // Check to see if we got a select_cc back (to turn into setcc/select).
13016     // Otherwise, just return whatever node we got back, like fabs.
13017     if (SCC.getOpcode() == ISD::SELECT_CC) {
13018       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13019                                   N0.getValueType(),
13020                                   SCC.getOperand(0), SCC.getOperand(1),
13021                                   SCC.getOperand(4));
13022       AddToWorklist(SETCC.getNode());
13023       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13024                            SCC.getOperand(2), SCC.getOperand(3));
13025     }
13026
13027     return SCC;
13028   }
13029   return SDValue();
13030 }
13031
13032 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13033 /// being selected between, see if we can simplify the select.  Callers of this
13034 /// should assume that TheSelect is deleted if this returns true.  As such, they
13035 /// should return the appropriate thing (e.g. the node) back to the top-level of
13036 /// the DAG combiner loop to avoid it being looked at.
13037 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13038                                     SDValue RHS) {
13039
13040   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13041   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13042   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13043     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13044       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13045       SDValue Sqrt = RHS;
13046       ISD::CondCode CC;
13047       SDValue CmpLHS;
13048       const ConstantFPSDNode *NegZero = nullptr;
13049
13050       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13051         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13052         CmpLHS = TheSelect->getOperand(0);
13053         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13054       } else {
13055         // SELECT or VSELECT
13056         SDValue Cmp = TheSelect->getOperand(0);
13057         if (Cmp.getOpcode() == ISD::SETCC) {
13058           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13059           CmpLHS = Cmp.getOperand(0);
13060           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13061         }
13062       }
13063       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13064           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13065           CC == ISD::SETULT || CC == ISD::SETLT)) {
13066         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13067         CombineTo(TheSelect, Sqrt);
13068         return true;
13069       }
13070     }
13071   }
13072   // Cannot simplify select with vector condition
13073   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13074
13075   // If this is a select from two identical things, try to pull the operation
13076   // through the select.
13077   if (LHS.getOpcode() != RHS.getOpcode() ||
13078       !LHS.hasOneUse() || !RHS.hasOneUse())
13079     return false;
13080
13081   // If this is a load and the token chain is identical, replace the select
13082   // of two loads with a load through a select of the address to load from.
13083   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13084   // constants have been dropped into the constant pool.
13085   if (LHS.getOpcode() == ISD::LOAD) {
13086     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13087     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13088
13089     // Token chains must be identical.
13090     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13091         // Do not let this transformation reduce the number of volatile loads.
13092         LLD->isVolatile() || RLD->isVolatile() ||
13093         // FIXME: If either is a pre/post inc/dec load,
13094         // we'd need to split out the address adjustment.
13095         LLD->isIndexed() || RLD->isIndexed() ||
13096         // If this is an EXTLOAD, the VT's must match.
13097         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13098         // If this is an EXTLOAD, the kind of extension must match.
13099         (LLD->getExtensionType() != RLD->getExtensionType() &&
13100          // The only exception is if one of the extensions is anyext.
13101          LLD->getExtensionType() != ISD::EXTLOAD &&
13102          RLD->getExtensionType() != ISD::EXTLOAD) ||
13103         // FIXME: this discards src value information.  This is
13104         // over-conservative. It would be beneficial to be able to remember
13105         // both potential memory locations.  Since we are discarding
13106         // src value info, don't do the transformation if the memory
13107         // locations are not in the default address space.
13108         LLD->getPointerInfo().getAddrSpace() != 0 ||
13109         RLD->getPointerInfo().getAddrSpace() != 0 ||
13110         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13111                                       LLD->getBasePtr().getValueType()))
13112       return false;
13113
13114     // Check that the select condition doesn't reach either load.  If so,
13115     // folding this will induce a cycle into the DAG.  If not, this is safe to
13116     // xform, so create a select of the addresses.
13117     SDValue Addr;
13118     if (TheSelect->getOpcode() == ISD::SELECT) {
13119       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13120       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13121           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13122         return false;
13123       // The loads must not depend on one another.
13124       if (LLD->isPredecessorOf(RLD) ||
13125           RLD->isPredecessorOf(LLD))
13126         return false;
13127       Addr = DAG.getSelect(SDLoc(TheSelect),
13128                            LLD->getBasePtr().getValueType(),
13129                            TheSelect->getOperand(0), LLD->getBasePtr(),
13130                            RLD->getBasePtr());
13131     } else {  // Otherwise SELECT_CC
13132       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13133       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13134
13135       if ((LLD->hasAnyUseOfValue(1) &&
13136            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13137           (RLD->hasAnyUseOfValue(1) &&
13138            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13139         return false;
13140
13141       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13142                          LLD->getBasePtr().getValueType(),
13143                          TheSelect->getOperand(0),
13144                          TheSelect->getOperand(1),
13145                          LLD->getBasePtr(), RLD->getBasePtr(),
13146                          TheSelect->getOperand(4));
13147     }
13148
13149     SDValue Load;
13150     // It is safe to replace the two loads if they have different alignments,
13151     // but the new load must be the minimum (most restrictive) alignment of the
13152     // inputs.
13153     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13154     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13155     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13156       Load = DAG.getLoad(TheSelect->getValueType(0),
13157                          SDLoc(TheSelect),
13158                          // FIXME: Discards pointer and AA info.
13159                          LLD->getChain(), Addr, MachinePointerInfo(),
13160                          LLD->isVolatile(), LLD->isNonTemporal(),
13161                          isInvariant, Alignment);
13162     } else {
13163       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13164                             RLD->getExtensionType() : LLD->getExtensionType(),
13165                             SDLoc(TheSelect),
13166                             TheSelect->getValueType(0),
13167                             // FIXME: Discards pointer and AA info.
13168                             LLD->getChain(), Addr, MachinePointerInfo(),
13169                             LLD->getMemoryVT(), LLD->isVolatile(),
13170                             LLD->isNonTemporal(), isInvariant, Alignment);
13171     }
13172
13173     // Users of the select now use the result of the load.
13174     CombineTo(TheSelect, Load);
13175
13176     // Users of the old loads now use the new load's chain.  We know the
13177     // old-load value is dead now.
13178     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13179     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13180     return true;
13181   }
13182
13183   return false;
13184 }
13185
13186 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13187 /// where 'cond' is the comparison specified by CC.
13188 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13189                                       SDValue N2, SDValue N3,
13190                                       ISD::CondCode CC, bool NotExtCompare) {
13191   // (x ? y : y) -> y.
13192   if (N2 == N3) return N2;
13193
13194   EVT VT = N2.getValueType();
13195   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13196   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13197
13198   // Determine if the condition we're dealing with is constant
13199   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13200                               N0, N1, CC, DL, false);
13201   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13202
13203   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13204     // fold select_cc true, x, y -> x
13205     // fold select_cc false, x, y -> y
13206     return !SCCC->isNullValue() ? N2 : N3;
13207   }
13208
13209   // Check to see if we can simplify the select into an fabs node
13210   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13211     // Allow either -0.0 or 0.0
13212     if (CFP->getValueAPF().isZero()) {
13213       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13214       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13215           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13216           N2 == N3.getOperand(0))
13217         return DAG.getNode(ISD::FABS, DL, VT, N0);
13218
13219       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13220       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13221           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13222           N2.getOperand(0) == N3)
13223         return DAG.getNode(ISD::FABS, DL, VT, N3);
13224     }
13225   }
13226
13227   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13228   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13229   // in it.  This is a win when the constant is not otherwise available because
13230   // it replaces two constant pool loads with one.  We only do this if the FP
13231   // type is known to be legal, because if it isn't, then we are before legalize
13232   // types an we want the other legalization to happen first (e.g. to avoid
13233   // messing with soft float) and if the ConstantFP is not legal, because if
13234   // it is legal, we may not need to store the FP constant in a constant pool.
13235   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13236     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13237       if (TLI.isTypeLegal(N2.getValueType()) &&
13238           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13239                TargetLowering::Legal &&
13240            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13241            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13242           // If both constants have multiple uses, then we won't need to do an
13243           // extra load, they are likely around in registers for other users.
13244           (TV->hasOneUse() || FV->hasOneUse())) {
13245         Constant *Elts[] = {
13246           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13247           const_cast<ConstantFP*>(TV->getConstantFPValue())
13248         };
13249         Type *FPTy = Elts[0]->getType();
13250         const DataLayout &TD = *TLI.getDataLayout();
13251
13252         // Create a ConstantArray of the two constants.
13253         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13254         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13255                                             TD.getPrefTypeAlignment(FPTy));
13256         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13257
13258         // Get the offsets to the 0 and 1 element of the array so that we can
13259         // select between them.
13260         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13261         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13262         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13263
13264         SDValue Cond = DAG.getSetCC(DL,
13265                                     getSetCCResultType(N0.getValueType()),
13266                                     N0, N1, CC);
13267         AddToWorklist(Cond.getNode());
13268         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13269                                           Cond, One, Zero);
13270         AddToWorklist(CstOffset.getNode());
13271         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13272                             CstOffset);
13273         AddToWorklist(CPIdx.getNode());
13274         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13275                            MachinePointerInfo::getConstantPool(), false,
13276                            false, false, Alignment);
13277       }
13278     }
13279
13280   // Check to see if we can perform the "gzip trick", transforming
13281   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13282   if (isNullConstant(N3) && CC == ISD::SETLT &&
13283       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13284        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13285     EVT XType = N0.getValueType();
13286     EVT AType = N2.getValueType();
13287     if (XType.bitsGE(AType)) {
13288       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13289       // single-bit constant.
13290       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13291         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13292         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13293         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13294                                        getShiftAmountTy(N0.getValueType()));
13295         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13296                                     XType, N0, ShCt);
13297         AddToWorklist(Shift.getNode());
13298
13299         if (XType.bitsGT(AType)) {
13300           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13301           AddToWorklist(Shift.getNode());
13302         }
13303
13304         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13305       }
13306
13307       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13308                                   XType, N0,
13309                                   DAG.getConstant(XType.getSizeInBits() - 1,
13310                                                   SDLoc(N0),
13311                                          getShiftAmountTy(N0.getValueType())));
13312       AddToWorklist(Shift.getNode());
13313
13314       if (XType.bitsGT(AType)) {
13315         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13316         AddToWorklist(Shift.getNode());
13317       }
13318
13319       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13320     }
13321   }
13322
13323   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13324   // where y is has a single bit set.
13325   // A plaintext description would be, we can turn the SELECT_CC into an AND
13326   // when the condition can be materialized as an all-ones register.  Any
13327   // single bit-test can be materialized as an all-ones register with
13328   // shift-left and shift-right-arith.
13329   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13330       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13331     SDValue AndLHS = N0->getOperand(0);
13332     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13333     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13334       // Shift the tested bit over the sign bit.
13335       APInt AndMask = ConstAndRHS->getAPIntValue();
13336       SDValue ShlAmt =
13337         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13338                         getShiftAmountTy(AndLHS.getValueType()));
13339       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13340
13341       // Now arithmetic right shift it all the way over, so the result is either
13342       // all-ones, or zero.
13343       SDValue ShrAmt =
13344         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13345                         getShiftAmountTy(Shl.getValueType()));
13346       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13347
13348       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13349     }
13350   }
13351
13352   // fold select C, 16, 0 -> shl C, 4
13353   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13354       TLI.getBooleanContents(N0.getValueType()) ==
13355           TargetLowering::ZeroOrOneBooleanContent) {
13356
13357     // If the caller doesn't want us to simplify this into a zext of a compare,
13358     // don't do it.
13359     if (NotExtCompare && N2C->isOne())
13360       return SDValue();
13361
13362     // Get a SetCC of the condition
13363     // NOTE: Don't create a SETCC if it's not legal on this target.
13364     if (!LegalOperations ||
13365         TLI.isOperationLegal(ISD::SETCC,
13366           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13367       SDValue Temp, SCC;
13368       // cast from setcc result type to select result type
13369       if (LegalTypes) {
13370         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13371                             N0, N1, CC);
13372         if (N2.getValueType().bitsLT(SCC.getValueType()))
13373           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13374                                         N2.getValueType());
13375         else
13376           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13377                              N2.getValueType(), SCC);
13378       } else {
13379         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13380         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13381                            N2.getValueType(), SCC);
13382       }
13383
13384       AddToWorklist(SCC.getNode());
13385       AddToWorklist(Temp.getNode());
13386
13387       if (N2C->isOne())
13388         return Temp;
13389
13390       // shl setcc result by log2 n2c
13391       return DAG.getNode(
13392           ISD::SHL, DL, N2.getValueType(), Temp,
13393           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13394                           getShiftAmountTy(Temp.getValueType())));
13395     }
13396   }
13397
13398   // Check to see if this is the equivalent of setcc
13399   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13400   // otherwise, go ahead with the folds.
13401   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13402     EVT XType = N0.getValueType();
13403     if (!LegalOperations ||
13404         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13405       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13406       if (Res.getValueType() != VT)
13407         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13408       return Res;
13409     }
13410
13411     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13412     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13413         (!LegalOperations ||
13414          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13415       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13416       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13417                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13418                                          SDLoc(Ctlz),
13419                                        getShiftAmountTy(Ctlz.getValueType())));
13420     }
13421     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13422     if (isNullConstant(N1) && CC == ISD::SETGT) {
13423       SDLoc DL(N0);
13424       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13425                                   XType, DAG.getConstant(0, DL, XType), N0);
13426       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13427       return DAG.getNode(ISD::SRL, DL, XType,
13428                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13429                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13430                                          getShiftAmountTy(XType)));
13431     }
13432     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13433     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13434       SDLoc DL(N0);
13435       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13436                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13437                                          getShiftAmountTy(N0.getValueType())));
13438       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13439                                                                     XType));
13440     }
13441   }
13442
13443   // Check to see if this is an integer abs.
13444   // select_cc setg[te] X,  0,  X, -X ->
13445   // select_cc setgt    X, -1,  X, -X ->
13446   // select_cc setl[te] X,  0, -X,  X ->
13447   // select_cc setlt    X,  1, -X,  X ->
13448   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13449   if (N1C) {
13450     ConstantSDNode *SubC = nullptr;
13451     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13452          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13453         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13454       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13455     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13456               (N1C->isOne() && CC == ISD::SETLT)) &&
13457              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13458       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13459
13460     EVT XType = N0.getValueType();
13461     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13462       SDLoc DL(N0);
13463       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13464                                   N0,
13465                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13466                                          getShiftAmountTy(N0.getValueType())));
13467       SDValue Add = DAG.getNode(ISD::ADD, DL,
13468                                 XType, N0, Shift);
13469       AddToWorklist(Shift.getNode());
13470       AddToWorklist(Add.getNode());
13471       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13472     }
13473   }
13474
13475   return SDValue();
13476 }
13477
13478 /// This is a stub for TargetLowering::SimplifySetCC.
13479 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13480                                    SDValue N1, ISD::CondCode Cond,
13481                                    SDLoc DL, bool foldBooleans) {
13482   TargetLowering::DAGCombinerInfo
13483     DagCombineInfo(DAG, Level, false, this);
13484   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13485 }
13486
13487 /// Given an ISD::SDIV node expressing a divide by constant, return
13488 /// a DAG expression to select that will generate the same value by multiplying
13489 /// by a magic number.
13490 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13491 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13492   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13493   if (!C)
13494     return SDValue();
13495
13496   // Avoid division by zero.
13497   if (C->isNullValue())
13498     return SDValue();
13499
13500   std::vector<SDNode*> Built;
13501   SDValue S =
13502       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13503
13504   for (SDNode *N : Built)
13505     AddToWorklist(N);
13506   return S;
13507 }
13508
13509 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13510 /// DAG expression that will generate the same value by right shifting.
13511 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13512   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13513   if (!C)
13514     return SDValue();
13515
13516   // Avoid division by zero.
13517   if (C->isNullValue())
13518     return SDValue();
13519
13520   std::vector<SDNode *> Built;
13521   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13522
13523   for (SDNode *N : Built)
13524     AddToWorklist(N);
13525   return S;
13526 }
13527
13528 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13529 /// expression that will generate the same value by multiplying by a magic
13530 /// number.
13531 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13532 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13533   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13534   if (!C)
13535     return SDValue();
13536
13537   // Avoid division by zero.
13538   if (C->isNullValue())
13539     return SDValue();
13540
13541   std::vector<SDNode*> Built;
13542   SDValue S =
13543       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13544
13545   for (SDNode *N : Built)
13546     AddToWorklist(N);
13547   return S;
13548 }
13549
13550 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13551   if (Level >= AfterLegalizeDAG)
13552     return SDValue();
13553
13554   // Expose the DAG combiner to the target combiner implementations.
13555   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13556
13557   unsigned Iterations = 0;
13558   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13559     if (Iterations) {
13560       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13561       // For the reciprocal, we need to find the zero of the function:
13562       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13563       //     =>
13564       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13565       //     does not require additional intermediate precision]
13566       EVT VT = Op.getValueType();
13567       SDLoc DL(Op);
13568       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13569
13570       AddToWorklist(Est.getNode());
13571
13572       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13573       for (unsigned i = 0; i < Iterations; ++i) {
13574         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13575         AddToWorklist(NewEst.getNode());
13576
13577         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13578         AddToWorklist(NewEst.getNode());
13579
13580         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13581         AddToWorklist(NewEst.getNode());
13582
13583         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13584         AddToWorklist(Est.getNode());
13585       }
13586     }
13587     return Est;
13588   }
13589
13590   return SDValue();
13591 }
13592
13593 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13594 /// For the reciprocal sqrt, we need to find the zero of the function:
13595 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13596 ///     =>
13597 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13598 /// As a result, we precompute A/2 prior to the iteration loop.
13599 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13600                                           unsigned Iterations) {
13601   EVT VT = Arg.getValueType();
13602   SDLoc DL(Arg);
13603   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13604
13605   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13606   // this entire sequence requires only one FP constant.
13607   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13608   AddToWorklist(HalfArg.getNode());
13609
13610   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13611   AddToWorklist(HalfArg.getNode());
13612
13613   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13614   for (unsigned i = 0; i < Iterations; ++i) {
13615     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13616     AddToWorklist(NewEst.getNode());
13617
13618     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13619     AddToWorklist(NewEst.getNode());
13620
13621     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13622     AddToWorklist(NewEst.getNode());
13623
13624     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13625     AddToWorklist(Est.getNode());
13626   }
13627   return Est;
13628 }
13629
13630 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13631 /// For the reciprocal sqrt, we need to find the zero of the function:
13632 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13633 ///     =>
13634 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13635 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13636                                           unsigned Iterations) {
13637   EVT VT = Arg.getValueType();
13638   SDLoc DL(Arg);
13639   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13640   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13641
13642   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13643   for (unsigned i = 0; i < Iterations; ++i) {
13644     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13645     AddToWorklist(HalfEst.getNode());
13646
13647     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13648     AddToWorklist(Est.getNode());
13649
13650     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13651     AddToWorklist(Est.getNode());
13652
13653     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13654     AddToWorklist(Est.getNode());
13655
13656     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13657     AddToWorklist(Est.getNode());
13658   }
13659   return Est;
13660 }
13661
13662 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13663   if (Level >= AfterLegalizeDAG)
13664     return SDValue();
13665
13666   // Expose the DAG combiner to the target combiner implementations.
13667   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13668   unsigned Iterations = 0;
13669   bool UseOneConstNR = false;
13670   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13671     AddToWorklist(Est.getNode());
13672     if (Iterations) {
13673       Est = UseOneConstNR ?
13674         BuildRsqrtNROneConst(Op, Est, Iterations) :
13675         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13676     }
13677     return Est;
13678   }
13679
13680   return SDValue();
13681 }
13682
13683 /// Return true if base is a frame index, which is known not to alias with
13684 /// anything but itself.  Provides base object and offset as results.
13685 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13686                            const GlobalValue *&GV, const void *&CV) {
13687   // Assume it is a primitive operation.
13688   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13689
13690   // If it's an adding a simple constant then integrate the offset.
13691   if (Base.getOpcode() == ISD::ADD) {
13692     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13693       Base = Base.getOperand(0);
13694       Offset += C->getZExtValue();
13695     }
13696   }
13697
13698   // Return the underlying GlobalValue, and update the Offset.  Return false
13699   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13700   // by multiple nodes with different offsets.
13701   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13702     GV = G->getGlobal();
13703     Offset += G->getOffset();
13704     return false;
13705   }
13706
13707   // Return the underlying Constant value, and update the Offset.  Return false
13708   // for ConstantSDNodes since the same constant pool entry may be represented
13709   // by multiple nodes with different offsets.
13710   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13711     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13712                                          : (const void *)C->getConstVal();
13713     Offset += C->getOffset();
13714     return false;
13715   }
13716   // If it's any of the following then it can't alias with anything but itself.
13717   return isa<FrameIndexSDNode>(Base);
13718 }
13719
13720 /// Return true if there is any possibility that the two addresses overlap.
13721 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13722   // If they are the same then they must be aliases.
13723   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13724
13725   // If they are both volatile then they cannot be reordered.
13726   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13727
13728   // Gather base node and offset information.
13729   SDValue Base1, Base2;
13730   int64_t Offset1, Offset2;
13731   const GlobalValue *GV1, *GV2;
13732   const void *CV1, *CV2;
13733   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13734                                       Base1, Offset1, GV1, CV1);
13735   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13736                                       Base2, Offset2, GV2, CV2);
13737
13738   // If they have a same base address then check to see if they overlap.
13739   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13740     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13741              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13742
13743   // It is possible for different frame indices to alias each other, mostly
13744   // when tail call optimization reuses return address slots for arguments.
13745   // To catch this case, look up the actual index of frame indices to compute
13746   // the real alias relationship.
13747   if (isFrameIndex1 && isFrameIndex2) {
13748     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13749     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13750     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13751     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13752              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13753   }
13754
13755   // Otherwise, if we know what the bases are, and they aren't identical, then
13756   // we know they cannot alias.
13757   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13758     return false;
13759
13760   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13761   // compared to the size and offset of the access, we may be able to prove they
13762   // do not alias.  This check is conservative for now to catch cases created by
13763   // splitting vector types.
13764   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13765       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13766       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13767        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13768       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13769     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13770     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13771
13772     // There is no overlap between these relatively aligned accesses of similar
13773     // size, return no alias.
13774     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13775         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13776       return false;
13777   }
13778
13779   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13780                    ? CombinerGlobalAA
13781                    : DAG.getSubtarget().useAA();
13782 #ifndef NDEBUG
13783   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13784       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13785     UseAA = false;
13786 #endif
13787   if (UseAA &&
13788       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13789     // Use alias analysis information.
13790     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13791                                  Op1->getSrcValueOffset());
13792     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13793         Op0->getSrcValueOffset() - MinOffset;
13794     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13795         Op1->getSrcValueOffset() - MinOffset;
13796     AliasAnalysis::AliasResult AAResult =
13797         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13798                                          Overlap1,
13799                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13800                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13801                                          Overlap2,
13802                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13803     if (AAResult == AliasAnalysis::NoAlias)
13804       return false;
13805   }
13806
13807   // Otherwise we have to assume they alias.
13808   return true;
13809 }
13810
13811 /// Walk up chain skipping non-aliasing memory nodes,
13812 /// looking for aliasing nodes and adding them to the Aliases vector.
13813 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13814                                    SmallVectorImpl<SDValue> &Aliases) {
13815   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13816   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13817
13818   // Get alias information for node.
13819   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13820
13821   // Starting off.
13822   Chains.push_back(OriginalChain);
13823   unsigned Depth = 0;
13824
13825   // Look at each chain and determine if it is an alias.  If so, add it to the
13826   // aliases list.  If not, then continue up the chain looking for the next
13827   // candidate.
13828   while (!Chains.empty()) {
13829     SDValue Chain = Chains.back();
13830     Chains.pop_back();
13831
13832     // For TokenFactor nodes, look at each operand and only continue up the
13833     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13834     // find more and revert to original chain since the xform is unlikely to be
13835     // profitable.
13836     //
13837     // FIXME: The depth check could be made to return the last non-aliasing
13838     // chain we found before we hit a tokenfactor rather than the original
13839     // chain.
13840     if (Depth > 6 || Aliases.size() == 2) {
13841       Aliases.clear();
13842       Aliases.push_back(OriginalChain);
13843       return;
13844     }
13845
13846     // Don't bother if we've been before.
13847     if (!Visited.insert(Chain.getNode()).second)
13848       continue;
13849
13850     switch (Chain.getOpcode()) {
13851     case ISD::EntryToken:
13852       // Entry token is ideal chain operand, but handled in FindBetterChain.
13853       break;
13854
13855     case ISD::LOAD:
13856     case ISD::STORE: {
13857       // Get alias information for Chain.
13858       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13859           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13860
13861       // If chain is alias then stop here.
13862       if (!(IsLoad && IsOpLoad) &&
13863           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13864         Aliases.push_back(Chain);
13865       } else {
13866         // Look further up the chain.
13867         Chains.push_back(Chain.getOperand(0));
13868         ++Depth;
13869       }
13870       break;
13871     }
13872
13873     case ISD::TokenFactor:
13874       // We have to check each of the operands of the token factor for "small"
13875       // token factors, so we queue them up.  Adding the operands to the queue
13876       // (stack) in reverse order maintains the original order and increases the
13877       // likelihood that getNode will find a matching token factor (CSE.)
13878       if (Chain.getNumOperands() > 16) {
13879         Aliases.push_back(Chain);
13880         break;
13881       }
13882       for (unsigned n = Chain.getNumOperands(); n;)
13883         Chains.push_back(Chain.getOperand(--n));
13884       ++Depth;
13885       break;
13886
13887     default:
13888       // For all other instructions we will just have to take what we can get.
13889       Aliases.push_back(Chain);
13890       break;
13891     }
13892   }
13893
13894   // We need to be careful here to also search for aliases through the
13895   // value operand of a store, etc. Consider the following situation:
13896   //   Token1 = ...
13897   //   L1 = load Token1, %52
13898   //   S1 = store Token1, L1, %51
13899   //   L2 = load Token1, %52+8
13900   //   S2 = store Token1, L2, %51+8
13901   //   Token2 = Token(S1, S2)
13902   //   L3 = load Token2, %53
13903   //   S3 = store Token2, L3, %52
13904   //   L4 = load Token2, %53+8
13905   //   S4 = store Token2, L4, %52+8
13906   // If we search for aliases of S3 (which loads address %52), and we look
13907   // only through the chain, then we'll miss the trivial dependence on L1
13908   // (which also loads from %52). We then might change all loads and
13909   // stores to use Token1 as their chain operand, which could result in
13910   // copying %53 into %52 before copying %52 into %51 (which should
13911   // happen first).
13912   //
13913   // The problem is, however, that searching for such data dependencies
13914   // can become expensive, and the cost is not directly related to the
13915   // chain depth. Instead, we'll rule out such configurations here by
13916   // insisting that we've visited all chain users (except for users
13917   // of the original chain, which is not necessary). When doing this,
13918   // we need to look through nodes we don't care about (otherwise, things
13919   // like register copies will interfere with trivial cases).
13920
13921   SmallVector<const SDNode *, 16> Worklist;
13922   for (const SDNode *N : Visited)
13923     if (N != OriginalChain.getNode())
13924       Worklist.push_back(N);
13925
13926   while (!Worklist.empty()) {
13927     const SDNode *M = Worklist.pop_back_val();
13928
13929     // We have already visited M, and want to make sure we've visited any uses
13930     // of M that we care about. For uses that we've not visisted, and don't
13931     // care about, queue them to the worklist.
13932
13933     for (SDNode::use_iterator UI = M->use_begin(),
13934          UIE = M->use_end(); UI != UIE; ++UI)
13935       if (UI.getUse().getValueType() == MVT::Other &&
13936           Visited.insert(*UI).second) {
13937         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13938           // We've not visited this use, and we care about it (it could have an
13939           // ordering dependency with the original node).
13940           Aliases.clear();
13941           Aliases.push_back(OriginalChain);
13942           return;
13943         }
13944
13945         // We've not visited this use, but we don't care about it. Mark it as
13946         // visited and enqueue it to the worklist.
13947         Worklist.push_back(*UI);
13948       }
13949   }
13950 }
13951
13952 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13953 /// (aliasing node.)
13954 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13955   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13956
13957   // Accumulate all the aliases to this node.
13958   GatherAllAliases(N, OldChain, Aliases);
13959
13960   // If no operands then chain to entry token.
13961   if (Aliases.size() == 0)
13962     return DAG.getEntryNode();
13963
13964   // If a single operand then chain to it.  We don't need to revisit it.
13965   if (Aliases.size() == 1)
13966     return Aliases[0];
13967
13968   // Construct a custom tailored token factor.
13969   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13970 }
13971
13972 /// This is the entry point for the file.
13973 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13974                            CodeGenOpt::Level OptLevel) {
13975   /// This is the main entry point to this class.
13976   DAGCombiner(*this, AA, OptLevel).Run(Level);
13977 }