[X86][XOP] Add support for lowering vector rotations
[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     /// Replaces all uses of the results of one DAG node with new values.
160     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161                       bool AddTo = true);
162
163     /// Replaces all uses of the results of one DAG node with new values.
164     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165       return CombineTo(N, &Res, 1, AddTo);
166     }
167
168     /// Replaces all uses of the results of one DAG node with new values.
169     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
170                       bool AddTo = true) {
171       SDValue To[] = { Res0, Res1 };
172       return CombineTo(N, To, 2, AddTo);
173     }
174
175     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176
177   private:
178
179     /// Check the specified integer node value to see if it can be simplified or
180     /// if things it uses can be simplified by bit propagation.
181     /// If so, return true.
182     bool SimplifyDemandedBits(SDValue Op) {
183       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184       APInt Demanded = APInt::getAllOnesValue(BitWidth);
185       return SimplifyDemandedBits(Op, Demanded);
186     }
187
188     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
189
190     bool CombineToPreIndexedLoadStore(SDNode *N);
191     bool CombineToPostIndexedLoadStore(SDNode *N);
192     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193     bool SliceUpLoad(SDNode *N);
194
195     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196     ///   load.
197     ///
198     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200     /// \param EltNo index of the vector element to load.
201     /// \param OriginalLoad load that EVE came from to be replaced.
202     /// \returns EVE on success SDValue() on failure.
203     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue PromoteIntBinOp(SDValue Op);
210     SDValue PromoteIntShiftOp(SDValue Op);
211     SDValue PromoteExtend(SDValue Op);
212     bool PromoteLoad(SDValue Op);
213
214     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216                          ISD::NodeType ExtType);
217
218     /// Call the node-specific routine that knows how to fold each
219     /// particular type of node. If that doesn't do anything, try the
220     /// target-specific DAG combines.
221     SDValue combine(SDNode *N);
222
223     // Visitation implementation - Implement dag node combining for different
224     // node types.  The semantics are as follows:
225     // Return Value:
226     //   SDValue.getNode() == 0 - No change was made
227     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
228     //   otherwise              - N should be replaced by the returned Operand.
229     //
230     SDValue visitTokenFactor(SDNode *N);
231     SDValue visitMERGE_VALUES(SDNode *N);
232     SDValue visitADD(SDNode *N);
233     SDValue visitSUB(SDNode *N);
234     SDValue visitADDC(SDNode *N);
235     SDValue visitSUBC(SDNode *N);
236     SDValue visitADDE(SDNode *N);
237     SDValue visitSUBE(SDNode *N);
238     SDValue visitMUL(SDNode *N);
239     SDValue useDivRem(SDNode *N);
240     SDValue visitSDIV(SDNode *N);
241     SDValue visitUDIV(SDNode *N);
242     SDValue visitREM(SDNode *N);
243     SDValue visitMULHU(SDNode *N);
244     SDValue visitMULHS(SDNode *N);
245     SDValue visitSMUL_LOHI(SDNode *N);
246     SDValue visitUMUL_LOHI(SDNode *N);
247     SDValue visitSMULO(SDNode *N);
248     SDValue visitUMULO(SDNode *N);
249     SDValue visitIMINMAX(SDNode *N);
250     SDValue visitAND(SDNode *N);
251     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitOR(SDNode *N);
253     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254     SDValue visitXOR(SDNode *N);
255     SDValue SimplifyVBinOp(SDNode *N);
256     SDValue visitSHL(SDNode *N);
257     SDValue visitSRA(SDNode *N);
258     SDValue visitSRL(SDNode *N);
259     SDValue visitRotate(SDNode *N);
260     SDValue visitBSWAP(SDNode *N);
261     SDValue visitCTLZ(SDNode *N);
262     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTTZ(SDNode *N);
264     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTPOP(SDNode *N);
266     SDValue visitSELECT(SDNode *N);
267     SDValue visitVSELECT(SDNode *N);
268     SDValue visitSELECT_CC(SDNode *N);
269     SDValue visitSETCC(SDNode *N);
270     SDValue visitSIGN_EXTEND(SDNode *N);
271     SDValue visitZERO_EXTEND(SDNode *N);
272     SDValue visitANY_EXTEND(SDNode *N);
273     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
274     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
275     SDValue visitTRUNCATE(SDNode *N);
276     SDValue visitBITCAST(SDNode *N);
277     SDValue visitBUILD_PAIR(SDNode *N);
278     SDValue visitFADD(SDNode *N);
279     SDValue visitFSUB(SDNode *N);
280     SDValue visitFMUL(SDNode *N);
281     SDValue visitFMA(SDNode *N);
282     SDValue visitFDIV(SDNode *N);
283     SDValue visitFREM(SDNode *N);
284     SDValue visitFSQRT(SDNode *N);
285     SDValue visitFCOPYSIGN(SDNode *N);
286     SDValue visitSINT_TO_FP(SDNode *N);
287     SDValue visitUINT_TO_FP(SDNode *N);
288     SDValue visitFP_TO_SINT(SDNode *N);
289     SDValue visitFP_TO_UINT(SDNode *N);
290     SDValue visitFP_ROUND(SDNode *N);
291     SDValue visitFP_ROUND_INREG(SDNode *N);
292     SDValue visitFP_EXTEND(SDNode *N);
293     SDValue visitFNEG(SDNode *N);
294     SDValue visitFABS(SDNode *N);
295     SDValue visitFCEIL(SDNode *N);
296     SDValue visitFTRUNC(SDNode *N);
297     SDValue visitFFLOOR(SDNode *N);
298     SDValue visitFMINNUM(SDNode *N);
299     SDValue visitFMAXNUM(SDNode *N);
300     SDValue visitBRCOND(SDNode *N);
301     SDValue visitBR_CC(SDNode *N);
302     SDValue visitLOAD(SDNode *N);
303
304     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
306
307     SDValue visitSTORE(SDNode *N);
308     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
309     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
310     SDValue visitBUILD_VECTOR(SDNode *N);
311     SDValue visitCONCAT_VECTORS(SDNode *N);
312     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
313     SDValue visitVECTOR_SHUFFLE(SDNode *N);
314     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
315     SDValue visitINSERT_SUBVECTOR(SDNode *N);
316     SDValue visitMLOAD(SDNode *N);
317     SDValue visitMSTORE(SDNode *N);
318     SDValue visitMGATHER(SDNode *N);
319     SDValue visitMSCATTER(SDNode *N);
320     SDValue visitFP_TO_FP16(SDNode *N);
321     SDValue visitFP16_TO_FP(SDNode *N);
322
323     SDValue visitFADDForFMACombine(SDNode *N);
324     SDValue visitFSUBForFMACombine(SDNode *N);
325     SDValue visitFMULForFMACombine(SDNode *N);
326
327     SDValue XformToShuffleWithZero(SDNode *N);
328     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
329
330     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
331
332     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
333     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
334     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
335     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
336                              SDValue N3, ISD::CondCode CC,
337                              bool NotExtCompare = false);
338     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
339                           SDLoc DL, bool foldBooleans = true);
340
341     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
342                            SDValue &CC) const;
343     bool isOneUseSetCC(SDValue N) const;
344
345     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
346                                          unsigned HiOp);
347     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
348     SDValue CombineExtLoad(SDNode *N);
349     SDValue combineRepeatedFPDivisors(SDNode *N);
350     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
351     SDValue BuildSDIV(SDNode *N);
352     SDValue BuildSDIVPow2(SDNode *N);
353     SDValue BuildUDIV(SDNode *N);
354     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
355     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
356     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
357                                  SDNodeFlags *Flags);
358     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
359                                  SDNodeFlags *Flags);
360     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
361                                bool DemandHighBits = true);
362     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
363     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
364                               SDValue InnerPos, SDValue InnerNeg,
365                               unsigned PosOpcode, unsigned NegOpcode,
366                               SDLoc DL);
367     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
368     SDValue ReduceLoadWidth(SDNode *N);
369     SDValue ReduceLoadOpStoreWidth(SDNode *N);
370     SDValue TransformFPLoadStorePair(SDNode *N);
371     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
372     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
373
374     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
375
376     /// Walk up chain skipping non-aliasing memory nodes,
377     /// looking for aliasing nodes and adding them to the Aliases vector.
378     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
379                           SmallVectorImpl<SDValue> &Aliases);
380
381     /// Return true if there is any possibility that the two addresses overlap.
382     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
383
384     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
385     /// chain (aliasing node.)
386     SDValue FindBetterChain(SDNode *N, SDValue Chain);
387
388     /// Do FindBetterChain for a store and any possibly adjacent stores on
389     /// consecutive chains.
390     bool findBetterNeighborChains(StoreSDNode *St);
391
392     /// Holds a pointer to an LSBaseSDNode as well as information on where it
393     /// is located in a sequence of memory operations connected by a chain.
394     struct MemOpLink {
395       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
396       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
397       // Ptr to the mem node.
398       LSBaseSDNode *MemNode;
399       // Offset from the base ptr.
400       int64_t OffsetFromBase;
401       // What is the sequence number of this mem node.
402       // Lowest mem operand in the DAG starts at zero.
403       unsigned SequenceNum;
404     };
405
406     /// This is a helper function for visitMUL to check the profitability
407     /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
408     /// MulNode is the original multiply, AddNode is (add x, c1),
409     /// and ConstNode is c2.
410     bool isMulAddWithConstProfitable(SDNode *MulNode,
411                                      SDValue &AddNode,
412                                      SDValue &ConstNode);
413
414     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
415     /// constant build_vector of the stored constant values in Stores.
416     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
417                                          SDLoc SL,
418                                          ArrayRef<MemOpLink> Stores,
419                                          SmallVectorImpl<SDValue> &Chains,
420                                          EVT Ty) const;
421
422     /// This is a helper function for MergeConsecutiveStores. When the source
423     /// elements of the consecutive stores are all constants or all extracted
424     /// vector elements, try to merge them into one larger store.
425     /// \return True if a merged store was created.
426     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
427                                          EVT MemVT, unsigned NumStores,
428                                          bool IsConstantSrc, bool UseVector);
429
430     /// This is a helper function for MergeConsecutiveStores.
431     /// Stores that may be merged are placed in StoreNodes.
432     /// Loads that may alias with those stores are placed in AliasLoadNodes.
433     void getStoreMergeAndAliasCandidates(
434         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
435         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
436
437     /// Merge consecutive store operations into a wide store.
438     /// This optimization uses wide integers or vectors when possible.
439     /// \return True if some memory operations were changed.
440     bool MergeConsecutiveStores(StoreSDNode *N);
441
442     /// \brief Try to transform a truncation where C is a constant:
443     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
444     ///
445     /// \p N needs to be a truncation and its first operand an AND. Other
446     /// requirements are checked by the function (e.g. that trunc is
447     /// single-use) and if missed an empty SDValue is returned.
448     SDValue distributeTruncateThroughAnd(SDNode *N);
449
450   public:
451     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
452         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
453           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
454       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
455     }
456
457     /// Runs the dag combiner on all nodes in the work list
458     void Run(CombineLevel AtLevel);
459
460     SelectionDAG &getDAG() const { return DAG; }
461
462     /// Returns a type large enough to hold any valid shift amount - before type
463     /// legalization these can be huge.
464     EVT getShiftAmountTy(EVT LHSTy) {
465       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
466       if (LHSTy.isVector())
467         return LHSTy;
468       auto &DL = DAG.getDataLayout();
469       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
470                         : TLI.getPointerTy(DL);
471     }
472
473     /// This method returns true if we are running before type legalization or
474     /// if the specified VT is legal.
475     bool isTypeLegal(const EVT &VT) {
476       if (!LegalTypes) return true;
477       return TLI.isTypeLegal(VT);
478     }
479
480     /// Convenience wrapper around TargetLowering::getSetCCResultType
481     EVT getSetCCResultType(EVT VT) const {
482       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
483     }
484   };
485 }
486
487
488 namespace {
489 /// This class is a DAGUpdateListener that removes any deleted
490 /// nodes from the worklist.
491 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
492   DAGCombiner &DC;
493 public:
494   explicit WorklistRemover(DAGCombiner &dc)
495     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
496
497   void NodeDeleted(SDNode *N, SDNode *E) override {
498     DC.removeFromWorklist(N);
499   }
500 };
501 }
502
503 //===----------------------------------------------------------------------===//
504 //  TargetLowering::DAGCombinerInfo implementation
505 //===----------------------------------------------------------------------===//
506
507 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
508   ((DAGCombiner*)DC)->AddToWorklist(N);
509 }
510
511 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
512   ((DAGCombiner*)DC)->removeFromWorklist(N);
513 }
514
515 SDValue TargetLowering::DAGCombinerInfo::
516 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
517   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
518 }
519
520 SDValue TargetLowering::DAGCombinerInfo::
521 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
522   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
523 }
524
525
526 SDValue TargetLowering::DAGCombinerInfo::
527 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
528   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
529 }
530
531 void TargetLowering::DAGCombinerInfo::
532 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
533   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
534 }
535
536 //===----------------------------------------------------------------------===//
537 // Helper Functions
538 //===----------------------------------------------------------------------===//
539
540 void DAGCombiner::deleteAndRecombine(SDNode *N) {
541   removeFromWorklist(N);
542
543   // If the operands of this node are only used by the node, they will now be
544   // dead. Make sure to re-visit them and recursively delete dead nodes.
545   for (const SDValue &Op : N->ops())
546     // For an operand generating multiple values, one of the values may
547     // become dead allowing further simplification (e.g. split index
548     // arithmetic from an indexed load).
549     if (Op->hasOneUse() || Op->getNumValues() > 1)
550       AddToWorklist(Op.getNode());
551
552   DAG.DeleteNode(N);
553 }
554
555 /// Return 1 if we can compute the negated form of the specified expression for
556 /// the same cost as the expression itself, or 2 if we can compute the negated
557 /// form more cheaply than the expression itself.
558 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
559                                const TargetLowering &TLI,
560                                const TargetOptions *Options,
561                                unsigned Depth = 0) {
562   // fneg is removable even if it has multiple uses.
563   if (Op.getOpcode() == ISD::FNEG) return 2;
564
565   // Don't allow anything with multiple uses.
566   if (!Op.hasOneUse()) return 0;
567
568   // Don't recurse exponentially.
569   if (Depth > 6) return 0;
570
571   switch (Op.getOpcode()) {
572   default: return false;
573   case ISD::ConstantFP:
574     // Don't invert constant FP values after legalize.  The negated constant
575     // isn't necessarily legal.
576     return LegalOperations ? 0 : 1;
577   case ISD::FADD:
578     // FIXME: determine better conditions for this xform.
579     if (!Options->UnsafeFPMath) return 0;
580
581     // After operation legalization, it might not be legal to create new FSUBs.
582     if (LegalOperations &&
583         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
584       return 0;
585
586     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
587     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
588                                     Options, Depth + 1))
589       return V;
590     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
591     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
592                               Depth + 1);
593   case ISD::FSUB:
594     // We can't turn -(A-B) into B-A when we honor signed zeros.
595     if (!Options->UnsafeFPMath) return 0;
596
597     // fold (fneg (fsub A, B)) -> (fsub B, A)
598     return 1;
599
600   case ISD::FMUL:
601   case ISD::FDIV:
602     if (Options->HonorSignDependentRoundingFPMath()) return 0;
603
604     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
605     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
606                                     Options, Depth + 1))
607       return V;
608
609     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
610                               Depth + 1);
611
612   case ISD::FP_EXTEND:
613   case ISD::FP_ROUND:
614   case ISD::FSIN:
615     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
616                               Depth + 1);
617   }
618 }
619
620 /// If isNegatibleForFree returns true, return the newly negated expression.
621 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
622                                     bool LegalOperations, unsigned Depth = 0) {
623   const TargetOptions &Options = DAG.getTarget().Options;
624   // fneg is removable even if it has multiple uses.
625   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
626
627   // Don't allow anything with multiple uses.
628   assert(Op.hasOneUse() && "Unknown reuse!");
629
630   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
631
632   const SDNodeFlags *Flags = Op.getNode()->getFlags();
633
634   switch (Op.getOpcode()) {
635   default: llvm_unreachable("Unknown code");
636   case ISD::ConstantFP: {
637     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
638     V.changeSign();
639     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
640   }
641   case ISD::FADD:
642     // FIXME: determine better conditions for this xform.
643     assert(Options.UnsafeFPMath);
644
645     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
646     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
647                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
648       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
649                          GetNegatedExpression(Op.getOperand(0), DAG,
650                                               LegalOperations, Depth+1),
651                          Op.getOperand(1), Flags);
652     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
653     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
654                        GetNegatedExpression(Op.getOperand(1), DAG,
655                                             LegalOperations, Depth+1),
656                        Op.getOperand(0), Flags);
657   case ISD::FSUB:
658     // We can't turn -(A-B) into B-A when we honor signed zeros.
659     assert(Options.UnsafeFPMath);
660
661     // fold (fneg (fsub 0, B)) -> B
662     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
663       if (N0CFP->isZero())
664         return Op.getOperand(1);
665
666     // fold (fneg (fsub A, B)) -> (fsub B, A)
667     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
668                        Op.getOperand(1), Op.getOperand(0), Flags);
669
670   case ISD::FMUL:
671   case ISD::FDIV:
672     assert(!Options.HonorSignDependentRoundingFPMath());
673
674     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
675     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
676                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
677       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
678                          GetNegatedExpression(Op.getOperand(0), DAG,
679                                               LegalOperations, Depth+1),
680                          Op.getOperand(1), Flags);
681
682     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
683     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
684                        Op.getOperand(0),
685                        GetNegatedExpression(Op.getOperand(1), DAG,
686                                             LegalOperations, Depth+1), Flags);
687
688   case ISD::FP_EXTEND:
689   case ISD::FSIN:
690     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
691                        GetNegatedExpression(Op.getOperand(0), DAG,
692                                             LegalOperations, Depth+1));
693   case ISD::FP_ROUND:
694       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
695                          GetNegatedExpression(Op.getOperand(0), DAG,
696                                               LegalOperations, Depth+1),
697                          Op.getOperand(1));
698   }
699 }
700
701 // Return true if this node is a setcc, or is a select_cc
702 // that selects between the target values used for true and false, making it
703 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
704 // the appropriate nodes based on the type of node we are checking. This
705 // simplifies life a bit for the callers.
706 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
707                                     SDValue &CC) const {
708   if (N.getOpcode() == ISD::SETCC) {
709     LHS = N.getOperand(0);
710     RHS = N.getOperand(1);
711     CC  = N.getOperand(2);
712     return true;
713   }
714
715   if (N.getOpcode() != ISD::SELECT_CC ||
716       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
717       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
718     return false;
719
720   if (TLI.getBooleanContents(N.getValueType()) ==
721       TargetLowering::UndefinedBooleanContent)
722     return false;
723
724   LHS = N.getOperand(0);
725   RHS = N.getOperand(1);
726   CC  = N.getOperand(4);
727   return true;
728 }
729
730 /// Return true if this is a SetCC-equivalent operation with only one use.
731 /// If this is true, it allows the users to invert the operation for free when
732 /// it is profitable to do so.
733 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
734   SDValue N0, N1, N2;
735   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
736     return true;
737   return false;
738 }
739
740 /// Returns true if N is a BUILD_VECTOR node whose
741 /// elements are all the same constant or undefined.
742 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
743   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
744   if (!C)
745     return false;
746
747   APInt SplatUndef;
748   unsigned SplatBitSize;
749   bool HasAnyUndefs;
750   EVT EltVT = N->getValueType(0).getVectorElementType();
751   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
752                              HasAnyUndefs) &&
753           EltVT.getSizeInBits() >= SplatBitSize);
754 }
755
756 // \brief Returns the SDNode if it is a constant integer BuildVector
757 // or constant integer.
758 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
759   if (isa<ConstantSDNode>(N))
760     return N.getNode();
761   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
762     return N.getNode();
763   return nullptr;
764 }
765
766 // \brief Returns the SDNode if it is a constant float BuildVector
767 // or constant float.
768 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
769   if (isa<ConstantFPSDNode>(N))
770     return N.getNode();
771   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
772     return N.getNode();
773   return nullptr;
774 }
775
776 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
777 // int.
778 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
779   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
780     return CN;
781
782   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
783     BitVector UndefElements;
784     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
785
786     // BuildVectors can truncate their operands. Ignore that case here.
787     // FIXME: We blindly ignore splats which include undef which is overly
788     // pessimistic.
789     if (CN && UndefElements.none() &&
790         CN->getValueType(0) == N.getValueType().getScalarType())
791       return CN;
792   }
793
794   return nullptr;
795 }
796
797 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
798 // float.
799 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
800   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
801     return CN;
802
803   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
804     BitVector UndefElements;
805     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
806
807     if (CN && UndefElements.none())
808       return CN;
809   }
810
811   return nullptr;
812 }
813
814 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
815                                     SDValue N0, SDValue N1) {
816   EVT VT = N0.getValueType();
817   if (N0.getOpcode() == Opc) {
818     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
819       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
820         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
821         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
822           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
823         return SDValue();
824       }
825       if (N0.hasOneUse()) {
826         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
827         // use
828         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
829         if (!OpNode.getNode())
830           return SDValue();
831         AddToWorklist(OpNode.getNode());
832         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
833       }
834     }
835   }
836
837   if (N1.getOpcode() == Opc) {
838     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
839       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
840         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
841         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
842           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
843         return SDValue();
844       }
845       if (N1.hasOneUse()) {
846         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
847         // use
848         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
849         if (!OpNode.getNode())
850           return SDValue();
851         AddToWorklist(OpNode.getNode());
852         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
853       }
854     }
855   }
856
857   return SDValue();
858 }
859
860 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
861                                bool AddTo) {
862   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
863   ++NodesCombined;
864   DEBUG(dbgs() << "\nReplacing.1 ";
865         N->dump(&DAG);
866         dbgs() << "\nWith: ";
867         To[0].getNode()->dump(&DAG);
868         dbgs() << " and " << NumTo-1 << " other values\n");
869   for (unsigned i = 0, e = NumTo; i != e; ++i)
870     assert((!To[i].getNode() ||
871             N->getValueType(i) == To[i].getValueType()) &&
872            "Cannot combine value to value of different type!");
873
874   WorklistRemover DeadNodes(*this);
875   DAG.ReplaceAllUsesWith(N, To);
876   if (AddTo) {
877     // Push the new nodes and any users onto the worklist
878     for (unsigned i = 0, e = NumTo; i != e; ++i) {
879       if (To[i].getNode()) {
880         AddToWorklist(To[i].getNode());
881         AddUsersToWorklist(To[i].getNode());
882       }
883     }
884   }
885
886   // Finally, if the node is now dead, remove it from the graph.  The node
887   // may not be dead if the replacement process recursively simplified to
888   // something else needing this node.
889   if (N->use_empty())
890     deleteAndRecombine(N);
891   return SDValue(N, 0);
892 }
893
894 void DAGCombiner::
895 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
896   // Replace all uses.  If any nodes become isomorphic to other nodes and
897   // are deleted, make sure to remove them from our worklist.
898   WorklistRemover DeadNodes(*this);
899   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
900
901   // Push the new node and any (possibly new) users onto the worklist.
902   AddToWorklist(TLO.New.getNode());
903   AddUsersToWorklist(TLO.New.getNode());
904
905   // Finally, if the node is now dead, remove it from the graph.  The node
906   // may not be dead if the replacement process recursively simplified to
907   // something else needing this node.
908   if (TLO.Old.getNode()->use_empty())
909     deleteAndRecombine(TLO.Old.getNode());
910 }
911
912 /// Check the specified integer node value to see if it can be simplified or if
913 /// things it uses can be simplified by bit propagation. If so, return true.
914 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
915   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
916   APInt KnownZero, KnownOne;
917   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
918     return false;
919
920   // Revisit the node.
921   AddToWorklist(Op.getNode());
922
923   // Replace the old value with the new one.
924   ++NodesCombined;
925   DEBUG(dbgs() << "\nReplacing.2 ";
926         TLO.Old.getNode()->dump(&DAG);
927         dbgs() << "\nWith: ";
928         TLO.New.getNode()->dump(&DAG);
929         dbgs() << '\n');
930
931   CommitTargetLoweringOpt(TLO);
932   return true;
933 }
934
935 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
936   SDLoc dl(Load);
937   EVT VT = Load->getValueType(0);
938   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
939
940   DEBUG(dbgs() << "\nReplacing.9 ";
941         Load->dump(&DAG);
942         dbgs() << "\nWith: ";
943         Trunc.getNode()->dump(&DAG);
944         dbgs() << '\n');
945   WorklistRemover DeadNodes(*this);
946   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
947   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
948   deleteAndRecombine(Load);
949   AddToWorklist(Trunc.getNode());
950 }
951
952 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
953   Replace = false;
954   SDLoc dl(Op);
955   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
956     EVT MemVT = LD->getMemoryVT();
957     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
958       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
959                                                        : ISD::EXTLOAD)
960       : LD->getExtensionType();
961     Replace = true;
962     return DAG.getExtLoad(ExtType, dl, PVT,
963                           LD->getChain(), LD->getBasePtr(),
964                           MemVT, LD->getMemOperand());
965   }
966
967   unsigned Opc = Op.getOpcode();
968   switch (Opc) {
969   default: break;
970   case ISD::AssertSext:
971     return DAG.getNode(ISD::AssertSext, dl, PVT,
972                        SExtPromoteOperand(Op.getOperand(0), PVT),
973                        Op.getOperand(1));
974   case ISD::AssertZext:
975     return DAG.getNode(ISD::AssertZext, dl, PVT,
976                        ZExtPromoteOperand(Op.getOperand(0), PVT),
977                        Op.getOperand(1));
978   case ISD::Constant: {
979     unsigned ExtOpc =
980       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
981     return DAG.getNode(ExtOpc, dl, PVT, Op);
982   }
983   }
984
985   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
986     return SDValue();
987   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
988 }
989
990 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
991   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
992     return SDValue();
993   EVT OldVT = Op.getValueType();
994   SDLoc dl(Op);
995   bool Replace = false;
996   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
997   if (!NewOp.getNode())
998     return SDValue();
999   AddToWorklist(NewOp.getNode());
1000
1001   if (Replace)
1002     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1003   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
1004                      DAG.getValueType(OldVT));
1005 }
1006
1007 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1008   EVT OldVT = Op.getValueType();
1009   SDLoc dl(Op);
1010   bool Replace = false;
1011   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1012   if (!NewOp.getNode())
1013     return SDValue();
1014   AddToWorklist(NewOp.getNode());
1015
1016   if (Replace)
1017     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1018   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1019 }
1020
1021 /// Promote the specified integer binary operation if the target indicates it is
1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1023 /// i32 since i16 instructions are longer.
1024 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1025   if (!LegalOperations)
1026     return SDValue();
1027
1028   EVT VT = Op.getValueType();
1029   if (VT.isVector() || !VT.isInteger())
1030     return SDValue();
1031
1032   // If operation type is 'undesirable', e.g. i16 on x86, consider
1033   // promoting it.
1034   unsigned Opc = Op.getOpcode();
1035   if (TLI.isTypeDesirableForOp(Opc, VT))
1036     return SDValue();
1037
1038   EVT PVT = VT;
1039   // Consult target whether it is a good idea to promote this operation and
1040   // what's the right type to promote it to.
1041   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1042     assert(PVT != VT && "Don't know what type to promote to!");
1043
1044     bool Replace0 = false;
1045     SDValue N0 = Op.getOperand(0);
1046     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1047     if (!NN0.getNode())
1048       return SDValue();
1049
1050     bool Replace1 = false;
1051     SDValue N1 = Op.getOperand(1);
1052     SDValue NN1;
1053     if (N0 == N1)
1054       NN1 = NN0;
1055     else {
1056       NN1 = PromoteOperand(N1, PVT, Replace1);
1057       if (!NN1.getNode())
1058         return SDValue();
1059     }
1060
1061     AddToWorklist(NN0.getNode());
1062     if (NN1.getNode())
1063       AddToWorklist(NN1.getNode());
1064
1065     if (Replace0)
1066       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1067     if (Replace1)
1068       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1069
1070     DEBUG(dbgs() << "\nPromoting ";
1071           Op.getNode()->dump(&DAG));
1072     SDLoc dl(Op);
1073     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1074                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1075   }
1076   return SDValue();
1077 }
1078
1079 /// Promote the specified integer shift operation if the target indicates it is
1080 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1081 /// i32 since i16 instructions are longer.
1082 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1083   if (!LegalOperations)
1084     return SDValue();
1085
1086   EVT VT = Op.getValueType();
1087   if (VT.isVector() || !VT.isInteger())
1088     return SDValue();
1089
1090   // If operation type is 'undesirable', e.g. i16 on x86, consider
1091   // promoting it.
1092   unsigned Opc = Op.getOpcode();
1093   if (TLI.isTypeDesirableForOp(Opc, VT))
1094     return SDValue();
1095
1096   EVT PVT = VT;
1097   // Consult target whether it is a good idea to promote this operation and
1098   // what's the right type to promote it to.
1099   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100     assert(PVT != VT && "Don't know what type to promote to!");
1101
1102     bool Replace = false;
1103     SDValue N0 = Op.getOperand(0);
1104     if (Opc == ISD::SRA)
1105       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1106     else if (Opc == ISD::SRL)
1107       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1108     else
1109       N0 = PromoteOperand(N0, PVT, Replace);
1110     if (!N0.getNode())
1111       return SDValue();
1112
1113     AddToWorklist(N0.getNode());
1114     if (Replace)
1115       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1116
1117     DEBUG(dbgs() << "\nPromoting ";
1118           Op.getNode()->dump(&DAG));
1119     SDLoc dl(Op);
1120     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1121                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1122   }
1123   return SDValue();
1124 }
1125
1126 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1127   if (!LegalOperations)
1128     return SDValue();
1129
1130   EVT VT = Op.getValueType();
1131   if (VT.isVector() || !VT.isInteger())
1132     return SDValue();
1133
1134   // If operation type is 'undesirable', e.g. i16 on x86, consider
1135   // promoting it.
1136   unsigned Opc = Op.getOpcode();
1137   if (TLI.isTypeDesirableForOp(Opc, VT))
1138     return SDValue();
1139
1140   EVT PVT = VT;
1141   // Consult target whether it is a good idea to promote this operation and
1142   // what's the right type to promote it to.
1143   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1144     assert(PVT != VT && "Don't know what type to promote to!");
1145     // fold (aext (aext x)) -> (aext x)
1146     // fold (aext (zext x)) -> (zext x)
1147     // fold (aext (sext x)) -> (sext x)
1148     DEBUG(dbgs() << "\nPromoting ";
1149           Op.getNode()->dump(&DAG));
1150     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1151   }
1152   return SDValue();
1153 }
1154
1155 bool DAGCombiner::PromoteLoad(SDValue Op) {
1156   if (!LegalOperations)
1157     return false;
1158
1159   EVT VT = Op.getValueType();
1160   if (VT.isVector() || !VT.isInteger())
1161     return false;
1162
1163   // If operation type is 'undesirable', e.g. i16 on x86, consider
1164   // promoting it.
1165   unsigned Opc = Op.getOpcode();
1166   if (TLI.isTypeDesirableForOp(Opc, VT))
1167     return false;
1168
1169   EVT PVT = VT;
1170   // Consult target whether it is a good idea to promote this operation and
1171   // what's the right type to promote it to.
1172   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1173     assert(PVT != VT && "Don't know what type to promote to!");
1174
1175     SDLoc dl(Op);
1176     SDNode *N = Op.getNode();
1177     LoadSDNode *LD = cast<LoadSDNode>(N);
1178     EVT MemVT = LD->getMemoryVT();
1179     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1180       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1181                                                        : ISD::EXTLOAD)
1182       : LD->getExtensionType();
1183     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1184                                    LD->getChain(), LD->getBasePtr(),
1185                                    MemVT, LD->getMemOperand());
1186     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1187
1188     DEBUG(dbgs() << "\nPromoting ";
1189           N->dump(&DAG);
1190           dbgs() << "\nTo: ";
1191           Result.getNode()->dump(&DAG);
1192           dbgs() << '\n');
1193     WorklistRemover DeadNodes(*this);
1194     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1195     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1196     deleteAndRecombine(N);
1197     AddToWorklist(Result.getNode());
1198     return true;
1199   }
1200   return false;
1201 }
1202
1203 /// \brief Recursively delete a node which has no uses and any operands for
1204 /// which it is the only use.
1205 ///
1206 /// Note that this both deletes the nodes and removes them from the worklist.
1207 /// It also adds any nodes who have had a user deleted to the worklist as they
1208 /// may now have only one use and subject to other combines.
1209 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1210   if (!N->use_empty())
1211     return false;
1212
1213   SmallSetVector<SDNode *, 16> Nodes;
1214   Nodes.insert(N);
1215   do {
1216     N = Nodes.pop_back_val();
1217     if (!N)
1218       continue;
1219
1220     if (N->use_empty()) {
1221       for (const SDValue &ChildN : N->op_values())
1222         Nodes.insert(ChildN.getNode());
1223
1224       removeFromWorklist(N);
1225       DAG.DeleteNode(N);
1226     } else {
1227       AddToWorklist(N);
1228     }
1229   } while (!Nodes.empty());
1230   return true;
1231 }
1232
1233 //===----------------------------------------------------------------------===//
1234 //  Main DAG Combiner implementation
1235 //===----------------------------------------------------------------------===//
1236
1237 void DAGCombiner::Run(CombineLevel AtLevel) {
1238   // set the instance variables, so that the various visit routines may use it.
1239   Level = AtLevel;
1240   LegalOperations = Level >= AfterLegalizeVectorOps;
1241   LegalTypes = Level >= AfterLegalizeTypes;
1242
1243   // Add all the dag nodes to the worklist.
1244   for (SDNode &Node : DAG.allnodes())
1245     AddToWorklist(&Node);
1246
1247   // Create a dummy node (which is not added to allnodes), that adds a reference
1248   // to the root node, preventing it from being deleted, and tracking any
1249   // changes of the root.
1250   HandleSDNode Dummy(DAG.getRoot());
1251
1252   // while the worklist isn't empty, find a node and
1253   // try and combine it.
1254   while (!WorklistMap.empty()) {
1255     SDNode *N;
1256     // The Worklist holds the SDNodes in order, but it may contain null entries.
1257     do {
1258       N = Worklist.pop_back_val();
1259     } while (!N);
1260
1261     bool GoodWorklistEntry = WorklistMap.erase(N);
1262     (void)GoodWorklistEntry;
1263     assert(GoodWorklistEntry &&
1264            "Found a worklist entry without a corresponding map entry!");
1265
1266     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1267     // N is deleted from the DAG, since they too may now be dead or may have a
1268     // reduced number of uses, allowing other xforms.
1269     if (recursivelyDeleteUnusedNodes(N))
1270       continue;
1271
1272     WorklistRemover DeadNodes(*this);
1273
1274     // If this combine is running after legalizing the DAG, re-legalize any
1275     // nodes pulled off the worklist.
1276     if (Level == AfterLegalizeDAG) {
1277       SmallSetVector<SDNode *, 16> UpdatedNodes;
1278       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1279
1280       for (SDNode *LN : UpdatedNodes) {
1281         AddToWorklist(LN);
1282         AddUsersToWorklist(LN);
1283       }
1284       if (!NIsValid)
1285         continue;
1286     }
1287
1288     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1289
1290     // Add any operands of the new node which have not yet been combined to the
1291     // worklist as well. Because the worklist uniques things already, this
1292     // won't repeatedly process the same operand.
1293     CombinedNodes.insert(N);
1294     for (const SDValue &ChildN : N->op_values())
1295       if (!CombinedNodes.count(ChildN.getNode()))
1296         AddToWorklist(ChildN.getNode());
1297
1298     SDValue RV = combine(N);
1299
1300     if (!RV.getNode())
1301       continue;
1302
1303     ++NodesCombined;
1304
1305     // If we get back the same node we passed in, rather than a new node or
1306     // zero, we know that the node must have defined multiple values and
1307     // CombineTo was used.  Since CombineTo takes care of the worklist
1308     // mechanics for us, we have no work to do in this case.
1309     if (RV.getNode() == N)
1310       continue;
1311
1312     assert(N->getOpcode() != ISD::DELETED_NODE &&
1313            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1314            "Node was deleted but visit returned new node!");
1315
1316     DEBUG(dbgs() << " ... into: ";
1317           RV.getNode()->dump(&DAG));
1318
1319     // Transfer debug value.
1320     DAG.TransferDbgValues(SDValue(N, 0), RV);
1321     if (N->getNumValues() == RV.getNode()->getNumValues())
1322       DAG.ReplaceAllUsesWith(N, RV.getNode());
1323     else {
1324       assert(N->getValueType(0) == RV.getValueType() &&
1325              N->getNumValues() == 1 && "Type mismatch");
1326       SDValue OpV = RV;
1327       DAG.ReplaceAllUsesWith(N, &OpV);
1328     }
1329
1330     // Push the new node and any users onto the worklist
1331     AddToWorklist(RV.getNode());
1332     AddUsersToWorklist(RV.getNode());
1333
1334     // Finally, if the node is now dead, remove it from the graph.  The node
1335     // may not be dead if the replacement process recursively simplified to
1336     // something else needing this node. This will also take care of adding any
1337     // operands which have lost a user to the worklist.
1338     recursivelyDeleteUnusedNodes(N);
1339   }
1340
1341   // If the root changed (e.g. it was a dead load, update the root).
1342   DAG.setRoot(Dummy.getValue());
1343   DAG.RemoveDeadNodes();
1344 }
1345
1346 SDValue DAGCombiner::visit(SDNode *N) {
1347   switch (N->getOpcode()) {
1348   default: break;
1349   case ISD::TokenFactor:        return visitTokenFactor(N);
1350   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1351   case ISD::ADD:                return visitADD(N);
1352   case ISD::SUB:                return visitSUB(N);
1353   case ISD::ADDC:               return visitADDC(N);
1354   case ISD::SUBC:               return visitSUBC(N);
1355   case ISD::ADDE:               return visitADDE(N);
1356   case ISD::SUBE:               return visitSUBE(N);
1357   case ISD::MUL:                return visitMUL(N);
1358   case ISD::SDIV:               return visitSDIV(N);
1359   case ISD::UDIV:               return visitUDIV(N);
1360   case ISD::SREM:
1361   case ISD::UREM:               return visitREM(N);
1362   case ISD::MULHU:              return visitMULHU(N);
1363   case ISD::MULHS:              return visitMULHS(N);
1364   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1365   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1366   case ISD::SMULO:              return visitSMULO(N);
1367   case ISD::UMULO:              return visitUMULO(N);
1368   case ISD::SMIN:
1369   case ISD::SMAX:
1370   case ISD::UMIN:
1371   case ISD::UMAX:               return visitIMINMAX(N);
1372   case ISD::AND:                return visitAND(N);
1373   case ISD::OR:                 return visitOR(N);
1374   case ISD::XOR:                return visitXOR(N);
1375   case ISD::SHL:                return visitSHL(N);
1376   case ISD::SRA:                return visitSRA(N);
1377   case ISD::SRL:                return visitSRL(N);
1378   case ISD::ROTR:
1379   case ISD::ROTL:               return visitRotate(N);
1380   case ISD::BSWAP:              return visitBSWAP(N);
1381   case ISD::CTLZ:               return visitCTLZ(N);
1382   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1383   case ISD::CTTZ:               return visitCTTZ(N);
1384   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1385   case ISD::CTPOP:              return visitCTPOP(N);
1386   case ISD::SELECT:             return visitSELECT(N);
1387   case ISD::VSELECT:            return visitVSELECT(N);
1388   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1389   case ISD::SETCC:              return visitSETCC(N);
1390   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1391   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1392   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1393   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1394   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1395   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1396   case ISD::BITCAST:            return visitBITCAST(N);
1397   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1398   case ISD::FADD:               return visitFADD(N);
1399   case ISD::FSUB:               return visitFSUB(N);
1400   case ISD::FMUL:               return visitFMUL(N);
1401   case ISD::FMA:                return visitFMA(N);
1402   case ISD::FDIV:               return visitFDIV(N);
1403   case ISD::FREM:               return visitFREM(N);
1404   case ISD::FSQRT:              return visitFSQRT(N);
1405   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1406   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1407   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1408   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1409   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1410   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1411   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1412   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1413   case ISD::FNEG:               return visitFNEG(N);
1414   case ISD::FABS:               return visitFABS(N);
1415   case ISD::FFLOOR:             return visitFFLOOR(N);
1416   case ISD::FMINNUM:            return visitFMINNUM(N);
1417   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1418   case ISD::FCEIL:              return visitFCEIL(N);
1419   case ISD::FTRUNC:             return visitFTRUNC(N);
1420   case ISD::BRCOND:             return visitBRCOND(N);
1421   case ISD::BR_CC:              return visitBR_CC(N);
1422   case ISD::LOAD:               return visitLOAD(N);
1423   case ISD::STORE:              return visitSTORE(N);
1424   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1425   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1426   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1427   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1428   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1429   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1430   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1431   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1432   case ISD::MGATHER:            return visitMGATHER(N);
1433   case ISD::MLOAD:              return visitMLOAD(N);
1434   case ISD::MSCATTER:           return visitMSCATTER(N);
1435   case ISD::MSTORE:             return visitMSTORE(N);
1436   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1437   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1438   }
1439   return SDValue();
1440 }
1441
1442 SDValue DAGCombiner::combine(SDNode *N) {
1443   SDValue RV = visit(N);
1444
1445   // If nothing happened, try a target-specific DAG combine.
1446   if (!RV.getNode()) {
1447     assert(N->getOpcode() != ISD::DELETED_NODE &&
1448            "Node was deleted but visit returned NULL!");
1449
1450     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1451         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1452
1453       // Expose the DAG combiner to the target combiner impls.
1454       TargetLowering::DAGCombinerInfo
1455         DagCombineInfo(DAG, Level, false, this);
1456
1457       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1458     }
1459   }
1460
1461   // If nothing happened still, try promoting the operation.
1462   if (!RV.getNode()) {
1463     switch (N->getOpcode()) {
1464     default: break;
1465     case ISD::ADD:
1466     case ISD::SUB:
1467     case ISD::MUL:
1468     case ISD::AND:
1469     case ISD::OR:
1470     case ISD::XOR:
1471       RV = PromoteIntBinOp(SDValue(N, 0));
1472       break;
1473     case ISD::SHL:
1474     case ISD::SRA:
1475     case ISD::SRL:
1476       RV = PromoteIntShiftOp(SDValue(N, 0));
1477       break;
1478     case ISD::SIGN_EXTEND:
1479     case ISD::ZERO_EXTEND:
1480     case ISD::ANY_EXTEND:
1481       RV = PromoteExtend(SDValue(N, 0));
1482       break;
1483     case ISD::LOAD:
1484       if (PromoteLoad(SDValue(N, 0)))
1485         RV = SDValue(N, 0);
1486       break;
1487     }
1488   }
1489
1490   // If N is a commutative binary node, try commuting it to enable more
1491   // sdisel CSE.
1492   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1493       N->getNumValues() == 1) {
1494     SDValue N0 = N->getOperand(0);
1495     SDValue N1 = N->getOperand(1);
1496
1497     // Constant operands are canonicalized to RHS.
1498     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1499       SDValue Ops[] = {N1, N0};
1500       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1501                                             N->getFlags());
1502       if (CSENode)
1503         return SDValue(CSENode, 0);
1504     }
1505   }
1506
1507   return RV;
1508 }
1509
1510 /// Given a node, return its input chain if it has one, otherwise return a null
1511 /// sd operand.
1512 static SDValue getInputChainForNode(SDNode *N) {
1513   if (unsigned NumOps = N->getNumOperands()) {
1514     if (N->getOperand(0).getValueType() == MVT::Other)
1515       return N->getOperand(0);
1516     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1517       return N->getOperand(NumOps-1);
1518     for (unsigned i = 1; i < NumOps-1; ++i)
1519       if (N->getOperand(i).getValueType() == MVT::Other)
1520         return N->getOperand(i);
1521   }
1522   return SDValue();
1523 }
1524
1525 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1526   // If N has two operands, where one has an input chain equal to the other,
1527   // the 'other' chain is redundant.
1528   if (N->getNumOperands() == 2) {
1529     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1530       return N->getOperand(0);
1531     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1532       return N->getOperand(1);
1533   }
1534
1535   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1536   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1537   SmallPtrSet<SDNode*, 16> SeenOps;
1538   bool Changed = false;             // If we should replace this token factor.
1539
1540   // Start out with this token factor.
1541   TFs.push_back(N);
1542
1543   // Iterate through token factors.  The TFs grows when new token factors are
1544   // encountered.
1545   for (unsigned i = 0; i < TFs.size(); ++i) {
1546     SDNode *TF = TFs[i];
1547
1548     // Check each of the operands.
1549     for (const SDValue &Op : TF->op_values()) {
1550
1551       switch (Op.getOpcode()) {
1552       case ISD::EntryToken:
1553         // Entry tokens don't need to be added to the list. They are
1554         // redundant.
1555         Changed = true;
1556         break;
1557
1558       case ISD::TokenFactor:
1559         if (Op.hasOneUse() &&
1560             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1561           // Queue up for processing.
1562           TFs.push_back(Op.getNode());
1563           // Clean up in case the token factor is removed.
1564           AddToWorklist(Op.getNode());
1565           Changed = true;
1566           break;
1567         }
1568         // Fall thru
1569
1570       default:
1571         // Only add if it isn't already in the list.
1572         if (SeenOps.insert(Op.getNode()).second)
1573           Ops.push_back(Op);
1574         else
1575           Changed = true;
1576         break;
1577       }
1578     }
1579   }
1580
1581   SDValue Result;
1582
1583   // If we've changed things around then replace token factor.
1584   if (Changed) {
1585     if (Ops.empty()) {
1586       // The entry token is the only possible outcome.
1587       Result = DAG.getEntryNode();
1588     } else {
1589       // New and improved token factor.
1590       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1591     }
1592
1593     // Add users to worklist if AA is enabled, since it may introduce
1594     // a lot of new chained token factors while removing memory deps.
1595     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1596       : DAG.getSubtarget().useAA();
1597     return CombineTo(N, Result, UseAA /*add to worklist*/);
1598   }
1599
1600   return Result;
1601 }
1602
1603 /// MERGE_VALUES can always be eliminated.
1604 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1605   WorklistRemover DeadNodes(*this);
1606   // Replacing results may cause a different MERGE_VALUES to suddenly
1607   // be CSE'd with N, and carry its uses with it. Iterate until no
1608   // uses remain, to ensure that the node can be safely deleted.
1609   // First add the users of this node to the work list so that they
1610   // can be tried again once they have new operands.
1611   AddUsersToWorklist(N);
1612   do {
1613     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1614       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1615   } while (!N->use_empty());
1616   deleteAndRecombine(N);
1617   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1618 }
1619
1620 static bool isNullConstant(SDValue V) {
1621   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1622   return Const != nullptr && Const->isNullValue();
1623 }
1624
1625 static bool isNullFPConstant(SDValue V) {
1626   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1627   return Const != nullptr && Const->isZero() && !Const->isNegative();
1628 }
1629
1630 static bool isAllOnesConstant(SDValue V) {
1631   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1632   return Const != nullptr && Const->isAllOnesValue();
1633 }
1634
1635 static bool isOneConstant(SDValue V) {
1636   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1637   return Const != nullptr && Const->isOne();
1638 }
1639
1640 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1641 /// ContantSDNode pointer else nullptr.
1642 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1643   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1644   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1645 }
1646
1647 SDValue DAGCombiner::visitADD(SDNode *N) {
1648   SDValue N0 = N->getOperand(0);
1649   SDValue N1 = N->getOperand(1);
1650   EVT VT = N0.getValueType();
1651
1652   // fold vector ops
1653   if (VT.isVector()) {
1654     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1655       return FoldedVOp;
1656
1657     // fold (add x, 0) -> x, vector edition
1658     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1659       return N0;
1660     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1661       return N1;
1662   }
1663
1664   // fold (add x, undef) -> undef
1665   if (N0.getOpcode() == ISD::UNDEF)
1666     return N0;
1667   if (N1.getOpcode() == ISD::UNDEF)
1668     return N1;
1669   // fold (add c1, c2) -> c1+c2
1670   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1671   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1672   if (N0C && N1C)
1673     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1674   // canonicalize constant to RHS
1675   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1676      !isConstantIntBuildVectorOrConstantInt(N1))
1677     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1678   // fold (add x, 0) -> x
1679   if (isNullConstant(N1))
1680     return N0;
1681   // fold (add Sym, c) -> Sym+c
1682   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1683     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1684         GA->getOpcode() == ISD::GlobalAddress)
1685       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1686                                   GA->getOffset() +
1687                                     (uint64_t)N1C->getSExtValue());
1688   // fold ((c1-A)+c2) -> (c1+c2)-A
1689   if (N1C && N0.getOpcode() == ISD::SUB)
1690     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1691       SDLoc DL(N);
1692       return DAG.getNode(ISD::SUB, DL, VT,
1693                          DAG.getConstant(N1C->getAPIntValue()+
1694                                          N0C->getAPIntValue(), DL, VT),
1695                          N0.getOperand(1));
1696     }
1697   // reassociate add
1698   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1699     return RADD;
1700   // fold ((0-A) + B) -> B-A
1701   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1702     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1703   // fold (A + (0-B)) -> A-B
1704   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1705     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1706   // fold (A+(B-A)) -> B
1707   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1708     return N1.getOperand(0);
1709   // fold ((B-A)+A) -> B
1710   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1711     return N0.getOperand(0);
1712   // fold (A+(B-(A+C))) to (B-C)
1713   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1714       N0 == N1.getOperand(1).getOperand(0))
1715     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1716                        N1.getOperand(1).getOperand(1));
1717   // fold (A+(B-(C+A))) to (B-C)
1718   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1719       N0 == N1.getOperand(1).getOperand(1))
1720     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1721                        N1.getOperand(1).getOperand(0));
1722   // fold (A+((B-A)+or-C)) to (B+or-C)
1723   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1724       N1.getOperand(0).getOpcode() == ISD::SUB &&
1725       N0 == N1.getOperand(0).getOperand(1))
1726     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1727                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1728
1729   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1730   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1731     SDValue N00 = N0.getOperand(0);
1732     SDValue N01 = N0.getOperand(1);
1733     SDValue N10 = N1.getOperand(0);
1734     SDValue N11 = N1.getOperand(1);
1735
1736     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1737       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1738                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1739                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1740   }
1741
1742   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1743     return SDValue(N, 0);
1744
1745   // fold (a+b) -> (a|b) iff a and b share no bits.
1746   if (VT.isInteger() && !VT.isVector()) {
1747     APInt LHSZero, LHSOne;
1748     APInt RHSZero, RHSOne;
1749     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1750
1751     if (LHSZero.getBoolValue()) {
1752       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1753
1754       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1755       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1756       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1757         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1758           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1759       }
1760     }
1761   }
1762
1763   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1764   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1765       isNullConstant(N1.getOperand(0).getOperand(0)))
1766     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1767                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1768                                    N1.getOperand(0).getOperand(1),
1769                                    N1.getOperand(1)));
1770   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1771       isNullConstant(N0.getOperand(0).getOperand(0)))
1772     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1773                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1774                                    N0.getOperand(0).getOperand(1),
1775                                    N0.getOperand(1)));
1776
1777   if (N1.getOpcode() == ISD::AND) {
1778     SDValue AndOp0 = N1.getOperand(0);
1779     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1780     unsigned DestBits = VT.getScalarType().getSizeInBits();
1781
1782     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1783     // and similar xforms where the inner op is either ~0 or 0.
1784     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1785       SDLoc DL(N);
1786       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1787     }
1788   }
1789
1790   // add (sext i1), X -> sub X, (zext i1)
1791   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1792       N0.getOperand(0).getValueType() == MVT::i1 &&
1793       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1794     SDLoc DL(N);
1795     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1796     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1797   }
1798
1799   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1800   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1801     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1802     if (TN->getVT() == MVT::i1) {
1803       SDLoc DL(N);
1804       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1805                                  DAG.getConstant(1, DL, VT));
1806       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1807     }
1808   }
1809
1810   return SDValue();
1811 }
1812
1813 SDValue DAGCombiner::visitADDC(SDNode *N) {
1814   SDValue N0 = N->getOperand(0);
1815   SDValue N1 = N->getOperand(1);
1816   EVT VT = N0.getValueType();
1817
1818   // If the flag result is dead, turn this into an ADD.
1819   if (!N->hasAnyUseOfValue(1))
1820     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1821                      DAG.getNode(ISD::CARRY_FALSE,
1822                                  SDLoc(N), MVT::Glue));
1823
1824   // canonicalize constant to RHS.
1825   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1826   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1827   if (N0C && !N1C)
1828     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1829
1830   // fold (addc x, 0) -> x + no carry out
1831   if (isNullConstant(N1))
1832     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1833                                         SDLoc(N), MVT::Glue));
1834
1835   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1836   APInt LHSZero, LHSOne;
1837   APInt RHSZero, RHSOne;
1838   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1839
1840   if (LHSZero.getBoolValue()) {
1841     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1842
1843     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1844     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1845     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1846       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1847                        DAG.getNode(ISD::CARRY_FALSE,
1848                                    SDLoc(N), MVT::Glue));
1849   }
1850
1851   return SDValue();
1852 }
1853
1854 SDValue DAGCombiner::visitADDE(SDNode *N) {
1855   SDValue N0 = N->getOperand(0);
1856   SDValue N1 = N->getOperand(1);
1857   SDValue CarryIn = N->getOperand(2);
1858
1859   // canonicalize constant to RHS
1860   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1861   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1862   if (N0C && !N1C)
1863     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1864                        N1, N0, CarryIn);
1865
1866   // fold (adde x, y, false) -> (addc x, y)
1867   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1868     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1869
1870   return SDValue();
1871 }
1872
1873 // Since it may not be valid to emit a fold to zero for vector initializers
1874 // check if we can before folding.
1875 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1876                              SelectionDAG &DAG,
1877                              bool LegalOperations, bool LegalTypes) {
1878   if (!VT.isVector())
1879     return DAG.getConstant(0, DL, VT);
1880   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1881     return DAG.getConstant(0, DL, VT);
1882   return SDValue();
1883 }
1884
1885 SDValue DAGCombiner::visitSUB(SDNode *N) {
1886   SDValue N0 = N->getOperand(0);
1887   SDValue N1 = N->getOperand(1);
1888   EVT VT = N0.getValueType();
1889
1890   // fold vector ops
1891   if (VT.isVector()) {
1892     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1893       return FoldedVOp;
1894
1895     // fold (sub x, 0) -> x, vector edition
1896     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1897       return N0;
1898   }
1899
1900   // fold (sub x, x) -> 0
1901   // FIXME: Refactor this and xor and other similar operations together.
1902   if (N0 == N1)
1903     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1904   // fold (sub c1, c2) -> c1-c2
1905   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1906   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1907   if (N0C && N1C)
1908     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1909   // fold (sub x, c) -> (add x, -c)
1910   if (N1C) {
1911     SDLoc DL(N);
1912     return DAG.getNode(ISD::ADD, DL, VT, N0,
1913                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1914   }
1915   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1916   if (isAllOnesConstant(N0))
1917     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1918   // fold A-(A-B) -> B
1919   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1920     return N1.getOperand(1);
1921   // fold (A+B)-A -> B
1922   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1923     return N0.getOperand(1);
1924   // fold (A+B)-B -> A
1925   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1926     return N0.getOperand(0);
1927   // fold C2-(A+C1) -> (C2-C1)-A
1928   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1929     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1930   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1931     SDLoc DL(N);
1932     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1933                                    DL, VT);
1934     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1935                        N1.getOperand(0));
1936   }
1937   // fold ((A+(B+or-C))-B) -> A+or-C
1938   if (N0.getOpcode() == ISD::ADD &&
1939       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1940        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1941       N0.getOperand(1).getOperand(0) == N1)
1942     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1943                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1944   // fold ((A+(C+B))-B) -> A+C
1945   if (N0.getOpcode() == ISD::ADD &&
1946       N0.getOperand(1).getOpcode() == ISD::ADD &&
1947       N0.getOperand(1).getOperand(1) == N1)
1948     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1950   // fold ((A-(B-C))-C) -> A-B
1951   if (N0.getOpcode() == ISD::SUB &&
1952       N0.getOperand(1).getOpcode() == ISD::SUB &&
1953       N0.getOperand(1).getOperand(1) == N1)
1954     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1955                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1956
1957   // If either operand of a sub is undef, the result is undef
1958   if (N0.getOpcode() == ISD::UNDEF)
1959     return N0;
1960   if (N1.getOpcode() == ISD::UNDEF)
1961     return N1;
1962
1963   // If the relocation model supports it, consider symbol offsets.
1964   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1965     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1966       // fold (sub Sym, c) -> Sym-c
1967       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1968         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1969                                     GA->getOffset() -
1970                                       (uint64_t)N1C->getSExtValue());
1971       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1972       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1973         if (GA->getGlobal() == GB->getGlobal())
1974           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1975                                  SDLoc(N), VT);
1976     }
1977
1978   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1979   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1980     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1981     if (TN->getVT() == MVT::i1) {
1982       SDLoc DL(N);
1983       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1984                                  DAG.getConstant(1, DL, VT));
1985       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1986     }
1987   }
1988
1989   return SDValue();
1990 }
1991
1992 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1993   SDValue N0 = N->getOperand(0);
1994   SDValue N1 = N->getOperand(1);
1995   EVT VT = N0.getValueType();
1996   SDLoc DL(N);
1997
1998   // If the flag result is dead, turn this into an SUB.
1999   if (!N->hasAnyUseOfValue(1))
2000     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
2001                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2002
2003   // fold (subc x, x) -> 0 + no borrow
2004   if (N0 == N1)
2005     return CombineTo(N, DAG.getConstant(0, DL, VT),
2006                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2007
2008   // fold (subc x, 0) -> x + no borrow
2009   if (isNullConstant(N1))
2010     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2011
2012   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2013   if (isAllOnesConstant(N0))
2014     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2015                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2016
2017   return SDValue();
2018 }
2019
2020 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2021   SDValue N0 = N->getOperand(0);
2022   SDValue N1 = N->getOperand(1);
2023   SDValue CarryIn = N->getOperand(2);
2024
2025   // fold (sube x, y, false) -> (subc x, y)
2026   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2027     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2028
2029   return SDValue();
2030 }
2031
2032 SDValue DAGCombiner::visitMUL(SDNode *N) {
2033   SDValue N0 = N->getOperand(0);
2034   SDValue N1 = N->getOperand(1);
2035   EVT VT = N0.getValueType();
2036
2037   // fold (mul x, undef) -> 0
2038   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2039     return DAG.getConstant(0, SDLoc(N), VT);
2040
2041   bool N0IsConst = false;
2042   bool N1IsConst = false;
2043   bool N1IsOpaqueConst = false;
2044   bool N0IsOpaqueConst = false;
2045   APInt ConstValue0, ConstValue1;
2046   // fold vector ops
2047   if (VT.isVector()) {
2048     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2049       return FoldedVOp;
2050
2051     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2052     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2053   } else {
2054     N0IsConst = isa<ConstantSDNode>(N0);
2055     if (N0IsConst) {
2056       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2057       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2058     }
2059     N1IsConst = isa<ConstantSDNode>(N1);
2060     if (N1IsConst) {
2061       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2062       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2063     }
2064   }
2065
2066   // fold (mul c1, c2) -> c1*c2
2067   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2068     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2069                                       N0.getNode(), N1.getNode());
2070
2071   // canonicalize constant to RHS (vector doesn't have to splat)
2072   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2073      !isConstantIntBuildVectorOrConstantInt(N1))
2074     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2075   // fold (mul x, 0) -> 0
2076   if (N1IsConst && ConstValue1 == 0)
2077     return N1;
2078   // We require a splat of the entire scalar bit width for non-contiguous
2079   // bit patterns.
2080   bool IsFullSplat =
2081     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2082   // fold (mul x, 1) -> x
2083   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2084     return N0;
2085   // fold (mul x, -1) -> 0-x
2086   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2087     SDLoc DL(N);
2088     return DAG.getNode(ISD::SUB, DL, VT,
2089                        DAG.getConstant(0, DL, VT), N0);
2090   }
2091   // fold (mul x, (1 << c)) -> x << c
2092   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2093       IsFullSplat) {
2094     SDLoc DL(N);
2095     return DAG.getNode(ISD::SHL, DL, VT, N0,
2096                        DAG.getConstant(ConstValue1.logBase2(), DL,
2097                                        getShiftAmountTy(N0.getValueType())));
2098   }
2099   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2100   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2101       IsFullSplat) {
2102     unsigned Log2Val = (-ConstValue1).logBase2();
2103     SDLoc DL(N);
2104     // FIXME: If the input is something that is easily negated (e.g. a
2105     // single-use add), we should put the negate there.
2106     return DAG.getNode(ISD::SUB, DL, VT,
2107                        DAG.getConstant(0, DL, VT),
2108                        DAG.getNode(ISD::SHL, DL, VT, N0,
2109                             DAG.getConstant(Log2Val, DL,
2110                                       getShiftAmountTy(N0.getValueType()))));
2111   }
2112
2113   APInt Val;
2114   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2115   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2116       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2117                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2118     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2119                              N1, N0.getOperand(1));
2120     AddToWorklist(C3.getNode());
2121     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2122                        N0.getOperand(0), C3);
2123   }
2124
2125   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2126   // use.
2127   {
2128     SDValue Sh(nullptr,0), Y(nullptr,0);
2129     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2130     if (N0.getOpcode() == ISD::SHL &&
2131         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2132                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2133         N0.getNode()->hasOneUse()) {
2134       Sh = N0; Y = N1;
2135     } else if (N1.getOpcode() == ISD::SHL &&
2136                isa<ConstantSDNode>(N1.getOperand(1)) &&
2137                N1.getNode()->hasOneUse()) {
2138       Sh = N1; Y = N0;
2139     }
2140
2141     if (Sh.getNode()) {
2142       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2143                                 Sh.getOperand(0), Y);
2144       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2145                          Mul, Sh.getOperand(1));
2146     }
2147   }
2148
2149   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2150   if (isConstantIntBuildVectorOrConstantInt(N1) &&
2151       N0.getOpcode() == ISD::ADD &&
2152       isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
2153       isMulAddWithConstProfitable(N, N0, N1))
2154       return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2155                          DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2156                                      N0.getOperand(0), N1),
2157                          DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2158                                      N0.getOperand(1), N1));
2159
2160   // reassociate mul
2161   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2162     return RMUL;
2163
2164   return SDValue();
2165 }
2166
2167 /// Return true if divmod libcall is available.
2168 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2169                                      const TargetLowering &TLI) {
2170   RTLIB::Libcall LC;
2171   switch (Node->getSimpleValueType(0).SimpleTy) {
2172   default: return false; // No libcall for vector types.
2173   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2174   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2175   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2176   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2177   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2178   }
2179
2180   return TLI.getLibcallName(LC) != nullptr;
2181 }
2182
2183 /// Issue divrem if both quotient and remainder are needed.
2184 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2185   if (Node->use_empty())
2186     return SDValue(); // This is a dead node, leave it alone.
2187
2188   EVT VT = Node->getValueType(0);
2189   if (!TLI.isTypeLegal(VT))
2190     return SDValue();
2191
2192   unsigned Opcode = Node->getOpcode();
2193   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2194
2195   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2196   // If DIVREM is going to get expanded into a libcall,
2197   // but there is no libcall available, then don't combine.
2198   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2199       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2200     return SDValue();
2201
2202   // If div is legal, it's better to do the normal expansion
2203   unsigned OtherOpcode = 0;
2204   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2205     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2206     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2207       return SDValue();
2208   } else {
2209     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2210     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2211       return SDValue();
2212   }
2213
2214   SDValue Op0 = Node->getOperand(0);
2215   SDValue Op1 = Node->getOperand(1);
2216   SDValue combined;
2217   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2218          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2219     SDNode *User = *UI;
2220     if (User == Node || User->use_empty())
2221       continue;
2222     // Convert the other matching node(s), too;
2223     // otherwise, the DIVREM may get target-legalized into something
2224     // target-specific that we won't be able to recognize.
2225     unsigned UserOpc = User->getOpcode();
2226     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2227         User->getOperand(0) == Op0 &&
2228         User->getOperand(1) == Op1) {
2229       if (!combined) {
2230         if (UserOpc == OtherOpcode) {
2231           SDVTList VTs = DAG.getVTList(VT, VT);
2232           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2233         } else if (UserOpc == DivRemOpc) {
2234           combined = SDValue(User, 0);
2235         } else {
2236           assert(UserOpc == Opcode);
2237           continue;
2238         }
2239       }
2240       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2241         CombineTo(User, combined);
2242       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2243         CombineTo(User, combined.getValue(1));
2244     }
2245   }
2246   return combined;
2247 }
2248
2249 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2250   SDValue N0 = N->getOperand(0);
2251   SDValue N1 = N->getOperand(1);
2252   EVT VT = N->getValueType(0);
2253
2254   // fold vector ops
2255   if (VT.isVector())
2256     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2257       return FoldedVOp;
2258
2259   SDLoc DL(N);
2260
2261   // fold (sdiv c1, c2) -> c1/c2
2262   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2263   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2264   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2265     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2266   // fold (sdiv X, 1) -> X
2267   if (N1C && N1C->isOne())
2268     return N0;
2269   // fold (sdiv X, -1) -> 0-X
2270   if (N1C && N1C->isAllOnesValue())
2271     return DAG.getNode(ISD::SUB, DL, VT,
2272                        DAG.getConstant(0, DL, VT), N0);
2273
2274   // If we know the sign bits of both operands are zero, strength reduce to a
2275   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2276   if (!VT.isVector()) {
2277     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2278       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2279   }
2280
2281   // fold (sdiv X, pow2) -> simple ops after legalize
2282   // FIXME: We check for the exact bit here because the generic lowering gives
2283   // better results in that case. The target-specific lowering should learn how
2284   // to handle exact sdivs efficiently.
2285   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2286       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2287       (N1C->getAPIntValue().isPowerOf2() ||
2288        (-N1C->getAPIntValue()).isPowerOf2())) {
2289     // Target-specific implementation of sdiv x, pow2.
2290     if (SDValue Res = BuildSDIVPow2(N))
2291       return Res;
2292
2293     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2294
2295     // Splat the sign bit into the register
2296     SDValue SGN =
2297         DAG.getNode(ISD::SRA, DL, VT, N0,
2298                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2299                                     getShiftAmountTy(N0.getValueType())));
2300     AddToWorklist(SGN.getNode());
2301
2302     // Add (N0 < 0) ? abs2 - 1 : 0;
2303     SDValue SRL =
2304         DAG.getNode(ISD::SRL, DL, VT, SGN,
2305                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2306                                     getShiftAmountTy(SGN.getValueType())));
2307     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2308     AddToWorklist(SRL.getNode());
2309     AddToWorklist(ADD.getNode());    // Divide by pow2
2310     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2311                   DAG.getConstant(lg2, DL,
2312                                   getShiftAmountTy(ADD.getValueType())));
2313
2314     // If we're dividing by a positive value, we're done.  Otherwise, we must
2315     // negate the result.
2316     if (N1C->getAPIntValue().isNonNegative())
2317       return SRA;
2318
2319     AddToWorklist(SRA.getNode());
2320     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2321   }
2322
2323   // If integer divide is expensive and we satisfy the requirements, emit an
2324   // alternate sequence.  Targets may check function attributes for size/speed
2325   // trade-offs.
2326   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2327   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2328     if (SDValue Op = BuildSDIV(N))
2329       return Op;
2330
2331   // sdiv, srem -> sdivrem
2332   if (SDValue DivRem = useDivRem(N))
2333     return DivRem;
2334
2335   // undef / X -> 0
2336   if (N0.getOpcode() == ISD::UNDEF)
2337     return DAG.getConstant(0, DL, VT);
2338   // X / undef -> undef
2339   if (N1.getOpcode() == ISD::UNDEF)
2340     return N1;
2341
2342   return SDValue();
2343 }
2344
2345 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2346   SDValue N0 = N->getOperand(0);
2347   SDValue N1 = N->getOperand(1);
2348   EVT VT = N->getValueType(0);
2349
2350   // fold vector ops
2351   if (VT.isVector())
2352     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2353       return FoldedVOp;
2354
2355   SDLoc DL(N);
2356
2357   // fold (udiv c1, c2) -> c1/c2
2358   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2359   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2360   if (N0C && N1C)
2361     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2362                                                     N0C, N1C))
2363       return Folded;
2364   // fold (udiv x, (1 << c)) -> x >>u c
2365   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2366     return DAG.getNode(ISD::SRL, DL, VT, N0,
2367                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2368                                        getShiftAmountTy(N0.getValueType())));
2369
2370   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2371   if (N1.getOpcode() == ISD::SHL) {
2372     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2373       if (SHC->getAPIntValue().isPowerOf2()) {
2374         EVT ADDVT = N1.getOperand(1).getValueType();
2375         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2376                                   N1.getOperand(1),
2377                                   DAG.getConstant(SHC->getAPIntValue()
2378                                                                   .logBase2(),
2379                                                   DL, ADDVT));
2380         AddToWorklist(Add.getNode());
2381         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2382       }
2383     }
2384   }
2385
2386   // fold (udiv x, c) -> alternate
2387   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2388   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2389     if (SDValue Op = BuildUDIV(N))
2390       return Op;
2391
2392   // sdiv, srem -> sdivrem
2393   if (SDValue DivRem = useDivRem(N))
2394     return DivRem;
2395
2396   // undef / X -> 0
2397   if (N0.getOpcode() == ISD::UNDEF)
2398     return DAG.getConstant(0, DL, VT);
2399   // X / undef -> undef
2400   if (N1.getOpcode() == ISD::UNDEF)
2401     return N1;
2402
2403   return SDValue();
2404 }
2405
2406 // handles ISD::SREM and ISD::UREM
2407 SDValue DAGCombiner::visitREM(SDNode *N) {
2408   unsigned Opcode = N->getOpcode();
2409   SDValue N0 = N->getOperand(0);
2410   SDValue N1 = N->getOperand(1);
2411   EVT VT = N->getValueType(0);
2412   bool isSigned = (Opcode == ISD::SREM);
2413   SDLoc DL(N);
2414
2415   // fold (rem c1, c2) -> c1%c2
2416   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2417   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2418   if (N0C && N1C)
2419     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2420       return Folded;
2421
2422   if (isSigned) {
2423     // If we know the sign bits of both operands are zero, strength reduce to a
2424     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2425     if (!VT.isVector()) {
2426       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2427         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2428     }
2429   } else {
2430     // fold (urem x, pow2) -> (and x, pow2-1)
2431     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2432         N1C->getAPIntValue().isPowerOf2()) {
2433       return DAG.getNode(ISD::AND, DL, VT, N0,
2434                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2435     }
2436     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2437     if (N1.getOpcode() == ISD::SHL) {
2438       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2439         if (SHC->getAPIntValue().isPowerOf2()) {
2440           SDValue Add =
2441             DAG.getNode(ISD::ADD, DL, VT, N1,
2442                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2443                                  VT));
2444           AddToWorklist(Add.getNode());
2445           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2446         }
2447       }
2448     }
2449   }
2450
2451   // If X/C can be simplified by the division-by-constant logic, lower
2452   // X%C to the equivalent of X-X/C*C.
2453   if (N1C && !N1C->isNullValue()) {
2454     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2455     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2456     AddToWorklist(Div.getNode());
2457     SDValue OptimizedDiv = combine(Div.getNode());
2458     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2459       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2460       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2461       AddToWorklist(Mul.getNode());
2462       return Sub;
2463     }
2464   }
2465
2466   // sdiv, srem -> sdivrem
2467   if (SDValue DivRem = useDivRem(N))
2468     return DivRem.getValue(1);
2469
2470   // undef % X -> 0
2471   if (N0.getOpcode() == ISD::UNDEF)
2472     return DAG.getConstant(0, DL, VT);
2473   // X % undef -> undef
2474   if (N1.getOpcode() == ISD::UNDEF)
2475     return N1;
2476
2477   return SDValue();
2478 }
2479
2480 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2481   SDValue N0 = N->getOperand(0);
2482   SDValue N1 = N->getOperand(1);
2483   EVT VT = N->getValueType(0);
2484   SDLoc DL(N);
2485
2486   // fold (mulhs x, 0) -> 0
2487   if (isNullConstant(N1))
2488     return N1;
2489   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2490   if (isOneConstant(N1)) {
2491     SDLoc DL(N);
2492     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2493                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2494                                        DL,
2495                                        getShiftAmountTy(N0.getValueType())));
2496   }
2497   // fold (mulhs x, undef) -> 0
2498   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2499     return DAG.getConstant(0, SDLoc(N), VT);
2500
2501   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2502   // plus a shift.
2503   if (VT.isSimple() && !VT.isVector()) {
2504     MVT Simple = VT.getSimpleVT();
2505     unsigned SimpleSize = Simple.getSizeInBits();
2506     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2507     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2508       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2509       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2510       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2511       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2512             DAG.getConstant(SimpleSize, DL,
2513                             getShiftAmountTy(N1.getValueType())));
2514       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2515     }
2516   }
2517
2518   return SDValue();
2519 }
2520
2521 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2522   SDValue N0 = N->getOperand(0);
2523   SDValue N1 = N->getOperand(1);
2524   EVT VT = N->getValueType(0);
2525   SDLoc DL(N);
2526
2527   // fold (mulhu x, 0) -> 0
2528   if (isNullConstant(N1))
2529     return N1;
2530   // fold (mulhu x, 1) -> 0
2531   if (isOneConstant(N1))
2532     return DAG.getConstant(0, DL, N0.getValueType());
2533   // fold (mulhu x, undef) -> 0
2534   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2535     return DAG.getConstant(0, DL, VT);
2536
2537   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2538   // plus a shift.
2539   if (VT.isSimple() && !VT.isVector()) {
2540     MVT Simple = VT.getSimpleVT();
2541     unsigned SimpleSize = Simple.getSizeInBits();
2542     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2543     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2544       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2545       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2546       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2547       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2548             DAG.getConstant(SimpleSize, DL,
2549                             getShiftAmountTy(N1.getValueType())));
2550       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2551     }
2552   }
2553
2554   return SDValue();
2555 }
2556
2557 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2558 /// give the opcodes for the two computations that are being performed. Return
2559 /// true if a simplification was made.
2560 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2561                                                 unsigned HiOp) {
2562   // If the high half is not needed, just compute the low half.
2563   bool HiExists = N->hasAnyUseOfValue(1);
2564   if (!HiExists &&
2565       (!LegalOperations ||
2566        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2567     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2568     return CombineTo(N, Res, Res);
2569   }
2570
2571   // If the low half is not needed, just compute the high half.
2572   bool LoExists = N->hasAnyUseOfValue(0);
2573   if (!LoExists &&
2574       (!LegalOperations ||
2575        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2576     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2577     return CombineTo(N, Res, Res);
2578   }
2579
2580   // If both halves are used, return as it is.
2581   if (LoExists && HiExists)
2582     return SDValue();
2583
2584   // If the two computed results can be simplified separately, separate them.
2585   if (LoExists) {
2586     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2587     AddToWorklist(Lo.getNode());
2588     SDValue LoOpt = combine(Lo.getNode());
2589     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2590         (!LegalOperations ||
2591          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2592       return CombineTo(N, LoOpt, LoOpt);
2593   }
2594
2595   if (HiExists) {
2596     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2597     AddToWorklist(Hi.getNode());
2598     SDValue HiOpt = combine(Hi.getNode());
2599     if (HiOpt.getNode() && HiOpt != Hi &&
2600         (!LegalOperations ||
2601          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2602       return CombineTo(N, HiOpt, HiOpt);
2603   }
2604
2605   return SDValue();
2606 }
2607
2608 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2609   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2610     return Res;
2611
2612   EVT VT = N->getValueType(0);
2613   SDLoc DL(N);
2614
2615   // If the type is twice as wide is legal, transform the mulhu to a wider
2616   // multiply plus a shift.
2617   if (VT.isSimple() && !VT.isVector()) {
2618     MVT Simple = VT.getSimpleVT();
2619     unsigned SimpleSize = Simple.getSizeInBits();
2620     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2621     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2622       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2623       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2624       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2625       // Compute the high part as N1.
2626       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2627             DAG.getConstant(SimpleSize, DL,
2628                             getShiftAmountTy(Lo.getValueType())));
2629       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2630       // Compute the low part as N0.
2631       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2632       return CombineTo(N, Lo, Hi);
2633     }
2634   }
2635
2636   return SDValue();
2637 }
2638
2639 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2640   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2641     return Res;
2642
2643   EVT VT = N->getValueType(0);
2644   SDLoc DL(N);
2645
2646   // If the type is twice as wide is legal, transform the mulhu to a wider
2647   // multiply plus a shift.
2648   if (VT.isSimple() && !VT.isVector()) {
2649     MVT Simple = VT.getSimpleVT();
2650     unsigned SimpleSize = Simple.getSizeInBits();
2651     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2652     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2653       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2654       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2655       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2656       // Compute the high part as N1.
2657       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2658             DAG.getConstant(SimpleSize, DL,
2659                             getShiftAmountTy(Lo.getValueType())));
2660       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2661       // Compute the low part as N0.
2662       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2663       return CombineTo(N, Lo, Hi);
2664     }
2665   }
2666
2667   return SDValue();
2668 }
2669
2670 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2671   // (smulo x, 2) -> (saddo x, x)
2672   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2673     if (C2->getAPIntValue() == 2)
2674       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2675                          N->getOperand(0), N->getOperand(0));
2676
2677   return SDValue();
2678 }
2679
2680 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2681   // (umulo x, 2) -> (uaddo x, x)
2682   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2683     if (C2->getAPIntValue() == 2)
2684       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2685                          N->getOperand(0), N->getOperand(0));
2686
2687   return SDValue();
2688 }
2689
2690 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2691   SDValue N0 = N->getOperand(0);
2692   SDValue N1 = N->getOperand(1);
2693   EVT VT = N0.getValueType();
2694
2695   // fold vector ops
2696   if (VT.isVector())
2697     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2698       return FoldedVOp;
2699
2700   // fold (add c1, c2) -> c1+c2
2701   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2702   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2703   if (N0C && N1C)
2704     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2705
2706   // canonicalize constant to RHS
2707   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2708      !isConstantIntBuildVectorOrConstantInt(N1))
2709     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2710
2711   return SDValue();
2712 }
2713
2714 /// If this is a binary operator with two operands of the same opcode, try to
2715 /// simplify it.
2716 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2717   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2718   EVT VT = N0.getValueType();
2719   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2720
2721   // Bail early if none of these transforms apply.
2722   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2723
2724   // For each of OP in AND/OR/XOR:
2725   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2726   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2727   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2728   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2729   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2730   //
2731   // do not sink logical op inside of a vector extend, since it may combine
2732   // into a vsetcc.
2733   EVT Op0VT = N0.getOperand(0).getValueType();
2734   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2735        N0.getOpcode() == ISD::SIGN_EXTEND ||
2736        N0.getOpcode() == ISD::BSWAP ||
2737        // Avoid infinite looping with PromoteIntBinOp.
2738        (N0.getOpcode() == ISD::ANY_EXTEND &&
2739         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2740        (N0.getOpcode() == ISD::TRUNCATE &&
2741         (!TLI.isZExtFree(VT, Op0VT) ||
2742          !TLI.isTruncateFree(Op0VT, VT)) &&
2743         TLI.isTypeLegal(Op0VT))) &&
2744       !VT.isVector() &&
2745       Op0VT == N1.getOperand(0).getValueType() &&
2746       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2747     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2748                                  N0.getOperand(0).getValueType(),
2749                                  N0.getOperand(0), N1.getOperand(0));
2750     AddToWorklist(ORNode.getNode());
2751     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2752   }
2753
2754   // For each of OP in SHL/SRL/SRA/AND...
2755   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2756   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2757   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2758   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2759        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2760       N0.getOperand(1) == N1.getOperand(1)) {
2761     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2762                                  N0.getOperand(0).getValueType(),
2763                                  N0.getOperand(0), N1.getOperand(0));
2764     AddToWorklist(ORNode.getNode());
2765     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2766                        ORNode, N0.getOperand(1));
2767   }
2768
2769   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2770   // Only perform this optimization after type legalization and before
2771   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2772   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2773   // we don't want to undo this promotion.
2774   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2775   // on scalars.
2776   if ((N0.getOpcode() == ISD::BITCAST ||
2777        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2778       Level == AfterLegalizeTypes) {
2779     SDValue In0 = N0.getOperand(0);
2780     SDValue In1 = N1.getOperand(0);
2781     EVT In0Ty = In0.getValueType();
2782     EVT In1Ty = In1.getValueType();
2783     SDLoc DL(N);
2784     // If both incoming values are integers, and the original types are the
2785     // same.
2786     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2787       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2788       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2789       AddToWorklist(Op.getNode());
2790       return BC;
2791     }
2792   }
2793
2794   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2795   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2796   // If both shuffles use the same mask, and both shuffle within a single
2797   // vector, then it is worthwhile to move the swizzle after the operation.
2798   // The type-legalizer generates this pattern when loading illegal
2799   // vector types from memory. In many cases this allows additional shuffle
2800   // optimizations.
2801   // There are other cases where moving the shuffle after the xor/and/or
2802   // is profitable even if shuffles don't perform a swizzle.
2803   // If both shuffles use the same mask, and both shuffles have the same first
2804   // or second operand, then it might still be profitable to move the shuffle
2805   // after the xor/and/or operation.
2806   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2807     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2808     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2809
2810     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2811            "Inputs to shuffles are not the same type");
2812
2813     // Check that both shuffles use the same mask. The masks are known to be of
2814     // the same length because the result vector type is the same.
2815     // Check also that shuffles have only one use to avoid introducing extra
2816     // instructions.
2817     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2818         SVN0->getMask().equals(SVN1->getMask())) {
2819       SDValue ShOp = N0->getOperand(1);
2820
2821       // Don't try to fold this node if it requires introducing a
2822       // build vector of all zeros that might be illegal at this stage.
2823       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2824         if (!LegalTypes)
2825           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2826         else
2827           ShOp = SDValue();
2828       }
2829
2830       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2831       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2832       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2833       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2834         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2835                                       N0->getOperand(0), N1->getOperand(0));
2836         AddToWorklist(NewNode.getNode());
2837         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2838                                     &SVN0->getMask()[0]);
2839       }
2840
2841       // Don't try to fold this node if it requires introducing a
2842       // build vector of all zeros that might be illegal at this stage.
2843       ShOp = N0->getOperand(0);
2844       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2845         if (!LegalTypes)
2846           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2847         else
2848           ShOp = SDValue();
2849       }
2850
2851       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2852       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2853       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2854       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2855         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2856                                       N0->getOperand(1), N1->getOperand(1));
2857         AddToWorklist(NewNode.getNode());
2858         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2859                                     &SVN0->getMask()[0]);
2860       }
2861     }
2862   }
2863
2864   return SDValue();
2865 }
2866
2867 /// This contains all DAGCombine rules which reduce two values combined by
2868 /// an And operation to a single value. This makes them reusable in the context
2869 /// of visitSELECT(). Rules involving constants are not included as
2870 /// visitSELECT() already handles those cases.
2871 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2872                                   SDNode *LocReference) {
2873   EVT VT = N1.getValueType();
2874
2875   // fold (and x, undef) -> 0
2876   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2877     return DAG.getConstant(0, SDLoc(LocReference), VT);
2878   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2879   SDValue LL, LR, RL, RR, CC0, CC1;
2880   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2881     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2882     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2883
2884     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2885         LL.getValueType().isInteger()) {
2886       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2887       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2888         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2889                                      LR.getValueType(), LL, RL);
2890         AddToWorklist(ORNode.getNode());
2891         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2892       }
2893       if (isAllOnesConstant(LR)) {
2894         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2895         if (Op1 == ISD::SETEQ) {
2896           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2897                                         LR.getValueType(), LL, RL);
2898           AddToWorklist(ANDNode.getNode());
2899           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2900         }
2901         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2902         if (Op1 == ISD::SETGT) {
2903           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2904                                        LR.getValueType(), LL, RL);
2905           AddToWorklist(ORNode.getNode());
2906           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2907         }
2908       }
2909     }
2910     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2911     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2912         Op0 == Op1 && LL.getValueType().isInteger() &&
2913       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2914                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2915       SDLoc DL(N0);
2916       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2917                                     LL, DAG.getConstant(1, DL,
2918                                                         LL.getValueType()));
2919       AddToWorklist(ADDNode.getNode());
2920       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2921                           DAG.getConstant(2, DL, LL.getValueType()),
2922                           ISD::SETUGE);
2923     }
2924     // canonicalize equivalent to ll == rl
2925     if (LL == RR && LR == RL) {
2926       Op1 = ISD::getSetCCSwappedOperands(Op1);
2927       std::swap(RL, RR);
2928     }
2929     if (LL == RL && LR == RR) {
2930       bool isInteger = LL.getValueType().isInteger();
2931       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2932       if (Result != ISD::SETCC_INVALID &&
2933           (!LegalOperations ||
2934            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2935             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2936         EVT CCVT = getSetCCResultType(LL.getValueType());
2937         if (N0.getValueType() == CCVT ||
2938             (!LegalOperations && N0.getValueType() == MVT::i1))
2939           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2940                               LL, LR, Result);
2941       }
2942     }
2943   }
2944
2945   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2946       VT.getSizeInBits() <= 64) {
2947     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2948       APInt ADDC = ADDI->getAPIntValue();
2949       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2950         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2951         // immediate for an add, but it is legal if its top c2 bits are set,
2952         // transform the ADD so the immediate doesn't need to be materialized
2953         // in a register.
2954         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2955           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2956                                              SRLI->getZExtValue());
2957           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2958             ADDC |= Mask;
2959             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2960               SDLoc DL(N0);
2961               SDValue NewAdd =
2962                 DAG.getNode(ISD::ADD, DL, VT,
2963                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2964               CombineTo(N0.getNode(), NewAdd);
2965               // Return N so it doesn't get rechecked!
2966               return SDValue(LocReference, 0);
2967             }
2968           }
2969         }
2970       }
2971     }
2972   }
2973
2974   return SDValue();
2975 }
2976
2977 SDValue DAGCombiner::visitAND(SDNode *N) {
2978   SDValue N0 = N->getOperand(0);
2979   SDValue N1 = N->getOperand(1);
2980   EVT VT = N1.getValueType();
2981
2982   // fold vector ops
2983   if (VT.isVector()) {
2984     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2985       return FoldedVOp;
2986
2987     // fold (and x, 0) -> 0, vector edition
2988     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2989       // do not return N0, because undef node may exist in N0
2990       return DAG.getConstant(
2991           APInt::getNullValue(
2992               N0.getValueType().getScalarType().getSizeInBits()),
2993           SDLoc(N), N0.getValueType());
2994     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2995       // do not return N1, because undef node may exist in N1
2996       return DAG.getConstant(
2997           APInt::getNullValue(
2998               N1.getValueType().getScalarType().getSizeInBits()),
2999           SDLoc(N), N1.getValueType());
3000
3001     // fold (and x, -1) -> x, vector edition
3002     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3003       return N1;
3004     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3005       return N0;
3006   }
3007
3008   // fold (and c1, c2) -> c1&c2
3009   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3010   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3011   if (N0C && N1C && !N1C->isOpaque())
3012     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3013   // canonicalize constant to RHS
3014   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3015      !isConstantIntBuildVectorOrConstantInt(N1))
3016     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3017   // fold (and x, -1) -> x
3018   if (isAllOnesConstant(N1))
3019     return N0;
3020   // if (and x, c) is known to be zero, return 0
3021   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3022   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3023                                    APInt::getAllOnesValue(BitWidth)))
3024     return DAG.getConstant(0, SDLoc(N), VT);
3025   // reassociate and
3026   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3027     return RAND;
3028   // fold (and (or x, C), D) -> D if (C & D) == D
3029   if (N1C && N0.getOpcode() == ISD::OR)
3030     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3031       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3032         return N1;
3033   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3034   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3035     SDValue N0Op0 = N0.getOperand(0);
3036     APInt Mask = ~N1C->getAPIntValue();
3037     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3038     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3039       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3040                                  N0.getValueType(), N0Op0);
3041
3042       // Replace uses of the AND with uses of the Zero extend node.
3043       CombineTo(N, Zext);
3044
3045       // We actually want to replace all uses of the any_extend with the
3046       // zero_extend, to avoid duplicating things.  This will later cause this
3047       // AND to be folded.
3048       CombineTo(N0.getNode(), Zext);
3049       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3050     }
3051   }
3052   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3053   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3054   // already be zero by virtue of the width of the base type of the load.
3055   //
3056   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3057   // more cases.
3058   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3059        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3060       N0.getOpcode() == ISD::LOAD) {
3061     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3062                                          N0 : N0.getOperand(0) );
3063
3064     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3065     // This can be a pure constant or a vector splat, in which case we treat the
3066     // vector as a scalar and use the splat value.
3067     APInt Constant = APInt::getNullValue(1);
3068     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3069       Constant = C->getAPIntValue();
3070     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3071       APInt SplatValue, SplatUndef;
3072       unsigned SplatBitSize;
3073       bool HasAnyUndefs;
3074       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3075                                              SplatBitSize, HasAnyUndefs);
3076       if (IsSplat) {
3077         // Undef bits can contribute to a possible optimisation if set, so
3078         // set them.
3079         SplatValue |= SplatUndef;
3080
3081         // The splat value may be something like "0x00FFFFFF", which means 0 for
3082         // the first vector value and FF for the rest, repeating. We need a mask
3083         // that will apply equally to all members of the vector, so AND all the
3084         // lanes of the constant together.
3085         EVT VT = Vector->getValueType(0);
3086         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3087
3088         // If the splat value has been compressed to a bitlength lower
3089         // than the size of the vector lane, we need to re-expand it to
3090         // the lane size.
3091         if (BitWidth > SplatBitSize)
3092           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3093                SplatBitSize < BitWidth;
3094                SplatBitSize = SplatBitSize * 2)
3095             SplatValue |= SplatValue.shl(SplatBitSize);
3096
3097         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3098         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3099         if (SplatBitSize % BitWidth == 0) {
3100           Constant = APInt::getAllOnesValue(BitWidth);
3101           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3102             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3103         }
3104       }
3105     }
3106
3107     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3108     // actually legal and isn't going to get expanded, else this is a false
3109     // optimisation.
3110     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3111                                                     Load->getValueType(0),
3112                                                     Load->getMemoryVT());
3113
3114     // Resize the constant to the same size as the original memory access before
3115     // extension. If it is still the AllOnesValue then this AND is completely
3116     // unneeded.
3117     Constant =
3118       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3119
3120     bool B;
3121     switch (Load->getExtensionType()) {
3122     default: B = false; break;
3123     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3124     case ISD::ZEXTLOAD:
3125     case ISD::NON_EXTLOAD: B = true; break;
3126     }
3127
3128     if (B && Constant.isAllOnesValue()) {
3129       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3130       // preserve semantics once we get rid of the AND.
3131       SDValue NewLoad(Load, 0);
3132       if (Load->getExtensionType() == ISD::EXTLOAD) {
3133         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3134                               Load->getValueType(0), SDLoc(Load),
3135                               Load->getChain(), Load->getBasePtr(),
3136                               Load->getOffset(), Load->getMemoryVT(),
3137                               Load->getMemOperand());
3138         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3139         if (Load->getNumValues() == 3) {
3140           // PRE/POST_INC loads have 3 values.
3141           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3142                            NewLoad.getValue(2) };
3143           CombineTo(Load, To, 3, true);
3144         } else {
3145           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3146         }
3147       }
3148
3149       // Fold the AND away, taking care not to fold to the old load node if we
3150       // replaced it.
3151       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3152
3153       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3154     }
3155   }
3156
3157   // fold (and (load x), 255) -> (zextload x, i8)
3158   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3159   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3160   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3161               (N0.getOpcode() == ISD::ANY_EXTEND &&
3162                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3163     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3164     LoadSDNode *LN0 = HasAnyExt
3165       ? cast<LoadSDNode>(N0.getOperand(0))
3166       : cast<LoadSDNode>(N0);
3167     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3168         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3169       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3170       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3171         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3172         EVT LoadedVT = LN0->getMemoryVT();
3173         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3174
3175         if (ExtVT == LoadedVT &&
3176             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3177                                                     ExtVT))) {
3178
3179           SDValue NewLoad =
3180             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3181                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3182                            LN0->getMemOperand());
3183           AddToWorklist(N);
3184           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3185           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3186         }
3187
3188         // Do not change the width of a volatile load.
3189         // Do not generate loads of non-round integer types since these can
3190         // be expensive (and would be wrong if the type is not byte sized).
3191         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3192             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3193                                                     ExtVT))) {
3194           EVT PtrType = LN0->getOperand(1).getValueType();
3195
3196           unsigned Alignment = LN0->getAlignment();
3197           SDValue NewPtr = LN0->getBasePtr();
3198
3199           // For big endian targets, we need to add an offset to the pointer
3200           // to load the correct bytes.  For little endian systems, we merely
3201           // need to read fewer bytes from the same pointer.
3202           if (DAG.getDataLayout().isBigEndian()) {
3203             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3204             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3205             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3206             SDLoc DL(LN0);
3207             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3208                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3209             Alignment = MinAlign(Alignment, PtrOff);
3210           }
3211
3212           AddToWorklist(NewPtr.getNode());
3213
3214           SDValue Load =
3215             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3216                            LN0->getChain(), NewPtr,
3217                            LN0->getPointerInfo(),
3218                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3219                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3220           AddToWorklist(N);
3221           CombineTo(LN0, Load, Load.getValue(1));
3222           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3223         }
3224       }
3225     }
3226   }
3227
3228   if (SDValue Combined = visitANDLike(N0, N1, N))
3229     return Combined;
3230
3231   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3232   if (N0.getOpcode() == N1.getOpcode())
3233     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3234       return Tmp;
3235
3236   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3237   // fold (and (sra)) -> (and (srl)) when possible.
3238   if (!VT.isVector() &&
3239       SimplifyDemandedBits(SDValue(N, 0)))
3240     return SDValue(N, 0);
3241
3242   // fold (zext_inreg (extload x)) -> (zextload x)
3243   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3244     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3245     EVT MemVT = LN0->getMemoryVT();
3246     // If we zero all the possible extended bits, then we can turn this into
3247     // a zextload if we are running before legalize or the operation is legal.
3248     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3249     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3250                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3251         ((!LegalOperations && !LN0->isVolatile()) ||
3252          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3253       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3254                                        LN0->getChain(), LN0->getBasePtr(),
3255                                        MemVT, LN0->getMemOperand());
3256       AddToWorklist(N);
3257       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3258       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3259     }
3260   }
3261   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3262   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3263       N0.hasOneUse()) {
3264     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3265     EVT MemVT = LN0->getMemoryVT();
3266     // If we zero all the possible extended bits, then we can turn this into
3267     // a zextload if we are running before legalize or the operation is legal.
3268     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3269     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3270                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3271         ((!LegalOperations && !LN0->isVolatile()) ||
3272          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3273       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3274                                        LN0->getChain(), LN0->getBasePtr(),
3275                                        MemVT, LN0->getMemOperand());
3276       AddToWorklist(N);
3277       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3278       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3279     }
3280   }
3281   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3282   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3283     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3284                                        N0.getOperand(1), false);
3285     if (BSwap.getNode())
3286       return BSwap;
3287   }
3288
3289   return SDValue();
3290 }
3291
3292 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3293 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3294                                         bool DemandHighBits) {
3295   if (!LegalOperations)
3296     return SDValue();
3297
3298   EVT VT = N->getValueType(0);
3299   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3300     return SDValue();
3301   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3302     return SDValue();
3303
3304   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3305   bool LookPassAnd0 = false;
3306   bool LookPassAnd1 = false;
3307   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3308       std::swap(N0, N1);
3309   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3310       std::swap(N0, N1);
3311   if (N0.getOpcode() == ISD::AND) {
3312     if (!N0.getNode()->hasOneUse())
3313       return SDValue();
3314     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3315     if (!N01C || N01C->getZExtValue() != 0xFF00)
3316       return SDValue();
3317     N0 = N0.getOperand(0);
3318     LookPassAnd0 = true;
3319   }
3320
3321   if (N1.getOpcode() == ISD::AND) {
3322     if (!N1.getNode()->hasOneUse())
3323       return SDValue();
3324     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3325     if (!N11C || N11C->getZExtValue() != 0xFF)
3326       return SDValue();
3327     N1 = N1.getOperand(0);
3328     LookPassAnd1 = true;
3329   }
3330
3331   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3332     std::swap(N0, N1);
3333   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3334     return SDValue();
3335   if (!N0.getNode()->hasOneUse() ||
3336       !N1.getNode()->hasOneUse())
3337     return SDValue();
3338
3339   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3340   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3341   if (!N01C || !N11C)
3342     return SDValue();
3343   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3344     return SDValue();
3345
3346   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3347   SDValue N00 = N0->getOperand(0);
3348   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3349     if (!N00.getNode()->hasOneUse())
3350       return SDValue();
3351     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3352     if (!N001C || N001C->getZExtValue() != 0xFF)
3353       return SDValue();
3354     N00 = N00.getOperand(0);
3355     LookPassAnd0 = true;
3356   }
3357
3358   SDValue N10 = N1->getOperand(0);
3359   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3360     if (!N10.getNode()->hasOneUse())
3361       return SDValue();
3362     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3363     if (!N101C || N101C->getZExtValue() != 0xFF00)
3364       return SDValue();
3365     N10 = N10.getOperand(0);
3366     LookPassAnd1 = true;
3367   }
3368
3369   if (N00 != N10)
3370     return SDValue();
3371
3372   // Make sure everything beyond the low halfword gets set to zero since the SRL
3373   // 16 will clear the top bits.
3374   unsigned OpSizeInBits = VT.getSizeInBits();
3375   if (DemandHighBits && OpSizeInBits > 16) {
3376     // If the left-shift isn't masked out then the only way this is a bswap is
3377     // if all bits beyond the low 8 are 0. In that case the entire pattern
3378     // reduces to a left shift anyway: leave it for other parts of the combiner.
3379     if (!LookPassAnd0)
3380       return SDValue();
3381
3382     // However, if the right shift isn't masked out then it might be because
3383     // it's not needed. See if we can spot that too.
3384     if (!LookPassAnd1 &&
3385         !DAG.MaskedValueIsZero(
3386             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3387       return SDValue();
3388   }
3389
3390   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3391   if (OpSizeInBits > 16) {
3392     SDLoc DL(N);
3393     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3394                       DAG.getConstant(OpSizeInBits - 16, DL,
3395                                       getShiftAmountTy(VT)));
3396   }
3397   return Res;
3398 }
3399
3400 /// Return true if the specified node is an element that makes up a 32-bit
3401 /// packed halfword byteswap.
3402 /// ((x & 0x000000ff) << 8) |
3403 /// ((x & 0x0000ff00) >> 8) |
3404 /// ((x & 0x00ff0000) << 8) |
3405 /// ((x & 0xff000000) >> 8)
3406 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3407   if (!N.getNode()->hasOneUse())
3408     return false;
3409
3410   unsigned Opc = N.getOpcode();
3411   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3412     return false;
3413
3414   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3415   if (!N1C)
3416     return false;
3417
3418   unsigned Num;
3419   switch (N1C->getZExtValue()) {
3420   default:
3421     return false;
3422   case 0xFF:       Num = 0; break;
3423   case 0xFF00:     Num = 1; break;
3424   case 0xFF0000:   Num = 2; break;
3425   case 0xFF000000: Num = 3; break;
3426   }
3427
3428   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3429   SDValue N0 = N.getOperand(0);
3430   if (Opc == ISD::AND) {
3431     if (Num == 0 || Num == 2) {
3432       // (x >> 8) & 0xff
3433       // (x >> 8) & 0xff0000
3434       if (N0.getOpcode() != ISD::SRL)
3435         return false;
3436       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3437       if (!C || C->getZExtValue() != 8)
3438         return false;
3439     } else {
3440       // (x << 8) & 0xff00
3441       // (x << 8) & 0xff000000
3442       if (N0.getOpcode() != ISD::SHL)
3443         return false;
3444       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3445       if (!C || C->getZExtValue() != 8)
3446         return false;
3447     }
3448   } else if (Opc == ISD::SHL) {
3449     // (x & 0xff) << 8
3450     // (x & 0xff0000) << 8
3451     if (Num != 0 && Num != 2)
3452       return false;
3453     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3454     if (!C || C->getZExtValue() != 8)
3455       return false;
3456   } else { // Opc == ISD::SRL
3457     // (x & 0xff00) >> 8
3458     // (x & 0xff000000) >> 8
3459     if (Num != 1 && Num != 3)
3460       return false;
3461     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3462     if (!C || C->getZExtValue() != 8)
3463       return false;
3464   }
3465
3466   if (Parts[Num])
3467     return false;
3468
3469   Parts[Num] = N0.getOperand(0).getNode();
3470   return true;
3471 }
3472
3473 /// Match a 32-bit packed halfword bswap. That is
3474 /// ((x & 0x000000ff) << 8) |
3475 /// ((x & 0x0000ff00) >> 8) |
3476 /// ((x & 0x00ff0000) << 8) |
3477 /// ((x & 0xff000000) >> 8)
3478 /// => (rotl (bswap x), 16)
3479 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3480   if (!LegalOperations)
3481     return SDValue();
3482
3483   EVT VT = N->getValueType(0);
3484   if (VT != MVT::i32)
3485     return SDValue();
3486   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3487     return SDValue();
3488
3489   // Look for either
3490   // (or (or (and), (and)), (or (and), (and)))
3491   // (or (or (or (and), (and)), (and)), (and))
3492   if (N0.getOpcode() != ISD::OR)
3493     return SDValue();
3494   SDValue N00 = N0.getOperand(0);
3495   SDValue N01 = N0.getOperand(1);
3496   SDNode *Parts[4] = {};
3497
3498   if (N1.getOpcode() == ISD::OR &&
3499       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3500     // (or (or (and), (and)), (or (and), (and)))
3501     SDValue N000 = N00.getOperand(0);
3502     if (!isBSwapHWordElement(N000, Parts))
3503       return SDValue();
3504
3505     SDValue N001 = N00.getOperand(1);
3506     if (!isBSwapHWordElement(N001, Parts))
3507       return SDValue();
3508     SDValue N010 = N01.getOperand(0);
3509     if (!isBSwapHWordElement(N010, Parts))
3510       return SDValue();
3511     SDValue N011 = N01.getOperand(1);
3512     if (!isBSwapHWordElement(N011, Parts))
3513       return SDValue();
3514   } else {
3515     // (or (or (or (and), (and)), (and)), (and))
3516     if (!isBSwapHWordElement(N1, Parts))
3517       return SDValue();
3518     if (!isBSwapHWordElement(N01, Parts))
3519       return SDValue();
3520     if (N00.getOpcode() != ISD::OR)
3521       return SDValue();
3522     SDValue N000 = N00.getOperand(0);
3523     if (!isBSwapHWordElement(N000, Parts))
3524       return SDValue();
3525     SDValue N001 = N00.getOperand(1);
3526     if (!isBSwapHWordElement(N001, Parts))
3527       return SDValue();
3528   }
3529
3530   // Make sure the parts are all coming from the same node.
3531   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3532     return SDValue();
3533
3534   SDLoc DL(N);
3535   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3536                               SDValue(Parts[0], 0));
3537
3538   // Result of the bswap should be rotated by 16. If it's not legal, then
3539   // do  (x << 16) | (x >> 16).
3540   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3541   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3542     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3543   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3544     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3545   return DAG.getNode(ISD::OR, DL, VT,
3546                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3547                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3548 }
3549
3550 /// This contains all DAGCombine rules which reduce two values combined by
3551 /// an Or operation to a single value \see visitANDLike().
3552 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3553   EVT VT = N1.getValueType();
3554   // fold (or x, undef) -> -1
3555   if (!LegalOperations &&
3556       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3557     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3558     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3559                            SDLoc(LocReference), VT);
3560   }
3561   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3562   SDValue LL, LR, RL, RR, CC0, CC1;
3563   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3564     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3565     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3566
3567     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3568       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3569       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3570       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3571         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3572                                      LR.getValueType(), LL, RL);
3573         AddToWorklist(ORNode.getNode());
3574         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3575       }
3576       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3577       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3578       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3579         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3580                                       LR.getValueType(), LL, RL);
3581         AddToWorklist(ANDNode.getNode());
3582         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3583       }
3584     }
3585     // canonicalize equivalent to ll == rl
3586     if (LL == RR && LR == RL) {
3587       Op1 = ISD::getSetCCSwappedOperands(Op1);
3588       std::swap(RL, RR);
3589     }
3590     if (LL == RL && LR == RR) {
3591       bool isInteger = LL.getValueType().isInteger();
3592       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3593       if (Result != ISD::SETCC_INVALID &&
3594           (!LegalOperations ||
3595            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3596             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3597         EVT CCVT = getSetCCResultType(LL.getValueType());
3598         if (N0.getValueType() == CCVT ||
3599             (!LegalOperations && N0.getValueType() == MVT::i1))
3600           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3601                               LL, LR, Result);
3602       }
3603     }
3604   }
3605
3606   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3607   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3608       // Don't increase # computations.
3609       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3610     // We can only do this xform if we know that bits from X that are set in C2
3611     // but not in C1 are already zero.  Likewise for Y.
3612     if (const ConstantSDNode *N0O1C =
3613         getAsNonOpaqueConstant(N0.getOperand(1))) {
3614       if (const ConstantSDNode *N1O1C =
3615           getAsNonOpaqueConstant(N1.getOperand(1))) {
3616         // We can only do this xform if we know that bits from X that are set in
3617         // C2 but not in C1 are already zero.  Likewise for Y.
3618         const APInt &LHSMask = N0O1C->getAPIntValue();
3619         const APInt &RHSMask = N1O1C->getAPIntValue();
3620
3621         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3622             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3623           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3624                                   N0.getOperand(0), N1.getOperand(0));
3625           SDLoc DL(LocReference);
3626           return DAG.getNode(ISD::AND, DL, VT, X,
3627                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3628         }
3629       }
3630     }
3631   }
3632
3633   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3634   if (N0.getOpcode() == ISD::AND &&
3635       N1.getOpcode() == ISD::AND &&
3636       N0.getOperand(0) == N1.getOperand(0) &&
3637       // Don't increase # computations.
3638       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3639     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3640                             N0.getOperand(1), N1.getOperand(1));
3641     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3642   }
3643
3644   return SDValue();
3645 }
3646
3647 SDValue DAGCombiner::visitOR(SDNode *N) {
3648   SDValue N0 = N->getOperand(0);
3649   SDValue N1 = N->getOperand(1);
3650   EVT VT = N1.getValueType();
3651
3652   // fold vector ops
3653   if (VT.isVector()) {
3654     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3655       return FoldedVOp;
3656
3657     // fold (or x, 0) -> x, vector edition
3658     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3659       return N1;
3660     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3661       return N0;
3662
3663     // fold (or x, -1) -> -1, vector edition
3664     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3665       // do not return N0, because undef node may exist in N0
3666       return DAG.getConstant(
3667           APInt::getAllOnesValue(
3668               N0.getValueType().getScalarType().getSizeInBits()),
3669           SDLoc(N), N0.getValueType());
3670     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3671       // do not return N1, because undef node may exist in N1
3672       return DAG.getConstant(
3673           APInt::getAllOnesValue(
3674               N1.getValueType().getScalarType().getSizeInBits()),
3675           SDLoc(N), N1.getValueType());
3676
3677     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3678     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3679     // Do this only if the resulting shuffle is legal.
3680     if (isa<ShuffleVectorSDNode>(N0) &&
3681         isa<ShuffleVectorSDNode>(N1) &&
3682         // Avoid folding a node with illegal type.
3683         TLI.isTypeLegal(VT) &&
3684         N0->getOperand(1) == N1->getOperand(1) &&
3685         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3686       bool CanFold = true;
3687       unsigned NumElts = VT.getVectorNumElements();
3688       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3689       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3690       // We construct two shuffle masks:
3691       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3692       // and N1 as the second operand.
3693       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3694       // and N0 as the second operand.
3695       // We do this because OR is commutable and therefore there might be
3696       // two ways to fold this node into a shuffle.
3697       SmallVector<int,4> Mask1;
3698       SmallVector<int,4> Mask2;
3699
3700       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3701         int M0 = SV0->getMaskElt(i);
3702         int M1 = SV1->getMaskElt(i);
3703
3704         // Both shuffle indexes are undef. Propagate Undef.
3705         if (M0 < 0 && M1 < 0) {
3706           Mask1.push_back(M0);
3707           Mask2.push_back(M0);
3708           continue;
3709         }
3710
3711         if (M0 < 0 || M1 < 0 ||
3712             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3713             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3714           CanFold = false;
3715           break;
3716         }
3717
3718         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3719         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3720       }
3721
3722       if (CanFold) {
3723         // Fold this sequence only if the resulting shuffle is 'legal'.
3724         if (TLI.isShuffleMaskLegal(Mask1, VT))
3725           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3726                                       N1->getOperand(0), &Mask1[0]);
3727         if (TLI.isShuffleMaskLegal(Mask2, VT))
3728           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3729                                       N0->getOperand(0), &Mask2[0]);
3730       }
3731     }
3732   }
3733
3734   // fold (or c1, c2) -> c1|c2
3735   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3736   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3737   if (N0C && N1C && !N1C->isOpaque())
3738     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3739   // canonicalize constant to RHS
3740   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3741      !isConstantIntBuildVectorOrConstantInt(N1))
3742     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3743   // fold (or x, 0) -> x
3744   if (isNullConstant(N1))
3745     return N0;
3746   // fold (or x, -1) -> -1
3747   if (isAllOnesConstant(N1))
3748     return N1;
3749   // fold (or x, c) -> c iff (x & ~c) == 0
3750   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3751     return N1;
3752
3753   if (SDValue Combined = visitORLike(N0, N1, N))
3754     return Combined;
3755
3756   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3757   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3758     return BSwap;
3759   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3760     return BSwap;
3761
3762   // reassociate or
3763   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3764     return ROR;
3765   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3766   // iff (c1 & c2) == 0.
3767   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3768              isa<ConstantSDNode>(N0.getOperand(1))) {
3769     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3770     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3771       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3772                                                    N1C, C1))
3773         return DAG.getNode(
3774             ISD::AND, SDLoc(N), VT,
3775             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3776       return SDValue();
3777     }
3778   }
3779   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3780   if (N0.getOpcode() == N1.getOpcode())
3781     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3782       return Tmp;
3783
3784   // See if this is some rotate idiom.
3785   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3786     return SDValue(Rot, 0);
3787
3788   // Simplify the operands using demanded-bits information.
3789   if (!VT.isVector() &&
3790       SimplifyDemandedBits(SDValue(N, 0)))
3791     return SDValue(N, 0);
3792
3793   return SDValue();
3794 }
3795
3796 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3797 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3798   if (Op.getOpcode() == ISD::AND) {
3799     if (isConstOrConstSplat(Op.getOperand(1))) {
3800       Mask = Op.getOperand(1);
3801       Op = Op.getOperand(0);
3802     } else {
3803       return false;
3804     }
3805   }
3806
3807   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3808     Shift = Op;
3809     return true;
3810   }
3811
3812   return false;
3813 }
3814
3815 // Return true if we can prove that, whenever Neg and Pos are both in the
3816 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3817 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3818 //
3819 //     (or (shift1 X, Neg), (shift2 X, Pos))
3820 //
3821 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3822 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3823 // to consider shift amounts with defined behavior.
3824 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3825   // If EltSize is a power of 2 then:
3826   //
3827   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3828   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3829   //
3830   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3831   // for the stronger condition:
3832   //
3833   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3834   //
3835   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3836   // we can just replace Neg with Neg' for the rest of the function.
3837   //
3838   // In other cases we check for the even stronger condition:
3839   //
3840   //     Neg == EltSize - Pos                                    [B]
3841   //
3842   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3843   // behavior if Pos == 0 (and consequently Neg == EltSize).
3844   //
3845   // We could actually use [A] whenever EltSize is a power of 2, but the
3846   // only extra cases that it would match are those uninteresting ones
3847   // where Neg and Pos are never in range at the same time.  E.g. for
3848   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3849   // as well as (sub 32, Pos), but:
3850   //
3851   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3852   //
3853   // always invokes undefined behavior for 32-bit X.
3854   //
3855   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3856   unsigned MaskLoBits = 0;
3857   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3858     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3859       if (NegC->getAPIntValue() == EltSize - 1) {
3860         Neg = Neg.getOperand(0);
3861         MaskLoBits = Log2_64(EltSize);
3862       }
3863     }
3864   }
3865
3866   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3867   if (Neg.getOpcode() != ISD::SUB)
3868     return 0;
3869   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3870   if (!NegC)
3871     return 0;
3872   SDValue NegOp1 = Neg.getOperand(1);
3873
3874   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3875   // Pos'.  The truncation is redundant for the purpose of the equality.
3876   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3877     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3878       if (PosC->getAPIntValue() == EltSize - 1)
3879         Pos = Pos.getOperand(0);
3880
3881   // The condition we need is now:
3882   //
3883   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3884   //
3885   // If NegOp1 == Pos then we need:
3886   //
3887   //              EltSize & Mask == NegC & Mask
3888   //
3889   // (because "x & Mask" is a truncation and distributes through subtraction).
3890   APInt Width;
3891   if (Pos == NegOp1)
3892     Width = NegC->getAPIntValue();
3893
3894   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3895   // Then the condition we want to prove becomes:
3896   //
3897   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3898   //
3899   // which, again because "x & Mask" is a truncation, becomes:
3900   //
3901   //                NegC & Mask == (EltSize - PosC) & Mask
3902   //             EltSize & Mask == (NegC + PosC) & Mask
3903   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3904     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3905       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3906     else
3907       return false;
3908   } else
3909     return false;
3910
3911   // Now we just need to check that EltSize & Mask == Width & Mask.
3912   if (MaskLoBits)
3913     // EltSize & Mask is 0 since Mask is EltSize - 1.
3914     return Width.getLoBits(MaskLoBits) == 0;
3915   return Width == EltSize;
3916 }
3917
3918 // A subroutine of MatchRotate used once we have found an OR of two opposite
3919 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3920 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3921 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3922 // Neg with outer conversions stripped away.
3923 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3924                                        SDValue Neg, SDValue InnerPos,
3925                                        SDValue InnerNeg, unsigned PosOpcode,
3926                                        unsigned NegOpcode, SDLoc DL) {
3927   // fold (or (shl x, (*ext y)),
3928   //          (srl x, (*ext (sub 32, y)))) ->
3929   //   (rotl x, y) or (rotr x, (sub 32, y))
3930   //
3931   // fold (or (shl x, (*ext (sub 32, y))),
3932   //          (srl x, (*ext y))) ->
3933   //   (rotr x, y) or (rotl x, (sub 32, y))
3934   EVT VT = Shifted.getValueType();
3935   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3936     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3937     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3938                        HasPos ? Pos : Neg).getNode();
3939   }
3940
3941   return nullptr;
3942 }
3943
3944 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3945 // idioms for rotate, and if the target supports rotation instructions, generate
3946 // a rot[lr].
3947 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3948   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3949   EVT VT = LHS.getValueType();
3950   if (!TLI.isTypeLegal(VT)) return nullptr;
3951
3952   // The target must have at least one rotate flavor.
3953   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3954   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3955   if (!HasROTL && !HasROTR) return nullptr;
3956
3957   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3958   SDValue LHSShift;   // The shift.
3959   SDValue LHSMask;    // AND value if any.
3960   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3961     return nullptr; // Not part of a rotate.
3962
3963   SDValue RHSShift;   // The shift.
3964   SDValue RHSMask;    // AND value if any.
3965   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3966     return nullptr; // Not part of a rotate.
3967
3968   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3969     return nullptr;   // Not shifting the same value.
3970
3971   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3972     return nullptr;   // Shifts must disagree.
3973
3974   // Canonicalize shl to left side in a shl/srl pair.
3975   if (RHSShift.getOpcode() == ISD::SHL) {
3976     std::swap(LHS, RHS);
3977     std::swap(LHSShift, RHSShift);
3978     std::swap(LHSMask, RHSMask);
3979   }
3980
3981   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3982   SDValue LHSShiftArg = LHSShift.getOperand(0);
3983   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3984   SDValue RHSShiftArg = RHSShift.getOperand(0);
3985   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3986
3987   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3988   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3989   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
3990     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
3991     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
3992     if ((LShVal + RShVal) != EltSizeInBits)
3993       return nullptr;
3994
3995     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3996                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3997
3998     // If there is an AND of either shifted operand, apply it to the result.
3999     if (LHSMask.getNode() || RHSMask.getNode()) {
4000       APInt Mask = APInt::getAllOnesValue(EltSizeInBits);
4001
4002       if (LHSMask.getNode()) {
4003         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4004         Mask &= isConstOrConstSplat(LHSMask)->getAPIntValue() | RHSBits;
4005       }
4006       if (RHSMask.getNode()) {
4007         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4008         Mask &= isConstOrConstSplat(RHSMask)->getAPIntValue() | LHSBits;
4009       }
4010
4011       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
4012     }
4013
4014     return Rot.getNode();
4015   }
4016
4017   // If there is a mask here, and we have a variable shift, we can't be sure
4018   // that we're masking out the right stuff.
4019   if (LHSMask.getNode() || RHSMask.getNode())
4020     return nullptr;
4021
4022   // If the shift amount is sign/zext/any-extended just peel it off.
4023   SDValue LExtOp0 = LHSShiftAmt;
4024   SDValue RExtOp0 = RHSShiftAmt;
4025   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4026        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4027        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4028        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4029       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4030        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4031        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4032        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4033     LExtOp0 = LHSShiftAmt.getOperand(0);
4034     RExtOp0 = RHSShiftAmt.getOperand(0);
4035   }
4036
4037   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4038                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4039   if (TryL)
4040     return TryL;
4041
4042   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4043                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4044   if (TryR)
4045     return TryR;
4046
4047   return nullptr;
4048 }
4049
4050 SDValue DAGCombiner::visitXOR(SDNode *N) {
4051   SDValue N0 = N->getOperand(0);
4052   SDValue N1 = N->getOperand(1);
4053   EVT VT = N0.getValueType();
4054
4055   // fold vector ops
4056   if (VT.isVector()) {
4057     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4058       return FoldedVOp;
4059
4060     // fold (xor x, 0) -> x, vector edition
4061     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4062       return N1;
4063     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4064       return N0;
4065   }
4066
4067   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4068   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4069     return DAG.getConstant(0, SDLoc(N), VT);
4070   // fold (xor x, undef) -> undef
4071   if (N0.getOpcode() == ISD::UNDEF)
4072     return N0;
4073   if (N1.getOpcode() == ISD::UNDEF)
4074     return N1;
4075   // fold (xor c1, c2) -> c1^c2
4076   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4077   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4078   if (N0C && N1C)
4079     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4080   // canonicalize constant to RHS
4081   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4082      !isConstantIntBuildVectorOrConstantInt(N1))
4083     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4084   // fold (xor x, 0) -> x
4085   if (isNullConstant(N1))
4086     return N0;
4087   // reassociate xor
4088   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4089     return RXOR;
4090
4091   // fold !(x cc y) -> (x !cc y)
4092   SDValue LHS, RHS, CC;
4093   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4094     bool isInt = LHS.getValueType().isInteger();
4095     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4096                                                isInt);
4097
4098     if (!LegalOperations ||
4099         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4100       switch (N0.getOpcode()) {
4101       default:
4102         llvm_unreachable("Unhandled SetCC Equivalent!");
4103       case ISD::SETCC:
4104         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4105       case ISD::SELECT_CC:
4106         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4107                                N0.getOperand(3), NotCC);
4108       }
4109     }
4110   }
4111
4112   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4113   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4114       N0.getNode()->hasOneUse() &&
4115       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4116     SDValue V = N0.getOperand(0);
4117     SDLoc DL(N0);
4118     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4119                     DAG.getConstant(1, DL, V.getValueType()));
4120     AddToWorklist(V.getNode());
4121     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4122   }
4123
4124   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4125   if (isOneConstant(N1) && VT == MVT::i1 &&
4126       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4127     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4128     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4129       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4130       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4131       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4132       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4133       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4134     }
4135   }
4136   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4137   if (isAllOnesConstant(N1) &&
4138       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4139     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4140     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4141       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4142       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4143       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4144       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4145       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4146     }
4147   }
4148   // fold (xor (and x, y), y) -> (and (not x), y)
4149   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4150       N0->getOperand(1) == N1) {
4151     SDValue X = N0->getOperand(0);
4152     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4153     AddToWorklist(NotX.getNode());
4154     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4155   }
4156   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4157   if (N1C && N0.getOpcode() == ISD::XOR) {
4158     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4159       SDLoc DL(N);
4160       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4161                          DAG.getConstant(N1C->getAPIntValue() ^
4162                                          N00C->getAPIntValue(), DL, VT));
4163     }
4164     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4165       SDLoc DL(N);
4166       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4167                          DAG.getConstant(N1C->getAPIntValue() ^
4168                                          N01C->getAPIntValue(), DL, VT));
4169     }
4170   }
4171   // fold (xor x, x) -> 0
4172   if (N0 == N1)
4173     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4174
4175   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4176   // Here is a concrete example of this equivalence:
4177   // i16   x ==  14
4178   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4179   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4180   //
4181   // =>
4182   //
4183   // i16     ~1      == 0b1111111111111110
4184   // i16 rol(~1, 14) == 0b1011111111111111
4185   //
4186   // Some additional tips to help conceptualize this transform:
4187   // - Try to see the operation as placing a single zero in a value of all ones.
4188   // - There exists no value for x which would allow the result to contain zero.
4189   // - Values of x larger than the bitwidth are undefined and do not require a
4190   //   consistent result.
4191   // - Pushing the zero left requires shifting one bits in from the right.
4192   // A rotate left of ~1 is a nice way of achieving the desired result.
4193   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4194       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4195     SDLoc DL(N);
4196     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4197                        N0.getOperand(1));
4198   }
4199
4200   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4201   if (N0.getOpcode() == N1.getOpcode())
4202     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4203       return Tmp;
4204
4205   // Simplify the expression using non-local knowledge.
4206   if (!VT.isVector() &&
4207       SimplifyDemandedBits(SDValue(N, 0)))
4208     return SDValue(N, 0);
4209
4210   return SDValue();
4211 }
4212
4213 /// Handle transforms common to the three shifts, when the shift amount is a
4214 /// constant.
4215 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4216   SDNode *LHS = N->getOperand(0).getNode();
4217   if (!LHS->hasOneUse()) return SDValue();
4218
4219   // We want to pull some binops through shifts, so that we have (and (shift))
4220   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4221   // thing happens with address calculations, so it's important to canonicalize
4222   // it.
4223   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4224
4225   switch (LHS->getOpcode()) {
4226   default: return SDValue();
4227   case ISD::OR:
4228   case ISD::XOR:
4229     HighBitSet = false; // We can only transform sra if the high bit is clear.
4230     break;
4231   case ISD::AND:
4232     HighBitSet = true;  // We can only transform sra if the high bit is set.
4233     break;
4234   case ISD::ADD:
4235     if (N->getOpcode() != ISD::SHL)
4236       return SDValue(); // only shl(add) not sr[al](add).
4237     HighBitSet = false; // We can only transform sra if the high bit is clear.
4238     break;
4239   }
4240
4241   // We require the RHS of the binop to be a constant and not opaque as well.
4242   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4243   if (!BinOpCst) return SDValue();
4244
4245   // FIXME: disable this unless the input to the binop is a shift by a constant.
4246   // If it is not a shift, it pessimizes some common cases like:
4247   //
4248   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4249   //    int bar(int *X, int i) { return X[i & 255]; }
4250   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4251   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4252        BinOpLHSVal->getOpcode() != ISD::SRA &&
4253        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4254       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4255     return SDValue();
4256
4257   EVT VT = N->getValueType(0);
4258
4259   // If this is a signed shift right, and the high bit is modified by the
4260   // logical operation, do not perform the transformation. The highBitSet
4261   // boolean indicates the value of the high bit of the constant which would
4262   // cause it to be modified for this operation.
4263   if (N->getOpcode() == ISD::SRA) {
4264     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4265     if (BinOpRHSSignSet != HighBitSet)
4266       return SDValue();
4267   }
4268
4269   if (!TLI.isDesirableToCommuteWithShift(LHS))
4270     return SDValue();
4271
4272   // Fold the constants, shifting the binop RHS by the shift amount.
4273   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4274                                N->getValueType(0),
4275                                LHS->getOperand(1), N->getOperand(1));
4276   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4277
4278   // Create the new shift.
4279   SDValue NewShift = DAG.getNode(N->getOpcode(),
4280                                  SDLoc(LHS->getOperand(0)),
4281                                  VT, LHS->getOperand(0), N->getOperand(1));
4282
4283   // Create the new binop.
4284   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4285 }
4286
4287 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4288   assert(N->getOpcode() == ISD::TRUNCATE);
4289   assert(N->getOperand(0).getOpcode() == ISD::AND);
4290
4291   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4292   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4293     SDValue N01 = N->getOperand(0).getOperand(1);
4294
4295     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4296       if (!N01C->isOpaque()) {
4297         EVT TruncVT = N->getValueType(0);
4298         SDValue N00 = N->getOperand(0).getOperand(0);
4299         APInt TruncC = N01C->getAPIntValue();
4300         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4301         SDLoc DL(N);
4302
4303         return DAG.getNode(ISD::AND, DL, TruncVT,
4304                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4305                            DAG.getConstant(TruncC, DL, TruncVT));
4306       }
4307     }
4308   }
4309
4310   return SDValue();
4311 }
4312
4313 SDValue DAGCombiner::visitRotate(SDNode *N) {
4314   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4315   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4316       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4317     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4318     if (NewOp1.getNode())
4319       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4320                          N->getOperand(0), NewOp1);
4321   }
4322   return SDValue();
4323 }
4324
4325 SDValue DAGCombiner::visitSHL(SDNode *N) {
4326   SDValue N0 = N->getOperand(0);
4327   SDValue N1 = N->getOperand(1);
4328   EVT VT = N0.getValueType();
4329   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4330
4331   // fold vector ops
4332   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4333   if (VT.isVector()) {
4334     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4335       return FoldedVOp;
4336
4337     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4338     // If setcc produces all-one true value then:
4339     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4340     if (N1CV && N1CV->isConstant()) {
4341       if (N0.getOpcode() == ISD::AND) {
4342         SDValue N00 = N0->getOperand(0);
4343         SDValue N01 = N0->getOperand(1);
4344         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4345
4346         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4347             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4348                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4349           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4350                                                      N01CV, N1CV))
4351             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4352         }
4353       } else {
4354         N1C = isConstOrConstSplat(N1);
4355       }
4356     }
4357   }
4358
4359   // fold (shl c1, c2) -> c1<<c2
4360   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4361   if (N0C && N1C && !N1C->isOpaque())
4362     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4363   // fold (shl 0, x) -> 0
4364   if (isNullConstant(N0))
4365     return N0;
4366   // fold (shl x, c >= size(x)) -> undef
4367   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4368     return DAG.getUNDEF(VT);
4369   // fold (shl x, 0) -> x
4370   if (N1C && N1C->isNullValue())
4371     return N0;
4372   // fold (shl undef, x) -> 0
4373   if (N0.getOpcode() == ISD::UNDEF)
4374     return DAG.getConstant(0, SDLoc(N), VT);
4375   // if (shl x, c) is known to be zero, return 0
4376   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4377                             APInt::getAllOnesValue(OpSizeInBits)))
4378     return DAG.getConstant(0, SDLoc(N), VT);
4379   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4380   if (N1.getOpcode() == ISD::TRUNCATE &&
4381       N1.getOperand(0).getOpcode() == ISD::AND) {
4382     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4383     if (NewOp1.getNode())
4384       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4385   }
4386
4387   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4388     return SDValue(N, 0);
4389
4390   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4391   if (N1C && N0.getOpcode() == ISD::SHL) {
4392     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4393       uint64_t c1 = N0C1->getZExtValue();
4394       uint64_t c2 = N1C->getZExtValue();
4395       SDLoc DL(N);
4396       if (c1 + c2 >= OpSizeInBits)
4397         return DAG.getConstant(0, DL, VT);
4398       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4399                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4400     }
4401   }
4402
4403   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4404   // For this to be valid, the second form must not preserve any of the bits
4405   // that are shifted out by the inner shift in the first form.  This means
4406   // the outer shift size must be >= the number of bits added by the ext.
4407   // As a corollary, we don't care what kind of ext it is.
4408   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4409               N0.getOpcode() == ISD::ANY_EXTEND ||
4410               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4411       N0.getOperand(0).getOpcode() == ISD::SHL) {
4412     SDValue N0Op0 = N0.getOperand(0);
4413     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4414       uint64_t c1 = N0Op0C1->getZExtValue();
4415       uint64_t c2 = N1C->getZExtValue();
4416       EVT InnerShiftVT = N0Op0.getValueType();
4417       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4418       if (c2 >= OpSizeInBits - InnerShiftSize) {
4419         SDLoc DL(N0);
4420         if (c1 + c2 >= OpSizeInBits)
4421           return DAG.getConstant(0, DL, VT);
4422         return DAG.getNode(ISD::SHL, DL, VT,
4423                            DAG.getNode(N0.getOpcode(), DL, VT,
4424                                        N0Op0->getOperand(0)),
4425                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4426       }
4427     }
4428   }
4429
4430   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4431   // Only fold this if the inner zext has no other uses to avoid increasing
4432   // the total number of instructions.
4433   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4434       N0.getOperand(0).getOpcode() == ISD::SRL) {
4435     SDValue N0Op0 = N0.getOperand(0);
4436     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4437       uint64_t c1 = N0Op0C1->getZExtValue();
4438       if (c1 < VT.getScalarSizeInBits()) {
4439         uint64_t c2 = N1C->getZExtValue();
4440         if (c1 == c2) {
4441           SDValue NewOp0 = N0.getOperand(0);
4442           EVT CountVT = NewOp0.getOperand(1).getValueType();
4443           SDLoc DL(N);
4444           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4445                                        NewOp0,
4446                                        DAG.getConstant(c2, DL, CountVT));
4447           AddToWorklist(NewSHL.getNode());
4448           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4449         }
4450       }
4451     }
4452   }
4453
4454   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4455   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4456   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4457       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4458     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4459       uint64_t C1 = N0C1->getZExtValue();
4460       uint64_t C2 = N1C->getZExtValue();
4461       SDLoc DL(N);
4462       if (C1 <= C2)
4463         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4464                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4465       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4466                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4467     }
4468   }
4469
4470   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4471   //                               (and (srl x, (sub c1, c2), MASK)
4472   // Only fold this if the inner shift has no other uses -- if it does, folding
4473   // this will increase the total number of instructions.
4474   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4475     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4476       uint64_t c1 = N0C1->getZExtValue();
4477       if (c1 < OpSizeInBits) {
4478         uint64_t c2 = N1C->getZExtValue();
4479         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4480         SDValue Shift;
4481         if (c2 > c1) {
4482           Mask = Mask.shl(c2 - c1);
4483           SDLoc DL(N);
4484           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4485                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4486         } else {
4487           Mask = Mask.lshr(c1 - c2);
4488           SDLoc DL(N);
4489           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4490                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4491         }
4492         SDLoc DL(N0);
4493         return DAG.getNode(ISD::AND, DL, VT, Shift,
4494                            DAG.getConstant(Mask, DL, VT));
4495       }
4496     }
4497   }
4498   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4499   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4500     unsigned BitSize = VT.getScalarSizeInBits();
4501     SDLoc DL(N);
4502     SDValue HiBitsMask =
4503       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4504                                             BitSize - N1C->getZExtValue()),
4505                       DL, VT);
4506     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4507                        HiBitsMask);
4508   }
4509
4510   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4511   // Variant of version done on multiply, except mul by a power of 2 is turned
4512   // into a shift.
4513   APInt Val;
4514   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4515       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4516        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4517     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4518     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4519     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4520   }
4521
4522   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4523   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4524     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4525       if (SDValue Folded =
4526               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4527         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4528     }
4529   }
4530
4531   if (N1C && !N1C->isOpaque())
4532     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4533       return NewSHL;
4534
4535   return SDValue();
4536 }
4537
4538 SDValue DAGCombiner::visitSRA(SDNode *N) {
4539   SDValue N0 = N->getOperand(0);
4540   SDValue N1 = N->getOperand(1);
4541   EVT VT = N0.getValueType();
4542   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4543
4544   // fold vector ops
4545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4546   if (VT.isVector()) {
4547     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4548       return FoldedVOp;
4549
4550     N1C = isConstOrConstSplat(N1);
4551   }
4552
4553   // fold (sra c1, c2) -> (sra c1, c2)
4554   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4555   if (N0C && N1C && !N1C->isOpaque())
4556     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4557   // fold (sra 0, x) -> 0
4558   if (isNullConstant(N0))
4559     return N0;
4560   // fold (sra -1, x) -> -1
4561   if (isAllOnesConstant(N0))
4562     return N0;
4563   // fold (sra x, (setge c, size(x))) -> undef
4564   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4565     return DAG.getUNDEF(VT);
4566   // fold (sra x, 0) -> x
4567   if (N1C && N1C->isNullValue())
4568     return N0;
4569   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4570   // sext_inreg.
4571   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4572     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4573     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4574     if (VT.isVector())
4575       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4576                                ExtVT, VT.getVectorNumElements());
4577     if ((!LegalOperations ||
4578          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4579       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4580                          N0.getOperand(0), DAG.getValueType(ExtVT));
4581   }
4582
4583   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4584   if (N1C && N0.getOpcode() == ISD::SRA) {
4585     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4586       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4587       if (Sum >= OpSizeInBits)
4588         Sum = OpSizeInBits - 1;
4589       SDLoc DL(N);
4590       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4591                          DAG.getConstant(Sum, DL, N1.getValueType()));
4592     }
4593   }
4594
4595   // fold (sra (shl X, m), (sub result_size, n))
4596   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4597   // result_size - n != m.
4598   // If truncate is free for the target sext(shl) is likely to result in better
4599   // code.
4600   if (N0.getOpcode() == ISD::SHL && N1C) {
4601     // Get the two constanst of the shifts, CN0 = m, CN = n.
4602     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4603     if (N01C) {
4604       LLVMContext &Ctx = *DAG.getContext();
4605       // Determine what the truncate's result bitsize and type would be.
4606       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4607
4608       if (VT.isVector())
4609         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4610
4611       // Determine the residual right-shift amount.
4612       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4613
4614       // If the shift is not a no-op (in which case this should be just a sign
4615       // extend already), the truncated to type is legal, sign_extend is legal
4616       // on that type, and the truncate to that type is both legal and free,
4617       // perform the transform.
4618       if ((ShiftAmt > 0) &&
4619           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4620           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4621           TLI.isTruncateFree(VT, TruncVT)) {
4622
4623         SDLoc DL(N);
4624         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4625             getShiftAmountTy(N0.getOperand(0).getValueType()));
4626         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4627                                     N0.getOperand(0), Amt);
4628         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4629                                     Shift);
4630         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4631                            N->getValueType(0), Trunc);
4632       }
4633     }
4634   }
4635
4636   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4637   if (N1.getOpcode() == ISD::TRUNCATE &&
4638       N1.getOperand(0).getOpcode() == ISD::AND) {
4639     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4640     if (NewOp1.getNode())
4641       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4642   }
4643
4644   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4645   //      if c1 is equal to the number of bits the trunc removes
4646   if (N0.getOpcode() == ISD::TRUNCATE &&
4647       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4648        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4649       N0.getOperand(0).hasOneUse() &&
4650       N0.getOperand(0).getOperand(1).hasOneUse() &&
4651       N1C) {
4652     SDValue N0Op0 = N0.getOperand(0);
4653     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4654       unsigned LargeShiftVal = LargeShift->getZExtValue();
4655       EVT LargeVT = N0Op0.getValueType();
4656
4657       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4658         SDLoc DL(N);
4659         SDValue Amt =
4660           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4661                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4662         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4663                                   N0Op0.getOperand(0), Amt);
4664         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4665       }
4666     }
4667   }
4668
4669   // Simplify, based on bits shifted out of the LHS.
4670   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4671     return SDValue(N, 0);
4672
4673
4674   // If the sign bit is known to be zero, switch this to a SRL.
4675   if (DAG.SignBitIsZero(N0))
4676     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4677
4678   if (N1C && !N1C->isOpaque())
4679     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4680       return NewSRA;
4681
4682   return SDValue();
4683 }
4684
4685 SDValue DAGCombiner::visitSRL(SDNode *N) {
4686   SDValue N0 = N->getOperand(0);
4687   SDValue N1 = N->getOperand(1);
4688   EVT VT = N0.getValueType();
4689   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4690
4691   // fold vector ops
4692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4693   if (VT.isVector()) {
4694     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4695       return FoldedVOp;
4696
4697     N1C = isConstOrConstSplat(N1);
4698   }
4699
4700   // fold (srl c1, c2) -> c1 >>u c2
4701   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4702   if (N0C && N1C && !N1C->isOpaque())
4703     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4704   // fold (srl 0, x) -> 0
4705   if (isNullConstant(N0))
4706     return N0;
4707   // fold (srl x, c >= size(x)) -> undef
4708   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4709     return DAG.getUNDEF(VT);
4710   // fold (srl x, 0) -> x
4711   if (N1C && N1C->isNullValue())
4712     return N0;
4713   // if (srl x, c) is known to be zero, return 0
4714   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4715                                    APInt::getAllOnesValue(OpSizeInBits)))
4716     return DAG.getConstant(0, SDLoc(N), VT);
4717
4718   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4719   if (N1C && N0.getOpcode() == ISD::SRL) {
4720     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4721       uint64_t c1 = N01C->getZExtValue();
4722       uint64_t c2 = N1C->getZExtValue();
4723       SDLoc DL(N);
4724       if (c1 + c2 >= OpSizeInBits)
4725         return DAG.getConstant(0, DL, VT);
4726       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4727                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4728     }
4729   }
4730
4731   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4732   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4733       N0.getOperand(0).getOpcode() == ISD::SRL &&
4734       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4735     uint64_t c1 =
4736       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4737     uint64_t c2 = N1C->getZExtValue();
4738     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4739     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4740     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4741     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4742     if (c1 + OpSizeInBits == InnerShiftSize) {
4743       SDLoc DL(N0);
4744       if (c1 + c2 >= InnerShiftSize)
4745         return DAG.getConstant(0, DL, VT);
4746       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4747                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4748                                      N0.getOperand(0)->getOperand(0),
4749                                      DAG.getConstant(c1 + c2, DL,
4750                                                      ShiftCountVT)));
4751     }
4752   }
4753
4754   // fold (srl (shl x, c), c) -> (and x, cst2)
4755   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4756     unsigned BitSize = N0.getScalarValueSizeInBits();
4757     if (BitSize <= 64) {
4758       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4759       SDLoc DL(N);
4760       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4761                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4762     }
4763   }
4764
4765   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4766   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4767     // Shifting in all undef bits?
4768     EVT SmallVT = N0.getOperand(0).getValueType();
4769     unsigned BitSize = SmallVT.getScalarSizeInBits();
4770     if (N1C->getZExtValue() >= BitSize)
4771       return DAG.getUNDEF(VT);
4772
4773     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4774       uint64_t ShiftAmt = N1C->getZExtValue();
4775       SDLoc DL0(N0);
4776       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4777                                        N0.getOperand(0),
4778                           DAG.getConstant(ShiftAmt, DL0,
4779                                           getShiftAmountTy(SmallVT)));
4780       AddToWorklist(SmallShift.getNode());
4781       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4782       SDLoc DL(N);
4783       return DAG.getNode(ISD::AND, DL, VT,
4784                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4785                          DAG.getConstant(Mask, DL, VT));
4786     }
4787   }
4788
4789   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4790   // bit, which is unmodified by sra.
4791   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4792     if (N0.getOpcode() == ISD::SRA)
4793       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4794   }
4795
4796   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4797   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4798       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4799     APInt KnownZero, KnownOne;
4800     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4801
4802     // If any of the input bits are KnownOne, then the input couldn't be all
4803     // zeros, thus the result of the srl will always be zero.
4804     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4805
4806     // If all of the bits input the to ctlz node are known to be zero, then
4807     // the result of the ctlz is "32" and the result of the shift is one.
4808     APInt UnknownBits = ~KnownZero;
4809     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4810
4811     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4812     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4813       // Okay, we know that only that the single bit specified by UnknownBits
4814       // could be set on input to the CTLZ node. If this bit is set, the SRL
4815       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4816       // to an SRL/XOR pair, which is likely to simplify more.
4817       unsigned ShAmt = UnknownBits.countTrailingZeros();
4818       SDValue Op = N0.getOperand(0);
4819
4820       if (ShAmt) {
4821         SDLoc DL(N0);
4822         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4823                   DAG.getConstant(ShAmt, DL,
4824                                   getShiftAmountTy(Op.getValueType())));
4825         AddToWorklist(Op.getNode());
4826       }
4827
4828       SDLoc DL(N);
4829       return DAG.getNode(ISD::XOR, DL, VT,
4830                          Op, DAG.getConstant(1, DL, VT));
4831     }
4832   }
4833
4834   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4835   if (N1.getOpcode() == ISD::TRUNCATE &&
4836       N1.getOperand(0).getOpcode() == ISD::AND) {
4837     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4838       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4839   }
4840
4841   // fold operands of srl based on knowledge that the low bits are not
4842   // demanded.
4843   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4844     return SDValue(N, 0);
4845
4846   if (N1C && !N1C->isOpaque())
4847     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4848       return NewSRL;
4849
4850   // Attempt to convert a srl of a load into a narrower zero-extending load.
4851   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4852     return NarrowLoad;
4853
4854   // Here is a common situation. We want to optimize:
4855   //
4856   //   %a = ...
4857   //   %b = and i32 %a, 2
4858   //   %c = srl i32 %b, 1
4859   //   brcond i32 %c ...
4860   //
4861   // into
4862   //
4863   //   %a = ...
4864   //   %b = and %a, 2
4865   //   %c = setcc eq %b, 0
4866   //   brcond %c ...
4867   //
4868   // However when after the source operand of SRL is optimized into AND, the SRL
4869   // itself may not be optimized further. Look for it and add the BRCOND into
4870   // the worklist.
4871   if (N->hasOneUse()) {
4872     SDNode *Use = *N->use_begin();
4873     if (Use->getOpcode() == ISD::BRCOND)
4874       AddToWorklist(Use);
4875     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4876       // Also look pass the truncate.
4877       Use = *Use->use_begin();
4878       if (Use->getOpcode() == ISD::BRCOND)
4879         AddToWorklist(Use);
4880     }
4881   }
4882
4883   return SDValue();
4884 }
4885
4886 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4887   SDValue N0 = N->getOperand(0);
4888   EVT VT = N->getValueType(0);
4889
4890   // fold (bswap c1) -> c2
4891   if (isConstantIntBuildVectorOrConstantInt(N0))
4892     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4893   // fold (bswap (bswap x)) -> x
4894   if (N0.getOpcode() == ISD::BSWAP)
4895     return N0->getOperand(0);
4896   return SDValue();
4897 }
4898
4899 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4900   SDValue N0 = N->getOperand(0);
4901   EVT VT = N->getValueType(0);
4902
4903   // fold (ctlz c1) -> c2
4904   if (isConstantIntBuildVectorOrConstantInt(N0))
4905     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4906   return SDValue();
4907 }
4908
4909 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4910   SDValue N0 = N->getOperand(0);
4911   EVT VT = N->getValueType(0);
4912
4913   // fold (ctlz_zero_undef c1) -> c2
4914   if (isConstantIntBuildVectorOrConstantInt(N0))
4915     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4916   return SDValue();
4917 }
4918
4919 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4920   SDValue N0 = N->getOperand(0);
4921   EVT VT = N->getValueType(0);
4922
4923   // fold (cttz c1) -> c2
4924   if (isConstantIntBuildVectorOrConstantInt(N0))
4925     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4926   return SDValue();
4927 }
4928
4929 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4930   SDValue N0 = N->getOperand(0);
4931   EVT VT = N->getValueType(0);
4932
4933   // fold (cttz_zero_undef c1) -> c2
4934   if (isConstantIntBuildVectorOrConstantInt(N0))
4935     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4936   return SDValue();
4937 }
4938
4939 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4940   SDValue N0 = N->getOperand(0);
4941   EVT VT = N->getValueType(0);
4942
4943   // fold (ctpop c1) -> c2
4944   if (isConstantIntBuildVectorOrConstantInt(N0))
4945     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4946   return SDValue();
4947 }
4948
4949
4950 /// \brief Generate Min/Max node
4951 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4952                                    SDValue True, SDValue False,
4953                                    ISD::CondCode CC, const TargetLowering &TLI,
4954                                    SelectionDAG &DAG) {
4955   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4956     return SDValue();
4957
4958   switch (CC) {
4959   case ISD::SETOLT:
4960   case ISD::SETOLE:
4961   case ISD::SETLT:
4962   case ISD::SETLE:
4963   case ISD::SETULT:
4964   case ISD::SETULE: {
4965     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4966     if (TLI.isOperationLegal(Opcode, VT))
4967       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4968     return SDValue();
4969   }
4970   case ISD::SETOGT:
4971   case ISD::SETOGE:
4972   case ISD::SETGT:
4973   case ISD::SETGE:
4974   case ISD::SETUGT:
4975   case ISD::SETUGE: {
4976     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4977     if (TLI.isOperationLegal(Opcode, VT))
4978       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4979     return SDValue();
4980   }
4981   default:
4982     return SDValue();
4983   }
4984 }
4985
4986 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4987   SDValue N0 = N->getOperand(0);
4988   SDValue N1 = N->getOperand(1);
4989   SDValue N2 = N->getOperand(2);
4990   EVT VT = N->getValueType(0);
4991   EVT VT0 = N0.getValueType();
4992
4993   // fold (select C, X, X) -> X
4994   if (N1 == N2)
4995     return N1;
4996   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4997     // fold (select true, X, Y) -> X
4998     // fold (select false, X, Y) -> Y
4999     return !N0C->isNullValue() ? N1 : N2;
5000   }
5001   // fold (select C, 1, X) -> (or C, X)
5002   if (VT == MVT::i1 && isOneConstant(N1))
5003     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5004   // fold (select C, 0, 1) -> (xor C, 1)
5005   // We can't do this reliably if integer based booleans have different contents
5006   // to floating point based booleans. This is because we can't tell whether we
5007   // have an integer-based boolean or a floating-point-based boolean unless we
5008   // can find the SETCC that produced it and inspect its operands. This is
5009   // fairly easy if C is the SETCC node, but it can potentially be
5010   // undiscoverable (or not reasonably discoverable). For example, it could be
5011   // in another basic block or it could require searching a complicated
5012   // expression.
5013   if (VT.isInteger() &&
5014       (VT0 == MVT::i1 || (VT0.isInteger() &&
5015                           TLI.getBooleanContents(false, false) ==
5016                               TLI.getBooleanContents(false, true) &&
5017                           TLI.getBooleanContents(false, false) ==
5018                               TargetLowering::ZeroOrOneBooleanContent)) &&
5019       isNullConstant(N1) && isOneConstant(N2)) {
5020     SDValue XORNode;
5021     if (VT == VT0) {
5022       SDLoc DL(N);
5023       return DAG.getNode(ISD::XOR, DL, VT0,
5024                          N0, DAG.getConstant(1, DL, VT0));
5025     }
5026     SDLoc DL0(N0);
5027     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5028                           N0, DAG.getConstant(1, DL0, VT0));
5029     AddToWorklist(XORNode.getNode());
5030     if (VT.bitsGT(VT0))
5031       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5032     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5033   }
5034   // fold (select C, 0, X) -> (and (not C), X)
5035   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5036     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5037     AddToWorklist(NOTNode.getNode());
5038     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5039   }
5040   // fold (select C, X, 1) -> (or (not C), X)
5041   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5042     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5043     AddToWorklist(NOTNode.getNode());
5044     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5045   }
5046   // fold (select C, X, 0) -> (and C, X)
5047   if (VT == MVT::i1 && isNullConstant(N2))
5048     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5049   // fold (select X, X, Y) -> (or X, Y)
5050   // fold (select X, 1, Y) -> (or X, Y)
5051   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5052     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5053   // fold (select X, Y, X) -> (and X, Y)
5054   // fold (select X, Y, 0) -> (and X, Y)
5055   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5056     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5057
5058   // If we can fold this based on the true/false value, do so.
5059   if (SimplifySelectOps(N, N1, N2))
5060     return SDValue(N, 0);  // Don't revisit N.
5061
5062   if (VT0 == MVT::i1) {
5063     // The code in this block deals with the following 2 equivalences:
5064     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5065     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5066     // The target can specify its prefered form with the
5067     // shouldNormalizeToSelectSequence() callback. However we always transform
5068     // to the right anyway if we find the inner select exists in the DAG anyway
5069     // and we always transform to the left side if we know that we can further
5070     // optimize the combination of the conditions.
5071     bool normalizeToSequence
5072       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5073     // select (and Cond0, Cond1), X, Y
5074     //   -> select Cond0, (select Cond1, X, Y), Y
5075     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5076       SDValue Cond0 = N0->getOperand(0);
5077       SDValue Cond1 = N0->getOperand(1);
5078       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5079                                         N1.getValueType(), Cond1, N1, N2);
5080       if (normalizeToSequence || !InnerSelect.use_empty())
5081         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5082                            InnerSelect, N2);
5083     }
5084     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5085     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5086       SDValue Cond0 = N0->getOperand(0);
5087       SDValue Cond1 = N0->getOperand(1);
5088       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5089                                         N1.getValueType(), Cond1, N1, N2);
5090       if (normalizeToSequence || !InnerSelect.use_empty())
5091         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5092                            InnerSelect);
5093     }
5094
5095     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5096     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5097       SDValue N1_0 = N1->getOperand(0);
5098       SDValue N1_1 = N1->getOperand(1);
5099       SDValue N1_2 = N1->getOperand(2);
5100       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5101         // Create the actual and node if we can generate good code for it.
5102         if (!normalizeToSequence) {
5103           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5104                                     N0, N1_0);
5105           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5106                              N1_1, N2);
5107         }
5108         // Otherwise see if we can optimize the "and" to a better pattern.
5109         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5110           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5111                              N1_1, N2);
5112       }
5113     }
5114     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5115     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5116       SDValue N2_0 = N2->getOperand(0);
5117       SDValue N2_1 = N2->getOperand(1);
5118       SDValue N2_2 = N2->getOperand(2);
5119       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5120         // Create the actual or node if we can generate good code for it.
5121         if (!normalizeToSequence) {
5122           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5123                                    N0, N2_0);
5124           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5125                              N1, N2_2);
5126         }
5127         // Otherwise see if we can optimize to a better pattern.
5128         if (SDValue Combined = visitORLike(N0, N2_0, N))
5129           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5130                              N1, N2_2);
5131       }
5132     }
5133   }
5134
5135   // fold selects based on a setcc into other things, such as min/max/abs
5136   if (N0.getOpcode() == ISD::SETCC) {
5137     // select x, y (fcmp lt x, y) -> fminnum x, y
5138     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5139     //
5140     // This is OK if we don't care about what happens if either operand is a
5141     // NaN.
5142     //
5143
5144     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5145     // no signed zeros as well as no nans.
5146     const TargetOptions &Options = DAG.getTarget().Options;
5147     if (Options.UnsafeFPMath &&
5148         VT.isFloatingPoint() && N0.hasOneUse() &&
5149         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5150       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5151
5152       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5153                                                 N0.getOperand(1), N1, N2, CC,
5154                                                 TLI, DAG))
5155         return FMinMax;
5156     }
5157
5158     if ((!LegalOperations &&
5159          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5160         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5161       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5162                          N0.getOperand(0), N0.getOperand(1),
5163                          N1, N2, N0.getOperand(2));
5164     return SimplifySelect(SDLoc(N), N0, N1, N2);
5165   }
5166
5167   return SDValue();
5168 }
5169
5170 static
5171 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5172   SDLoc DL(N);
5173   EVT LoVT, HiVT;
5174   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5175
5176   // Split the inputs.
5177   SDValue Lo, Hi, LL, LH, RL, RH;
5178   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5179   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5180
5181   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5182   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5183
5184   return std::make_pair(Lo, Hi);
5185 }
5186
5187 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5188 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5189 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5190   SDLoc dl(N);
5191   SDValue Cond = N->getOperand(0);
5192   SDValue LHS = N->getOperand(1);
5193   SDValue RHS = N->getOperand(2);
5194   EVT VT = N->getValueType(0);
5195   int NumElems = VT.getVectorNumElements();
5196   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5197          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5198          Cond.getOpcode() == ISD::BUILD_VECTOR);
5199
5200   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5201   // binary ones here.
5202   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5203     return SDValue();
5204
5205   // We're sure we have an even number of elements due to the
5206   // concat_vectors we have as arguments to vselect.
5207   // Skip BV elements until we find one that's not an UNDEF
5208   // After we find an UNDEF element, keep looping until we get to half the
5209   // length of the BV and see if all the non-undef nodes are the same.
5210   ConstantSDNode *BottomHalf = nullptr;
5211   for (int i = 0; i < NumElems / 2; ++i) {
5212     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5213       continue;
5214
5215     if (BottomHalf == nullptr)
5216       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5217     else if (Cond->getOperand(i).getNode() != BottomHalf)
5218       return SDValue();
5219   }
5220
5221   // Do the same for the second half of the BuildVector
5222   ConstantSDNode *TopHalf = nullptr;
5223   for (int i = NumElems / 2; i < NumElems; ++i) {
5224     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5225       continue;
5226
5227     if (TopHalf == nullptr)
5228       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5229     else if (Cond->getOperand(i).getNode() != TopHalf)
5230       return SDValue();
5231   }
5232
5233   assert(TopHalf && BottomHalf &&
5234          "One half of the selector was all UNDEFs and the other was all the "
5235          "same value. This should have been addressed before this function.");
5236   return DAG.getNode(
5237       ISD::CONCAT_VECTORS, dl, VT,
5238       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5239       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5240 }
5241
5242 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5243
5244   if (Level >= AfterLegalizeTypes)
5245     return SDValue();
5246
5247   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5248   SDValue Mask = MSC->getMask();
5249   SDValue Data  = MSC->getValue();
5250   SDLoc DL(N);
5251
5252   // If the MSCATTER data type requires splitting and the mask is provided by a
5253   // SETCC, then split both nodes and its operands before legalization. This
5254   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5255   // and enables future optimizations (e.g. min/max pattern matching on X86).
5256   if (Mask.getOpcode() != ISD::SETCC)
5257     return SDValue();
5258
5259   // Check if any splitting is required.
5260   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5261       TargetLowering::TypeSplitVector)
5262     return SDValue();
5263   SDValue MaskLo, MaskHi, Lo, Hi;
5264   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5265
5266   EVT LoVT, HiVT;
5267   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5268
5269   SDValue Chain = MSC->getChain();
5270
5271   EVT MemoryVT = MSC->getMemoryVT();
5272   unsigned Alignment = MSC->getOriginalAlignment();
5273
5274   EVT LoMemVT, HiMemVT;
5275   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5276
5277   SDValue DataLo, DataHi;
5278   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5279
5280   SDValue BasePtr = MSC->getBasePtr();
5281   SDValue IndexLo, IndexHi;
5282   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5283
5284   MachineMemOperand *MMO = DAG.getMachineFunction().
5285     getMachineMemOperand(MSC->getPointerInfo(),
5286                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5287                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5288
5289   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5290   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5291                             DL, OpsLo, MMO);
5292
5293   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5294   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5295                             DL, OpsHi, MMO);
5296
5297   AddToWorklist(Lo.getNode());
5298   AddToWorklist(Hi.getNode());
5299
5300   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5301 }
5302
5303 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5304
5305   if (Level >= AfterLegalizeTypes)
5306     return SDValue();
5307
5308   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5309   SDValue Mask = MST->getMask();
5310   SDValue Data  = MST->getValue();
5311   SDLoc DL(N);
5312
5313   // If the MSTORE data type requires splitting and the mask is provided by a
5314   // SETCC, then split both nodes and its operands before legalization. This
5315   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5316   // and enables future optimizations (e.g. min/max pattern matching on X86).
5317   if (Mask.getOpcode() == ISD::SETCC) {
5318
5319     // Check if any splitting is required.
5320     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5321         TargetLowering::TypeSplitVector)
5322       return SDValue();
5323
5324     SDValue MaskLo, MaskHi, Lo, Hi;
5325     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5326
5327     EVT LoVT, HiVT;
5328     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5329
5330     SDValue Chain = MST->getChain();
5331     SDValue Ptr   = MST->getBasePtr();
5332
5333     EVT MemoryVT = MST->getMemoryVT();
5334     unsigned Alignment = MST->getOriginalAlignment();
5335
5336     // if Alignment is equal to the vector size,
5337     // take the half of it for the second part
5338     unsigned SecondHalfAlignment =
5339       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5340          Alignment/2 : Alignment;
5341
5342     EVT LoMemVT, HiMemVT;
5343     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5344
5345     SDValue DataLo, DataHi;
5346     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5347
5348     MachineMemOperand *MMO = DAG.getMachineFunction().
5349       getMachineMemOperand(MST->getPointerInfo(),
5350                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5351                            Alignment, MST->getAAInfo(), MST->getRanges());
5352
5353     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5354                             MST->isTruncatingStore());
5355
5356     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5357     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5358                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5359
5360     MMO = DAG.getMachineFunction().
5361       getMachineMemOperand(MST->getPointerInfo(),
5362                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5363                            SecondHalfAlignment, MST->getAAInfo(),
5364                            MST->getRanges());
5365
5366     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5367                             MST->isTruncatingStore());
5368
5369     AddToWorklist(Lo.getNode());
5370     AddToWorklist(Hi.getNode());
5371
5372     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5373   }
5374   return SDValue();
5375 }
5376
5377 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5378
5379   if (Level >= AfterLegalizeTypes)
5380     return SDValue();
5381
5382   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5383   SDValue Mask = MGT->getMask();
5384   SDLoc DL(N);
5385
5386   // If the MGATHER result requires splitting and the mask is provided by a
5387   // SETCC, then split both nodes and its operands before legalization. This
5388   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5389   // and enables future optimizations (e.g. min/max pattern matching on X86).
5390
5391   if (Mask.getOpcode() != ISD::SETCC)
5392     return SDValue();
5393
5394   EVT VT = N->getValueType(0);
5395
5396   // Check if any splitting is required.
5397   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5398       TargetLowering::TypeSplitVector)
5399     return SDValue();
5400
5401   SDValue MaskLo, MaskHi, Lo, Hi;
5402   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5403
5404   SDValue Src0 = MGT->getValue();
5405   SDValue Src0Lo, Src0Hi;
5406   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5407
5408   EVT LoVT, HiVT;
5409   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5410
5411   SDValue Chain = MGT->getChain();
5412   EVT MemoryVT = MGT->getMemoryVT();
5413   unsigned Alignment = MGT->getOriginalAlignment();
5414
5415   EVT LoMemVT, HiMemVT;
5416   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5417
5418   SDValue BasePtr = MGT->getBasePtr();
5419   SDValue Index = MGT->getIndex();
5420   SDValue IndexLo, IndexHi;
5421   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5422
5423   MachineMemOperand *MMO = DAG.getMachineFunction().
5424     getMachineMemOperand(MGT->getPointerInfo(),
5425                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5426                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5427
5428   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5429   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5430                             MMO);
5431
5432   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5433   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5434                             MMO);
5435
5436   AddToWorklist(Lo.getNode());
5437   AddToWorklist(Hi.getNode());
5438
5439   // Build a factor node to remember that this load is independent of the
5440   // other one.
5441   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5442                       Hi.getValue(1));
5443
5444   // Legalized the chain result - switch anything that used the old chain to
5445   // use the new one.
5446   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5447
5448   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5449
5450   SDValue RetOps[] = { GatherRes, Chain };
5451   return DAG.getMergeValues(RetOps, DL);
5452 }
5453
5454 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5455
5456   if (Level >= AfterLegalizeTypes)
5457     return SDValue();
5458
5459   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5460   SDValue Mask = MLD->getMask();
5461   SDLoc DL(N);
5462
5463   // If the MLOAD result requires splitting and the mask is provided by a
5464   // SETCC, then split both nodes and its operands before legalization. This
5465   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5466   // and enables future optimizations (e.g. min/max pattern matching on X86).
5467
5468   if (Mask.getOpcode() == ISD::SETCC) {
5469     EVT VT = N->getValueType(0);
5470
5471     // Check if any splitting is required.
5472     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5473         TargetLowering::TypeSplitVector)
5474       return SDValue();
5475
5476     SDValue MaskLo, MaskHi, Lo, Hi;
5477     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5478
5479     SDValue Src0 = MLD->getSrc0();
5480     SDValue Src0Lo, Src0Hi;
5481     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5482
5483     EVT LoVT, HiVT;
5484     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5485
5486     SDValue Chain = MLD->getChain();
5487     SDValue Ptr   = MLD->getBasePtr();
5488     EVT MemoryVT = MLD->getMemoryVT();
5489     unsigned Alignment = MLD->getOriginalAlignment();
5490
5491     // if Alignment is equal to the vector size,
5492     // take the half of it for the second part
5493     unsigned SecondHalfAlignment =
5494       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5495          Alignment/2 : Alignment;
5496
5497     EVT LoMemVT, HiMemVT;
5498     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5499
5500     MachineMemOperand *MMO = DAG.getMachineFunction().
5501     getMachineMemOperand(MLD->getPointerInfo(),
5502                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5503                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5504
5505     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5506                            ISD::NON_EXTLOAD);
5507
5508     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5509     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5510                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5511
5512     MMO = DAG.getMachineFunction().
5513     getMachineMemOperand(MLD->getPointerInfo(),
5514                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5515                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5516
5517     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5518                            ISD::NON_EXTLOAD);
5519
5520     AddToWorklist(Lo.getNode());
5521     AddToWorklist(Hi.getNode());
5522
5523     // Build a factor node to remember that this load is independent of the
5524     // other one.
5525     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5526                         Hi.getValue(1));
5527
5528     // Legalized the chain result - switch anything that used the old chain to
5529     // use the new one.
5530     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5531
5532     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5533
5534     SDValue RetOps[] = { LoadRes, Chain };
5535     return DAG.getMergeValues(RetOps, DL);
5536   }
5537   return SDValue();
5538 }
5539
5540 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5541   SDValue N0 = N->getOperand(0);
5542   SDValue N1 = N->getOperand(1);
5543   SDValue N2 = N->getOperand(2);
5544   SDLoc DL(N);
5545
5546   // Canonicalize integer abs.
5547   // vselect (setg[te] X,  0),  X, -X ->
5548   // vselect (setgt    X, -1),  X, -X ->
5549   // vselect (setl[te] X,  0), -X,  X ->
5550   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5551   if (N0.getOpcode() == ISD::SETCC) {
5552     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5553     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5554     bool isAbs = false;
5555     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5556
5557     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5558          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5559         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5560       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5561     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5562              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5563       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5564
5565     if (isAbs) {
5566       EVT VT = LHS.getValueType();
5567       SDValue Shift = DAG.getNode(
5568           ISD::SRA, DL, VT, LHS,
5569           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5570       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5571       AddToWorklist(Shift.getNode());
5572       AddToWorklist(Add.getNode());
5573       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5574     }
5575   }
5576
5577   if (SimplifySelectOps(N, N1, N2))
5578     return SDValue(N, 0);  // Don't revisit N.
5579
5580   // If the VSELECT result requires splitting and the mask is provided by a
5581   // SETCC, then split both nodes and its operands before legalization. This
5582   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5583   // and enables future optimizations (e.g. min/max pattern matching on X86).
5584   if (N0.getOpcode() == ISD::SETCC) {
5585     EVT VT = N->getValueType(0);
5586
5587     // Check if any splitting is required.
5588     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5589         TargetLowering::TypeSplitVector)
5590       return SDValue();
5591
5592     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5593     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5594     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5595     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5596
5597     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5598     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5599
5600     // Add the new VSELECT nodes to the work list in case they need to be split
5601     // again.
5602     AddToWorklist(Lo.getNode());
5603     AddToWorklist(Hi.getNode());
5604
5605     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5606   }
5607
5608   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5609   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5610     return N1;
5611   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5612   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5613     return N2;
5614
5615   // The ConvertSelectToConcatVector function is assuming both the above
5616   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5617   // and addressed.
5618   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5619       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5620       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5621     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5622       return CV;
5623   }
5624
5625   return SDValue();
5626 }
5627
5628 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5629   SDValue N0 = N->getOperand(0);
5630   SDValue N1 = N->getOperand(1);
5631   SDValue N2 = N->getOperand(2);
5632   SDValue N3 = N->getOperand(3);
5633   SDValue N4 = N->getOperand(4);
5634   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5635
5636   // fold select_cc lhs, rhs, x, x, cc -> x
5637   if (N2 == N3)
5638     return N2;
5639
5640   // Determine if the condition we're dealing with is constant
5641   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5642                               N0, N1, CC, SDLoc(N), false);
5643   if (SCC.getNode()) {
5644     AddToWorklist(SCC.getNode());
5645
5646     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5647       if (!SCCC->isNullValue())
5648         return N2;    // cond always true -> true val
5649       else
5650         return N3;    // cond always false -> false val
5651     } else if (SCC->getOpcode() == ISD::UNDEF) {
5652       // When the condition is UNDEF, just return the first operand. This is
5653       // coherent the DAG creation, no setcc node is created in this case
5654       return N2;
5655     } else if (SCC.getOpcode() == ISD::SETCC) {
5656       // Fold to a simpler select_cc
5657       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5658                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5659                          SCC.getOperand(2));
5660     }
5661   }
5662
5663   // If we can fold this based on the true/false value, do so.
5664   if (SimplifySelectOps(N, N2, N3))
5665     return SDValue(N, 0);  // Don't revisit N.
5666
5667   // fold select_cc into other things, such as min/max/abs
5668   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5669 }
5670
5671 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5672   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5673                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5674                        SDLoc(N));
5675 }
5676
5677 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5678 /// a build_vector of constants.
5679 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5680 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5681 /// Vector extends are not folded if operations are legal; this is to
5682 /// avoid introducing illegal build_vector dag nodes.
5683 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5684                                          SelectionDAG &DAG, bool LegalTypes,
5685                                          bool LegalOperations) {
5686   unsigned Opcode = N->getOpcode();
5687   SDValue N0 = N->getOperand(0);
5688   EVT VT = N->getValueType(0);
5689
5690   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5691          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5692          && "Expected EXTEND dag node in input!");
5693
5694   // fold (sext c1) -> c1
5695   // fold (zext c1) -> c1
5696   // fold (aext c1) -> c1
5697   if (isa<ConstantSDNode>(N0))
5698     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5699
5700   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5701   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5702   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5703   EVT SVT = VT.getScalarType();
5704   if (!(VT.isVector() &&
5705       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5706       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5707     return nullptr;
5708
5709   // We can fold this node into a build_vector.
5710   unsigned VTBits = SVT.getSizeInBits();
5711   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5712   SmallVector<SDValue, 8> Elts;
5713   unsigned NumElts = VT.getVectorNumElements();
5714   SDLoc DL(N);
5715
5716   for (unsigned i=0; i != NumElts; ++i) {
5717     SDValue Op = N0->getOperand(i);
5718     if (Op->getOpcode() == ISD::UNDEF) {
5719       Elts.push_back(DAG.getUNDEF(SVT));
5720       continue;
5721     }
5722
5723     SDLoc DL(Op);
5724     // Get the constant value and if needed trunc it to the size of the type.
5725     // Nodes like build_vector might have constants wider than the scalar type.
5726     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5727     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5728       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5729     else
5730       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5731   }
5732
5733   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5734 }
5735
5736 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5737 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5738 // transformation. Returns true if extension are possible and the above
5739 // mentioned transformation is profitable.
5740 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5741                                     unsigned ExtOpc,
5742                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5743                                     const TargetLowering &TLI) {
5744   bool HasCopyToRegUses = false;
5745   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5746   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5747                             UE = N0.getNode()->use_end();
5748        UI != UE; ++UI) {
5749     SDNode *User = *UI;
5750     if (User == N)
5751       continue;
5752     if (UI.getUse().getResNo() != N0.getResNo())
5753       continue;
5754     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5755     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5756       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5757       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5758         // Sign bits will be lost after a zext.
5759         return false;
5760       bool Add = false;
5761       for (unsigned i = 0; i != 2; ++i) {
5762         SDValue UseOp = User->getOperand(i);
5763         if (UseOp == N0)
5764           continue;
5765         if (!isa<ConstantSDNode>(UseOp))
5766           return false;
5767         Add = true;
5768       }
5769       if (Add)
5770         ExtendNodes.push_back(User);
5771       continue;
5772     }
5773     // If truncates aren't free and there are users we can't
5774     // extend, it isn't worthwhile.
5775     if (!isTruncFree)
5776       return false;
5777     // Remember if this value is live-out.
5778     if (User->getOpcode() == ISD::CopyToReg)
5779       HasCopyToRegUses = true;
5780   }
5781
5782   if (HasCopyToRegUses) {
5783     bool BothLiveOut = false;
5784     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5785          UI != UE; ++UI) {
5786       SDUse &Use = UI.getUse();
5787       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5788         BothLiveOut = true;
5789         break;
5790       }
5791     }
5792     if (BothLiveOut)
5793       // Both unextended and extended values are live out. There had better be
5794       // a good reason for the transformation.
5795       return ExtendNodes.size();
5796   }
5797   return true;
5798 }
5799
5800 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5801                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5802                                   ISD::NodeType ExtType) {
5803   // Extend SetCC uses if necessary.
5804   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5805     SDNode *SetCC = SetCCs[i];
5806     SmallVector<SDValue, 4> Ops;
5807
5808     for (unsigned j = 0; j != 2; ++j) {
5809       SDValue SOp = SetCC->getOperand(j);
5810       if (SOp == Trunc)
5811         Ops.push_back(ExtLoad);
5812       else
5813         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5814     }
5815
5816     Ops.push_back(SetCC->getOperand(2));
5817     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5818   }
5819 }
5820
5821 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5822 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5823   SDValue N0 = N->getOperand(0);
5824   EVT DstVT = N->getValueType(0);
5825   EVT SrcVT = N0.getValueType();
5826
5827   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5828           N->getOpcode() == ISD::ZERO_EXTEND) &&
5829          "Unexpected node type (not an extend)!");
5830
5831   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5832   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5833   //   (v8i32 (sext (v8i16 (load x))))
5834   // into:
5835   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5836   //                          (v4i32 (sextload (x + 16)))))
5837   // Where uses of the original load, i.e.:
5838   //   (v8i16 (load x))
5839   // are replaced with:
5840   //   (v8i16 (truncate
5841   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5842   //                            (v4i32 (sextload (x + 16)))))))
5843   //
5844   // This combine is only applicable to illegal, but splittable, vectors.
5845   // All legal types, and illegal non-vector types, are handled elsewhere.
5846   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5847   //
5848   if (N0->getOpcode() != ISD::LOAD)
5849     return SDValue();
5850
5851   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5852
5853   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5854       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5855       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5856     return SDValue();
5857
5858   SmallVector<SDNode *, 4> SetCCs;
5859   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5860     return SDValue();
5861
5862   ISD::LoadExtType ExtType =
5863       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5864
5865   // Try to split the vector types to get down to legal types.
5866   EVT SplitSrcVT = SrcVT;
5867   EVT SplitDstVT = DstVT;
5868   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5869          SplitSrcVT.getVectorNumElements() > 1) {
5870     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5871     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5872   }
5873
5874   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5875     return SDValue();
5876
5877   SDLoc DL(N);
5878   const unsigned NumSplits =
5879       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5880   const unsigned Stride = SplitSrcVT.getStoreSize();
5881   SmallVector<SDValue, 4> Loads;
5882   SmallVector<SDValue, 4> Chains;
5883
5884   SDValue BasePtr = LN0->getBasePtr();
5885   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5886     const unsigned Offset = Idx * Stride;
5887     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5888
5889     SDValue SplitLoad = DAG.getExtLoad(
5890         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5891         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5892         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5893         Align, LN0->getAAInfo());
5894
5895     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5896                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5897
5898     Loads.push_back(SplitLoad.getValue(0));
5899     Chains.push_back(SplitLoad.getValue(1));
5900   }
5901
5902   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5903   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5904
5905   CombineTo(N, NewValue);
5906
5907   // Replace uses of the original load (before extension)
5908   // with a truncate of the concatenated sextloaded vectors.
5909   SDValue Trunc =
5910       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5911   CombineTo(N0.getNode(), Trunc, NewChain);
5912   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5913                   (ISD::NodeType)N->getOpcode());
5914   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5915 }
5916
5917 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5918   SDValue N0 = N->getOperand(0);
5919   EVT VT = N->getValueType(0);
5920
5921   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5922                                               LegalOperations))
5923     return SDValue(Res, 0);
5924
5925   // fold (sext (sext x)) -> (sext x)
5926   // fold (sext (aext x)) -> (sext x)
5927   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5928     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5929                        N0.getOperand(0));
5930
5931   if (N0.getOpcode() == ISD::TRUNCATE) {
5932     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5933     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5934     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5935       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5936       if (NarrowLoad.getNode() != N0.getNode()) {
5937         CombineTo(N0.getNode(), NarrowLoad);
5938         // CombineTo deleted the truncate, if needed, but not what's under it.
5939         AddToWorklist(oye);
5940       }
5941       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5942     }
5943
5944     // See if the value being truncated is already sign extended.  If so, just
5945     // eliminate the trunc/sext pair.
5946     SDValue Op = N0.getOperand(0);
5947     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5948     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5949     unsigned DestBits = VT.getScalarType().getSizeInBits();
5950     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5951
5952     if (OpBits == DestBits) {
5953       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5954       // bits, it is already ready.
5955       if (NumSignBits > DestBits-MidBits)
5956         return Op;
5957     } else if (OpBits < DestBits) {
5958       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5959       // bits, just sext from i32.
5960       if (NumSignBits > OpBits-MidBits)
5961         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5962     } else {
5963       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5964       // bits, just truncate to i32.
5965       if (NumSignBits > OpBits-MidBits)
5966         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5967     }
5968
5969     // fold (sext (truncate x)) -> (sextinreg x).
5970     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5971                                                  N0.getValueType())) {
5972       if (OpBits < DestBits)
5973         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5974       else if (OpBits > DestBits)
5975         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5976       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5977                          DAG.getValueType(N0.getValueType()));
5978     }
5979   }
5980
5981   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5982   // Only generate vector extloads when 1) they're legal, and 2) they are
5983   // deemed desirable by the target.
5984   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5985       ((!LegalOperations && !VT.isVector() &&
5986         !cast<LoadSDNode>(N0)->isVolatile()) ||
5987        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5988     bool DoXform = true;
5989     SmallVector<SDNode*, 4> SetCCs;
5990     if (!N0.hasOneUse())
5991       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5992     if (VT.isVector())
5993       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5994     if (DoXform) {
5995       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5996       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5997                                        LN0->getChain(),
5998                                        LN0->getBasePtr(), N0.getValueType(),
5999                                        LN0->getMemOperand());
6000       CombineTo(N, ExtLoad);
6001       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6002                                   N0.getValueType(), ExtLoad);
6003       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6004       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6005                       ISD::SIGN_EXTEND);
6006       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6007     }
6008   }
6009
6010   // fold (sext (load x)) to multiple smaller sextloads.
6011   // Only on illegal but splittable vectors.
6012   if (SDValue ExtLoad = CombineExtLoad(N))
6013     return ExtLoad;
6014
6015   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6016   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6017   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6018       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6019     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6020     EVT MemVT = LN0->getMemoryVT();
6021     if ((!LegalOperations && !LN0->isVolatile()) ||
6022         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6023       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6024                                        LN0->getChain(),
6025                                        LN0->getBasePtr(), MemVT,
6026                                        LN0->getMemOperand());
6027       CombineTo(N, ExtLoad);
6028       CombineTo(N0.getNode(),
6029                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6030                             N0.getValueType(), ExtLoad),
6031                 ExtLoad.getValue(1));
6032       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6033     }
6034   }
6035
6036   // fold (sext (and/or/xor (load x), cst)) ->
6037   //      (and/or/xor (sextload x), (sext cst))
6038   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6039        N0.getOpcode() == ISD::XOR) &&
6040       isa<LoadSDNode>(N0.getOperand(0)) &&
6041       N0.getOperand(1).getOpcode() == ISD::Constant &&
6042       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6043       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6044     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6045     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6046       bool DoXform = true;
6047       SmallVector<SDNode*, 4> SetCCs;
6048       if (!N0.hasOneUse())
6049         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6050                                           SetCCs, TLI);
6051       if (DoXform) {
6052         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6053                                          LN0->getChain(), LN0->getBasePtr(),
6054                                          LN0->getMemoryVT(),
6055                                          LN0->getMemOperand());
6056         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6057         Mask = Mask.sext(VT.getSizeInBits());
6058         SDLoc DL(N);
6059         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6060                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6061         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6062                                     SDLoc(N0.getOperand(0)),
6063                                     N0.getOperand(0).getValueType(), ExtLoad);
6064         CombineTo(N, And);
6065         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6066         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6067                         ISD::SIGN_EXTEND);
6068         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6069       }
6070     }
6071   }
6072
6073   if (N0.getOpcode() == ISD::SETCC) {
6074     EVT N0VT = N0.getOperand(0).getValueType();
6075     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6076     // Only do this before legalize for now.
6077     if (VT.isVector() && !LegalOperations &&
6078         TLI.getBooleanContents(N0VT) ==
6079             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6080       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6081       // of the same size as the compared operands. Only optimize sext(setcc())
6082       // if this is the case.
6083       EVT SVT = getSetCCResultType(N0VT);
6084
6085       // We know that the # elements of the results is the same as the
6086       // # elements of the compare (and the # elements of the compare result
6087       // for that matter).  Check to see that they are the same size.  If so,
6088       // we know that the element size of the sext'd result matches the
6089       // element size of the compare operands.
6090       if (VT.getSizeInBits() == SVT.getSizeInBits())
6091         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6092                              N0.getOperand(1),
6093                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6094
6095       // If the desired elements are smaller or larger than the source
6096       // elements we can use a matching integer vector type and then
6097       // truncate/sign extend
6098       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6099       if (SVT == MatchingVectorType) {
6100         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6101                                N0.getOperand(0), N0.getOperand(1),
6102                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6103         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6104       }
6105     }
6106
6107     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6108     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6109     SDLoc DL(N);
6110     SDValue NegOne =
6111       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6112     SDValue SCC =
6113       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6114                        NegOne, DAG.getConstant(0, DL, VT),
6115                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6116     if (SCC.getNode()) return SCC;
6117
6118     if (!VT.isVector()) {
6119       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6120       if (!LegalOperations ||
6121           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6122         SDLoc DL(N);
6123         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6124         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6125                                      N0.getOperand(0), N0.getOperand(1), CC);
6126         return DAG.getSelect(DL, VT, SetCC,
6127                              NegOne, DAG.getConstant(0, DL, VT));
6128       }
6129     }
6130   }
6131
6132   // fold (sext x) -> (zext x) if the sign bit is known zero.
6133   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6134       DAG.SignBitIsZero(N0))
6135     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6136
6137   return SDValue();
6138 }
6139
6140 // isTruncateOf - If N is a truncate of some other value, return true, record
6141 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6142 // This function computes KnownZero to avoid a duplicated call to
6143 // computeKnownBits in the caller.
6144 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6145                          APInt &KnownZero) {
6146   APInt KnownOne;
6147   if (N->getOpcode() == ISD::TRUNCATE) {
6148     Op = N->getOperand(0);
6149     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6150     return true;
6151   }
6152
6153   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6154       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6155     return false;
6156
6157   SDValue Op0 = N->getOperand(0);
6158   SDValue Op1 = N->getOperand(1);
6159   assert(Op0.getValueType() == Op1.getValueType());
6160
6161   if (isNullConstant(Op0))
6162     Op = Op1;
6163   else if (isNullConstant(Op1))
6164     Op = Op0;
6165   else
6166     return false;
6167
6168   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6169
6170   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6171     return false;
6172
6173   return true;
6174 }
6175
6176 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6177   SDValue N0 = N->getOperand(0);
6178   EVT VT = N->getValueType(0);
6179
6180   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6181                                               LegalOperations))
6182     return SDValue(Res, 0);
6183
6184   // fold (zext (zext x)) -> (zext x)
6185   // fold (zext (aext x)) -> (zext x)
6186   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6187     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6188                        N0.getOperand(0));
6189
6190   // fold (zext (truncate x)) -> (zext x) or
6191   //      (zext (truncate x)) -> (truncate x)
6192   // This is valid when the truncated bits of x are already zero.
6193   // FIXME: We should extend this to work for vectors too.
6194   SDValue Op;
6195   APInt KnownZero;
6196   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6197     APInt TruncatedBits =
6198       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6199       APInt(Op.getValueSizeInBits(), 0) :
6200       APInt::getBitsSet(Op.getValueSizeInBits(),
6201                         N0.getValueSizeInBits(),
6202                         std::min(Op.getValueSizeInBits(),
6203                                  VT.getSizeInBits()));
6204     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6205       if (VT.bitsGT(Op.getValueType()))
6206         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6207       if (VT.bitsLT(Op.getValueType()))
6208         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6209
6210       return Op;
6211     }
6212   }
6213
6214   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6215   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6216   if (N0.getOpcode() == ISD::TRUNCATE) {
6217     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6218       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6219       if (NarrowLoad.getNode() != N0.getNode()) {
6220         CombineTo(N0.getNode(), NarrowLoad);
6221         // CombineTo deleted the truncate, if needed, but not what's under it.
6222         AddToWorklist(oye);
6223       }
6224       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6225     }
6226   }
6227
6228   // fold (zext (truncate x)) -> (and x, mask)
6229   if (N0.getOpcode() == ISD::TRUNCATE) {
6230     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6231     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6232     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6233       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6234       if (NarrowLoad.getNode() != N0.getNode()) {
6235         CombineTo(N0.getNode(), NarrowLoad);
6236         // CombineTo deleted the truncate, if needed, but not what's under it.
6237         AddToWorklist(oye);
6238       }
6239       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6240     }
6241
6242     EVT SrcVT = N0.getOperand(0).getValueType();
6243     EVT MinVT = N0.getValueType();
6244
6245     // Try to mask before the extension to avoid having to generate a larger mask,
6246     // possibly over several sub-vectors.
6247     if (SrcVT.bitsLT(VT)) {
6248       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6249                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6250         SDValue Op = N0.getOperand(0);
6251         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6252         AddToWorklist(Op.getNode());
6253         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6254       }
6255     }
6256
6257     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6258       SDValue Op = N0.getOperand(0);
6259       if (SrcVT.bitsLT(VT)) {
6260         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6261         AddToWorklist(Op.getNode());
6262       } else if (SrcVT.bitsGT(VT)) {
6263         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6264         AddToWorklist(Op.getNode());
6265       }
6266       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6267     }
6268   }
6269
6270   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6271   // if either of the casts is not free.
6272   if (N0.getOpcode() == ISD::AND &&
6273       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6274       N0.getOperand(1).getOpcode() == ISD::Constant &&
6275       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6276                            N0.getValueType()) ||
6277        !TLI.isZExtFree(N0.getValueType(), VT))) {
6278     SDValue X = N0.getOperand(0).getOperand(0);
6279     if (X.getValueType().bitsLT(VT)) {
6280       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6281     } else if (X.getValueType().bitsGT(VT)) {
6282       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6283     }
6284     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6285     Mask = Mask.zext(VT.getSizeInBits());
6286     SDLoc DL(N);
6287     return DAG.getNode(ISD::AND, DL, VT,
6288                        X, DAG.getConstant(Mask, DL, VT));
6289   }
6290
6291   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6292   // Only generate vector extloads when 1) they're legal, and 2) they are
6293   // deemed desirable by the target.
6294   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6295       ((!LegalOperations && !VT.isVector() &&
6296         !cast<LoadSDNode>(N0)->isVolatile()) ||
6297        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6298     bool DoXform = true;
6299     SmallVector<SDNode*, 4> SetCCs;
6300     if (!N0.hasOneUse())
6301       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6302     if (VT.isVector())
6303       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6304     if (DoXform) {
6305       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6306       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6307                                        LN0->getChain(),
6308                                        LN0->getBasePtr(), N0.getValueType(),
6309                                        LN0->getMemOperand());
6310       CombineTo(N, ExtLoad);
6311       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6312                                   N0.getValueType(), ExtLoad);
6313       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6314
6315       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6316                       ISD::ZERO_EXTEND);
6317       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6318     }
6319   }
6320
6321   // fold (zext (load x)) to multiple smaller zextloads.
6322   // Only on illegal but splittable vectors.
6323   if (SDValue ExtLoad = CombineExtLoad(N))
6324     return ExtLoad;
6325
6326   // fold (zext (and/or/xor (load x), cst)) ->
6327   //      (and/or/xor (zextload x), (zext cst))
6328   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6329        N0.getOpcode() == ISD::XOR) &&
6330       isa<LoadSDNode>(N0.getOperand(0)) &&
6331       N0.getOperand(1).getOpcode() == ISD::Constant &&
6332       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6333       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6334     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6335     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6336       bool DoXform = true;
6337       SmallVector<SDNode*, 4> SetCCs;
6338       if (!N0.hasOneUse())
6339         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6340                                           SetCCs, TLI);
6341       if (DoXform) {
6342         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6343                                          LN0->getChain(), LN0->getBasePtr(),
6344                                          LN0->getMemoryVT(),
6345                                          LN0->getMemOperand());
6346         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6347         Mask = Mask.zext(VT.getSizeInBits());
6348         SDLoc DL(N);
6349         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6350                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6351         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6352                                     SDLoc(N0.getOperand(0)),
6353                                     N0.getOperand(0).getValueType(), ExtLoad);
6354         CombineTo(N, And);
6355         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6356         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6357                         ISD::ZERO_EXTEND);
6358         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6359       }
6360     }
6361   }
6362
6363   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6364   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6365   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6366       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6367     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6368     EVT MemVT = LN0->getMemoryVT();
6369     if ((!LegalOperations && !LN0->isVolatile()) ||
6370         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6371       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6372                                        LN0->getChain(),
6373                                        LN0->getBasePtr(), MemVT,
6374                                        LN0->getMemOperand());
6375       CombineTo(N, ExtLoad);
6376       CombineTo(N0.getNode(),
6377                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6378                             ExtLoad),
6379                 ExtLoad.getValue(1));
6380       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6381     }
6382   }
6383
6384   if (N0.getOpcode() == ISD::SETCC) {
6385     if (!LegalOperations && VT.isVector() &&
6386         N0.getValueType().getVectorElementType() == MVT::i1) {
6387       EVT N0VT = N0.getOperand(0).getValueType();
6388       if (getSetCCResultType(N0VT) == N0.getValueType())
6389         return SDValue();
6390
6391       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6392       // Only do this before legalize for now.
6393       EVT EltVT = VT.getVectorElementType();
6394       SDLoc DL(N);
6395       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6396                                     DAG.getConstant(1, DL, EltVT));
6397       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6398         // We know that the # elements of the results is the same as the
6399         // # elements of the compare (and the # elements of the compare result
6400         // for that matter).  Check to see that they are the same size.  If so,
6401         // we know that the element size of the sext'd result matches the
6402         // element size of the compare operands.
6403         return DAG.getNode(ISD::AND, DL, VT,
6404                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6405                                          N0.getOperand(1),
6406                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6407                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6408                                        OneOps));
6409
6410       // If the desired elements are smaller or larger than the source
6411       // elements we can use a matching integer vector type and then
6412       // truncate/sign extend
6413       EVT MatchingElementType =
6414         EVT::getIntegerVT(*DAG.getContext(),
6415                           N0VT.getScalarType().getSizeInBits());
6416       EVT MatchingVectorType =
6417         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6418                          N0VT.getVectorNumElements());
6419       SDValue VsetCC =
6420         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6421                       N0.getOperand(1),
6422                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6423       return DAG.getNode(ISD::AND, DL, VT,
6424                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6425                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6426     }
6427
6428     // zext(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()) return SCC;
6435   }
6436
6437   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6438   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6439       isa<ConstantSDNode>(N0.getOperand(1)) &&
6440       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6441       N0.hasOneUse()) {
6442     SDValue ShAmt = N0.getOperand(1);
6443     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6444     if (N0.getOpcode() == ISD::SHL) {
6445       SDValue InnerZExt = N0.getOperand(0);
6446       // If the original shl may be shifting out bits, do not perform this
6447       // transformation.
6448       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6449         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6450       if (ShAmtVal > KnownZeroBits)
6451         return SDValue();
6452     }
6453
6454     SDLoc DL(N);
6455
6456     // Ensure that the shift amount is wide enough for the shifted value.
6457     if (VT.getSizeInBits() >= 256)
6458       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6459
6460     return DAG.getNode(N0.getOpcode(), DL, VT,
6461                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6462                        ShAmt);
6463   }
6464
6465   return SDValue();
6466 }
6467
6468 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6469   SDValue N0 = N->getOperand(0);
6470   EVT VT = N->getValueType(0);
6471
6472   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6473                                               LegalOperations))
6474     return SDValue(Res, 0);
6475
6476   // fold (aext (aext x)) -> (aext x)
6477   // fold (aext (zext x)) -> (zext x)
6478   // fold (aext (sext x)) -> (sext x)
6479   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6480       N0.getOpcode() == ISD::ZERO_EXTEND ||
6481       N0.getOpcode() == ISD::SIGN_EXTEND)
6482     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6483
6484   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6485   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6486   if (N0.getOpcode() == ISD::TRUNCATE) {
6487     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6488       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6489       if (NarrowLoad.getNode() != N0.getNode()) {
6490         CombineTo(N0.getNode(), NarrowLoad);
6491         // CombineTo deleted the truncate, if needed, but not what's under it.
6492         AddToWorklist(oye);
6493       }
6494       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6495     }
6496   }
6497
6498   // fold (aext (truncate x))
6499   if (N0.getOpcode() == ISD::TRUNCATE) {
6500     SDValue TruncOp = N0.getOperand(0);
6501     if (TruncOp.getValueType() == VT)
6502       return TruncOp; // x iff x size == zext size.
6503     if (TruncOp.getValueType().bitsGT(VT))
6504       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6505     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6506   }
6507
6508   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6509   // if the trunc is not free.
6510   if (N0.getOpcode() == ISD::AND &&
6511       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6512       N0.getOperand(1).getOpcode() == ISD::Constant &&
6513       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6514                           N0.getValueType())) {
6515     SDValue X = N0.getOperand(0).getOperand(0);
6516     if (X.getValueType().bitsLT(VT)) {
6517       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6518     } else if (X.getValueType().bitsGT(VT)) {
6519       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6520     }
6521     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6522     Mask = Mask.zext(VT.getSizeInBits());
6523     SDLoc DL(N);
6524     return DAG.getNode(ISD::AND, DL, VT,
6525                        X, DAG.getConstant(Mask, DL, VT));
6526   }
6527
6528   // fold (aext (load x)) -> (aext (truncate (extload x)))
6529   // None of the supported targets knows how to perform load and any_ext
6530   // on vectors in one instruction.  We only perform this transformation on
6531   // scalars.
6532   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6533       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6534       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6535     bool DoXform = true;
6536     SmallVector<SDNode*, 4> SetCCs;
6537     if (!N0.hasOneUse())
6538       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6539     if (DoXform) {
6540       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6541       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6542                                        LN0->getChain(),
6543                                        LN0->getBasePtr(), N0.getValueType(),
6544                                        LN0->getMemOperand());
6545       CombineTo(N, ExtLoad);
6546       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6547                                   N0.getValueType(), ExtLoad);
6548       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6549       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6550                       ISD::ANY_EXTEND);
6551       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6552     }
6553   }
6554
6555   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6556   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6557   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6558   if (N0.getOpcode() == ISD::LOAD &&
6559       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6560       N0.hasOneUse()) {
6561     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6562     ISD::LoadExtType ExtType = LN0->getExtensionType();
6563     EVT MemVT = LN0->getMemoryVT();
6564     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6565       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6566                                        VT, LN0->getChain(), LN0->getBasePtr(),
6567                                        MemVT, LN0->getMemOperand());
6568       CombineTo(N, ExtLoad);
6569       CombineTo(N0.getNode(),
6570                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6571                             N0.getValueType(), ExtLoad),
6572                 ExtLoad.getValue(1));
6573       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6574     }
6575   }
6576
6577   if (N0.getOpcode() == ISD::SETCC) {
6578     // For vectors:
6579     // aext(setcc) -> vsetcc
6580     // aext(setcc) -> truncate(vsetcc)
6581     // aext(setcc) -> aext(vsetcc)
6582     // Only do this before legalize for now.
6583     if (VT.isVector() && !LegalOperations) {
6584       EVT N0VT = N0.getOperand(0).getValueType();
6585         // We know that the # elements of the results is the same as the
6586         // # elements of the compare (and the # elements of the compare result
6587         // for that matter).  Check to see that they are the same size.  If so,
6588         // we know that the element size of the sext'd result matches the
6589         // element size of the compare operands.
6590       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6591         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6592                              N0.getOperand(1),
6593                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6594       // If the desired elements are smaller or larger than the source
6595       // elements we can use a matching integer vector type and then
6596       // truncate/any extend
6597       else {
6598         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6599         SDValue VsetCC =
6600           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6601                         N0.getOperand(1),
6602                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6603         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6604       }
6605     }
6606
6607     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6608     SDLoc DL(N);
6609     SDValue SCC =
6610       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6611                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6612                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6613     if (SCC.getNode())
6614       return SCC;
6615   }
6616
6617   return SDValue();
6618 }
6619
6620 /// See if the specified operand can be simplified with the knowledge that only
6621 /// the bits specified by Mask are used.  If so, return the simpler operand,
6622 /// otherwise return a null SDValue.
6623 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6624   switch (V.getOpcode()) {
6625   default: break;
6626   case ISD::Constant: {
6627     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6628     assert(CV && "Const value should be ConstSDNode.");
6629     const APInt &CVal = CV->getAPIntValue();
6630     APInt NewVal = CVal & Mask;
6631     if (NewVal != CVal)
6632       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6633     break;
6634   }
6635   case ISD::OR:
6636   case ISD::XOR:
6637     // If the LHS or RHS don't contribute bits to the or, drop them.
6638     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6639       return V.getOperand(1);
6640     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6641       return V.getOperand(0);
6642     break;
6643   case ISD::SRL:
6644     // Only look at single-use SRLs.
6645     if (!V.getNode()->hasOneUse())
6646       break;
6647     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6648       // See if we can recursively simplify the LHS.
6649       unsigned Amt = RHSC->getZExtValue();
6650
6651       // Watch out for shift count overflow though.
6652       if (Amt >= Mask.getBitWidth()) break;
6653       APInt NewMask = Mask << Amt;
6654       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6655         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6656                            SimplifyLHS, V.getOperand(1));
6657     }
6658   }
6659   return SDValue();
6660 }
6661
6662 /// If the result of a wider load is shifted to right of N  bits and then
6663 /// truncated to a narrower type and where N is a multiple of number of bits of
6664 /// the narrower type, transform it to a narrower load from address + N / num of
6665 /// bits of new type. If the result is to be extended, also fold the extension
6666 /// to form a extending load.
6667 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6668   unsigned Opc = N->getOpcode();
6669
6670   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6671   SDValue N0 = N->getOperand(0);
6672   EVT VT = N->getValueType(0);
6673   EVT ExtVT = VT;
6674
6675   // This transformation isn't valid for vector loads.
6676   if (VT.isVector())
6677     return SDValue();
6678
6679   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6680   // extended to VT.
6681   if (Opc == ISD::SIGN_EXTEND_INREG) {
6682     ExtType = ISD::SEXTLOAD;
6683     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6684   } else if (Opc == ISD::SRL) {
6685     // Another special-case: SRL is basically zero-extending a narrower value.
6686     ExtType = ISD::ZEXTLOAD;
6687     N0 = SDValue(N, 0);
6688     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6689     if (!N01) return SDValue();
6690     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6691                               VT.getSizeInBits() - N01->getZExtValue());
6692   }
6693   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6694     return SDValue();
6695
6696   unsigned EVTBits = ExtVT.getSizeInBits();
6697
6698   // Do not generate loads of non-round integer types since these can
6699   // be expensive (and would be wrong if the type is not byte sized).
6700   if (!ExtVT.isRound())
6701     return SDValue();
6702
6703   unsigned ShAmt = 0;
6704   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6705     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6706       ShAmt = N01->getZExtValue();
6707       // Is the shift amount a multiple of size of VT?
6708       if ((ShAmt & (EVTBits-1)) == 0) {
6709         N0 = N0.getOperand(0);
6710         // Is the load width a multiple of size of VT?
6711         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6712           return SDValue();
6713       }
6714
6715       // At this point, we must have a load or else we can't do the transform.
6716       if (!isa<LoadSDNode>(N0)) return SDValue();
6717
6718       // Because a SRL must be assumed to *need* to zero-extend the high bits
6719       // (as opposed to anyext the high bits), we can't combine the zextload
6720       // lowering of SRL and an sextload.
6721       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6722         return SDValue();
6723
6724       // If the shift amount is larger than the input type then we're not
6725       // accessing any of the loaded bytes.  If the load was a zextload/extload
6726       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6727       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6728         return SDValue();
6729     }
6730   }
6731
6732   // If the load is shifted left (and the result isn't shifted back right),
6733   // we can fold the truncate through the shift.
6734   unsigned ShLeftAmt = 0;
6735   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6736       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6737     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6738       ShLeftAmt = N01->getZExtValue();
6739       N0 = N0.getOperand(0);
6740     }
6741   }
6742
6743   // If we haven't found a load, we can't narrow it.  Don't transform one with
6744   // multiple uses, this would require adding a new load.
6745   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6746     return SDValue();
6747
6748   // Don't change the width of a volatile load.
6749   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6750   if (LN0->isVolatile())
6751     return SDValue();
6752
6753   // Verify that we are actually reducing a load width here.
6754   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6755     return SDValue();
6756
6757   // For the transform to be legal, the load must produce only two values
6758   // (the value loaded and the chain).  Don't transform a pre-increment
6759   // load, for example, which produces an extra value.  Otherwise the
6760   // transformation is not equivalent, and the downstream logic to replace
6761   // uses gets things wrong.
6762   if (LN0->getNumValues() > 2)
6763     return SDValue();
6764
6765   // If the load that we're shrinking is an extload and we're not just
6766   // discarding the extension we can't simply shrink the load. Bail.
6767   // TODO: It would be possible to merge the extensions in some cases.
6768   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6769       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6770     return SDValue();
6771
6772   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6773     return SDValue();
6774
6775   EVT PtrType = N0.getOperand(1).getValueType();
6776
6777   if (PtrType == MVT::Untyped || PtrType.isExtended())
6778     // It's not possible to generate a constant of extended or untyped type.
6779     return SDValue();
6780
6781   // For big endian targets, we need to adjust the offset to the pointer to
6782   // load the correct bytes.
6783   if (DAG.getDataLayout().isBigEndian()) {
6784     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6785     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6786     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6787   }
6788
6789   uint64_t PtrOff = ShAmt / 8;
6790   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6791   SDLoc DL(LN0);
6792   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6793                                PtrType, LN0->getBasePtr(),
6794                                DAG.getConstant(PtrOff, DL, PtrType));
6795   AddToWorklist(NewPtr.getNode());
6796
6797   SDValue Load;
6798   if (ExtType == ISD::NON_EXTLOAD)
6799     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6800                         LN0->getPointerInfo().getWithOffset(PtrOff),
6801                         LN0->isVolatile(), LN0->isNonTemporal(),
6802                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6803   else
6804     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6805                           LN0->getPointerInfo().getWithOffset(PtrOff),
6806                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6807                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6808
6809   // Replace the old load's chain with the new load's chain.
6810   WorklistRemover DeadNodes(*this);
6811   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6812
6813   // Shift the result left, if we've swallowed a left shift.
6814   SDValue Result = Load;
6815   if (ShLeftAmt != 0) {
6816     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6817     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6818       ShImmTy = VT;
6819     // If the shift amount is as large as the result size (but, presumably,
6820     // no larger than the source) then the useful bits of the result are
6821     // zero; we can't simply return the shortened shift, because the result
6822     // of that operation is undefined.
6823     SDLoc DL(N0);
6824     if (ShLeftAmt >= VT.getSizeInBits())
6825       Result = DAG.getConstant(0, DL, VT);
6826     else
6827       Result = DAG.getNode(ISD::SHL, DL, VT,
6828                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6829   }
6830
6831   // Return the new loaded value.
6832   return Result;
6833 }
6834
6835 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6836   SDValue N0 = N->getOperand(0);
6837   SDValue N1 = N->getOperand(1);
6838   EVT VT = N->getValueType(0);
6839   EVT EVT = cast<VTSDNode>(N1)->getVT();
6840   unsigned VTBits = VT.getScalarType().getSizeInBits();
6841   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6842
6843   if (N0.isUndef())
6844     return DAG.getUNDEF(VT);
6845
6846   // fold (sext_in_reg c1) -> c1
6847   if (isConstantIntBuildVectorOrConstantInt(N0))
6848     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6849
6850   // If the input is already sign extended, just drop the extension.
6851   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6852     return N0;
6853
6854   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6855   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6856       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6857     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6858                        N0.getOperand(0), N1);
6859
6860   // fold (sext_in_reg (sext x)) -> (sext x)
6861   // fold (sext_in_reg (aext x)) -> (sext x)
6862   // if x is small enough.
6863   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6864     SDValue N00 = N0.getOperand(0);
6865     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6866         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6867       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6868   }
6869
6870   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6871   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6872     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6873
6874   // fold operands of sext_in_reg based on knowledge that the top bits are not
6875   // demanded.
6876   if (SimplifyDemandedBits(SDValue(N, 0)))
6877     return SDValue(N, 0);
6878
6879   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6880   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6881   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6882     return NarrowLoad;
6883
6884   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6885   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6886   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6887   if (N0.getOpcode() == ISD::SRL) {
6888     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6889       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6890         // We can turn this into an SRA iff the input to the SRL is already sign
6891         // extended enough.
6892         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6893         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6894           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6895                              N0.getOperand(0), N0.getOperand(1));
6896       }
6897   }
6898
6899   // fold (sext_inreg (extload x)) -> (sextload x)
6900   if (ISD::isEXTLoad(N0.getNode()) &&
6901       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6902       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6903       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6904        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6905     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6906     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6907                                      LN0->getChain(),
6908                                      LN0->getBasePtr(), EVT,
6909                                      LN0->getMemOperand());
6910     CombineTo(N, ExtLoad);
6911     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6912     AddToWorklist(ExtLoad.getNode());
6913     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6914   }
6915   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6916   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6917       N0.hasOneUse() &&
6918       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6919       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6920        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6921     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6922     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6923                                      LN0->getChain(),
6924                                      LN0->getBasePtr(), EVT,
6925                                      LN0->getMemOperand());
6926     CombineTo(N, ExtLoad);
6927     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6928     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6929   }
6930
6931   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6932   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6933     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6934                                        N0.getOperand(1), false);
6935     if (BSwap.getNode())
6936       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6937                          BSwap, N1);
6938   }
6939
6940   return SDValue();
6941 }
6942
6943 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6944   SDValue N0 = N->getOperand(0);
6945   EVT VT = N->getValueType(0);
6946
6947   if (N0.getOpcode() == ISD::UNDEF)
6948     return DAG.getUNDEF(VT);
6949
6950   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6951                                               LegalOperations))
6952     return SDValue(Res, 0);
6953
6954   return SDValue();
6955 }
6956
6957 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6958   SDValue N0 = N->getOperand(0);
6959   EVT VT = N->getValueType(0);
6960   bool isLE = DAG.getDataLayout().isLittleEndian();
6961
6962   // noop truncate
6963   if (N0.getValueType() == N->getValueType(0))
6964     return N0;
6965   // fold (truncate c1) -> c1
6966   if (isConstantIntBuildVectorOrConstantInt(N0))
6967     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6968   // fold (truncate (truncate x)) -> (truncate x)
6969   if (N0.getOpcode() == ISD::TRUNCATE)
6970     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6971   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6972   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6973       N0.getOpcode() == ISD::SIGN_EXTEND ||
6974       N0.getOpcode() == ISD::ANY_EXTEND) {
6975     if (N0.getOperand(0).getValueType().bitsLT(VT))
6976       // if the source is smaller than the dest, we still need an extend
6977       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6978                          N0.getOperand(0));
6979     if (N0.getOperand(0).getValueType().bitsGT(VT))
6980       // if the source is larger than the dest, than we just need the truncate
6981       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6982     // if the source and dest are the same type, we can drop both the extend
6983     // and the truncate.
6984     return N0.getOperand(0);
6985   }
6986
6987   // Fold extract-and-trunc into a narrow extract. For example:
6988   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6989   //   i32 y = TRUNCATE(i64 x)
6990   //        -- becomes --
6991   //   v16i8 b = BITCAST (v2i64 val)
6992   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6993   //
6994   // Note: We only run this optimization after type legalization (which often
6995   // creates this pattern) and before operation legalization after which
6996   // we need to be more careful about the vector instructions that we generate.
6997   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6998       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6999
7000     EVT VecTy = N0.getOperand(0).getValueType();
7001     EVT ExTy = N0.getValueType();
7002     EVT TrTy = N->getValueType(0);
7003
7004     unsigned NumElem = VecTy.getVectorNumElements();
7005     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7006
7007     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7008     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7009
7010     SDValue EltNo = N0->getOperand(1);
7011     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7012       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7013       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7014       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7015
7016       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7017                               NVT, N0.getOperand(0));
7018
7019       SDLoc DL(N);
7020       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7021                          DL, TrTy, V,
7022                          DAG.getConstant(Index, DL, IndexTy));
7023     }
7024   }
7025
7026   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7027   if (N0.getOpcode() == ISD::SELECT) {
7028     EVT SrcVT = N0.getValueType();
7029     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7030         TLI.isTruncateFree(SrcVT, VT)) {
7031       SDLoc SL(N0);
7032       SDValue Cond = N0.getOperand(0);
7033       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7034       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7035       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7036     }
7037   }
7038
7039   // Fold a series of buildvector, bitcast, and truncate if possible.
7040   // For example fold
7041   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7042   //   (2xi32 (buildvector x, y)).
7043   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7044       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7045       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7046       N0.getOperand(0).hasOneUse()) {
7047
7048     SDValue BuildVect = N0.getOperand(0);
7049     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7050     EVT TruncVecEltTy = VT.getVectorElementType();
7051
7052     // Check that the element types match.
7053     if (BuildVectEltTy == TruncVecEltTy) {
7054       // Now we only need to compute the offset of the truncated elements.
7055       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7056       unsigned TruncVecNumElts = VT.getVectorNumElements();
7057       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7058
7059       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7060              "Invalid number of elements");
7061
7062       SmallVector<SDValue, 8> Opnds;
7063       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7064         Opnds.push_back(BuildVect.getOperand(i));
7065
7066       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7067     }
7068   }
7069
7070   // See if we can simplify the input to this truncate through knowledge that
7071   // only the low bits are being used.
7072   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7073   // Currently we only perform this optimization on scalars because vectors
7074   // may have different active low bits.
7075   if (!VT.isVector()) {
7076     SDValue Shorter =
7077       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7078                                                VT.getSizeInBits()));
7079     if (Shorter.getNode())
7080       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7081   }
7082   // fold (truncate (load x)) -> (smaller load x)
7083   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7084   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7085     if (SDValue Reduced = ReduceLoadWidth(N))
7086       return Reduced;
7087
7088     // Handle the case where the load remains an extending load even
7089     // after truncation.
7090     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7091       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7092       if (!LN0->isVolatile() &&
7093           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7094         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7095                                          VT, LN0->getChain(), LN0->getBasePtr(),
7096                                          LN0->getMemoryVT(),
7097                                          LN0->getMemOperand());
7098         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7099         return NewLoad;
7100       }
7101     }
7102   }
7103   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7104   // where ... are all 'undef'.
7105   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7106     SmallVector<EVT, 8> VTs;
7107     SDValue V;
7108     unsigned Idx = 0;
7109     unsigned NumDefs = 0;
7110
7111     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7112       SDValue X = N0.getOperand(i);
7113       if (X.getOpcode() != ISD::UNDEF) {
7114         V = X;
7115         Idx = i;
7116         NumDefs++;
7117       }
7118       // Stop if more than one members are non-undef.
7119       if (NumDefs > 1)
7120         break;
7121       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7122                                      VT.getVectorElementType(),
7123                                      X.getValueType().getVectorNumElements()));
7124     }
7125
7126     if (NumDefs == 0)
7127       return DAG.getUNDEF(VT);
7128
7129     if (NumDefs == 1) {
7130       assert(V.getNode() && "The single defined operand is empty!");
7131       SmallVector<SDValue, 8> Opnds;
7132       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7133         if (i != Idx) {
7134           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7135           continue;
7136         }
7137         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7138         AddToWorklist(NV.getNode());
7139         Opnds.push_back(NV);
7140       }
7141       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7142     }
7143   }
7144
7145   // Simplify the operands using demanded-bits information.
7146   if (!VT.isVector() &&
7147       SimplifyDemandedBits(SDValue(N, 0)))
7148     return SDValue(N, 0);
7149
7150   return SDValue();
7151 }
7152
7153 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7154   SDValue Elt = N->getOperand(i);
7155   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7156     return Elt.getNode();
7157   return Elt.getOperand(Elt.getResNo()).getNode();
7158 }
7159
7160 /// build_pair (load, load) -> load
7161 /// if load locations are consecutive.
7162 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7163   assert(N->getOpcode() == ISD::BUILD_PAIR);
7164
7165   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7166   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7167   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7168       LD1->getAddressSpace() != LD2->getAddressSpace())
7169     return SDValue();
7170   EVT LD1VT = LD1->getValueType(0);
7171
7172   if (ISD::isNON_EXTLoad(LD2) &&
7173       LD2->hasOneUse() &&
7174       // If both are volatile this would reduce the number of volatile loads.
7175       // If one is volatile it might be ok, but play conservative and bail out.
7176       !LD1->isVolatile() &&
7177       !LD2->isVolatile() &&
7178       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7179     unsigned Align = LD1->getAlignment();
7180     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7181         VT.getTypeForEVT(*DAG.getContext()));
7182
7183     if (NewAlign <= Align &&
7184         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7185       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7186                          LD1->getBasePtr(), LD1->getPointerInfo(),
7187                          false, false, false, Align);
7188   }
7189
7190   return SDValue();
7191 }
7192
7193 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7194   SDValue N0 = N->getOperand(0);
7195   EVT VT = N->getValueType(0);
7196
7197   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7198   // Only do this before legalize, since afterward the target may be depending
7199   // on the bitconvert.
7200   // First check to see if this is all constant.
7201   if (!LegalTypes &&
7202       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7203       VT.isVector()) {
7204     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7205
7206     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7207     assert(!DestEltVT.isVector() &&
7208            "Element type of vector ValueType must not be vector!");
7209     if (isSimple)
7210       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7211   }
7212
7213   // If the input is a constant, let getNode fold it.
7214   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7215     // If we can't allow illegal operations, we need to check that this is just
7216     // a fp -> int or int -> conversion and that the resulting operation will
7217     // be legal.
7218     if (!LegalOperations ||
7219         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7220          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7221         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7222          TLI.isOperationLegal(ISD::Constant, VT)))
7223       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7224   }
7225
7226   // (conv (conv x, t1), t2) -> (conv x, t2)
7227   if (N0.getOpcode() == ISD::BITCAST)
7228     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7229                        N0.getOperand(0));
7230
7231   // fold (conv (load x)) -> (load (conv*)x)
7232   // If the resultant load doesn't need a higher alignment than the original!
7233   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7234       // Do not change the width of a volatile load.
7235       !cast<LoadSDNode>(N0)->isVolatile() &&
7236       // Do not remove the cast if the types differ in endian layout.
7237       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7238           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7239       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7240       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7241     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7242     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7243         VT.getTypeForEVT(*DAG.getContext()));
7244     unsigned OrigAlign = LN0->getAlignment();
7245
7246     if (Align <= OrigAlign) {
7247       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7248                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7249                                  LN0->isVolatile(), LN0->isNonTemporal(),
7250                                  LN0->isInvariant(), OrigAlign,
7251                                  LN0->getAAInfo());
7252       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7253       return Load;
7254     }
7255   }
7256
7257   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7258   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7259   // This often reduces constant pool loads.
7260   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7261        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7262       N0.getNode()->hasOneUse() && VT.isInteger() &&
7263       !VT.isVector() && !N0.getValueType().isVector()) {
7264     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7265                                   N0.getOperand(0));
7266     AddToWorklist(NewConv.getNode());
7267
7268     SDLoc DL(N);
7269     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7270     if (N0.getOpcode() == ISD::FNEG)
7271       return DAG.getNode(ISD::XOR, DL, VT,
7272                          NewConv, DAG.getConstant(SignBit, DL, VT));
7273     assert(N0.getOpcode() == ISD::FABS);
7274     return DAG.getNode(ISD::AND, DL, VT,
7275                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7276   }
7277
7278   // fold (bitconvert (fcopysign cst, x)) ->
7279   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7280   // Note that we don't handle (copysign x, cst) because this can always be
7281   // folded to an fneg or fabs.
7282   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7283       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7284       VT.isInteger() && !VT.isVector()) {
7285     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7286     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7287     if (isTypeLegal(IntXVT)) {
7288       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7289                               IntXVT, N0.getOperand(1));
7290       AddToWorklist(X.getNode());
7291
7292       // If X has a different width than the result/lhs, sext it or truncate it.
7293       unsigned VTWidth = VT.getSizeInBits();
7294       if (OrigXWidth < VTWidth) {
7295         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7296         AddToWorklist(X.getNode());
7297       } else if (OrigXWidth > VTWidth) {
7298         // To get the sign bit in the right place, we have to shift it right
7299         // before truncating.
7300         SDLoc DL(X);
7301         X = DAG.getNode(ISD::SRL, DL,
7302                         X.getValueType(), X,
7303                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7304                                         X.getValueType()));
7305         AddToWorklist(X.getNode());
7306         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7307         AddToWorklist(X.getNode());
7308       }
7309
7310       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7311       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7312                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7313       AddToWorklist(X.getNode());
7314
7315       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7316                                 VT, N0.getOperand(0));
7317       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7318                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7319       AddToWorklist(Cst.getNode());
7320
7321       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7322     }
7323   }
7324
7325   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7326   if (N0.getOpcode() == ISD::BUILD_PAIR)
7327     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7328       return CombineLD;
7329
7330   // Remove double bitcasts from shuffles - this is often a legacy of
7331   // XformToShuffleWithZero being used to combine bitmaskings (of
7332   // float vectors bitcast to integer vectors) into shuffles.
7333   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7334   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7335       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7336       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7337       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7338     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7339
7340     // If operands are a bitcast, peek through if it casts the original VT.
7341     // If operands are a constant, just bitcast back to original VT.
7342     auto PeekThroughBitcast = [&](SDValue Op) {
7343       if (Op.getOpcode() == ISD::BITCAST &&
7344           Op.getOperand(0).getValueType() == VT)
7345         return SDValue(Op.getOperand(0));
7346       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7347           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7348         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7349       return SDValue();
7350     };
7351
7352     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7353     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7354     if (!(SV0 && SV1))
7355       return SDValue();
7356
7357     int MaskScale =
7358         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7359     SmallVector<int, 8> NewMask;
7360     for (int M : SVN->getMask())
7361       for (int i = 0; i != MaskScale; ++i)
7362         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7363
7364     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7365     if (!LegalMask) {
7366       std::swap(SV0, SV1);
7367       ShuffleVectorSDNode::commuteMask(NewMask);
7368       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7369     }
7370
7371     if (LegalMask)
7372       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7373   }
7374
7375   return SDValue();
7376 }
7377
7378 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7379   EVT VT = N->getValueType(0);
7380   return CombineConsecutiveLoads(N, VT);
7381 }
7382
7383 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7384 /// operands. DstEltVT indicates the destination element value type.
7385 SDValue DAGCombiner::
7386 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7387   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7388
7389   // If this is already the right type, we're done.
7390   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7391
7392   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7393   unsigned DstBitSize = DstEltVT.getSizeInBits();
7394
7395   // If this is a conversion of N elements of one type to N elements of another
7396   // type, convert each element.  This handles FP<->INT cases.
7397   if (SrcBitSize == DstBitSize) {
7398     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7399                               BV->getValueType(0).getVectorNumElements());
7400
7401     // Due to the FP element handling below calling this routine recursively,
7402     // we can end up with a scalar-to-vector node here.
7403     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7404       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7405                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7406                                      DstEltVT, BV->getOperand(0)));
7407
7408     SmallVector<SDValue, 8> Ops;
7409     for (SDValue Op : BV->op_values()) {
7410       // If the vector element type is not legal, the BUILD_VECTOR operands
7411       // are promoted and implicitly truncated.  Make that explicit here.
7412       if (Op.getValueType() != SrcEltVT)
7413         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7414       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7415                                 DstEltVT, Op));
7416       AddToWorklist(Ops.back().getNode());
7417     }
7418     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7419   }
7420
7421   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7422   // handle annoying details of growing/shrinking FP values, we convert them to
7423   // int first.
7424   if (SrcEltVT.isFloatingPoint()) {
7425     // Convert the input float vector to a int vector where the elements are the
7426     // same sizes.
7427     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7428     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7429     SrcEltVT = IntVT;
7430   }
7431
7432   // Now we know the input is an integer vector.  If the output is a FP type,
7433   // convert to integer first, then to FP of the right size.
7434   if (DstEltVT.isFloatingPoint()) {
7435     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7436     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7437
7438     // Next, convert to FP elements of the same size.
7439     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7440   }
7441
7442   SDLoc DL(BV);
7443
7444   // Okay, we know the src/dst types are both integers of differing types.
7445   // Handling growing first.
7446   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7447   if (SrcBitSize < DstBitSize) {
7448     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7449
7450     SmallVector<SDValue, 8> Ops;
7451     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7452          i += NumInputsPerOutput) {
7453       bool isLE = DAG.getDataLayout().isLittleEndian();
7454       APInt NewBits = APInt(DstBitSize, 0);
7455       bool EltIsUndef = true;
7456       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7457         // Shift the previously computed bits over.
7458         NewBits <<= SrcBitSize;
7459         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7460         if (Op.getOpcode() == ISD::UNDEF) continue;
7461         EltIsUndef = false;
7462
7463         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7464                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7465       }
7466
7467       if (EltIsUndef)
7468         Ops.push_back(DAG.getUNDEF(DstEltVT));
7469       else
7470         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7471     }
7472
7473     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7474     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7475   }
7476
7477   // Finally, this must be the case where we are shrinking elements: each input
7478   // turns into multiple outputs.
7479   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7480   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7481                             NumOutputsPerInput*BV->getNumOperands());
7482   SmallVector<SDValue, 8> Ops;
7483
7484   for (const SDValue &Op : BV->op_values()) {
7485     if (Op.getOpcode() == ISD::UNDEF) {
7486       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7487       continue;
7488     }
7489
7490     APInt OpVal = cast<ConstantSDNode>(Op)->
7491                   getAPIntValue().zextOrTrunc(SrcBitSize);
7492
7493     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7494       APInt ThisVal = OpVal.trunc(DstBitSize);
7495       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7496       OpVal = OpVal.lshr(DstBitSize);
7497     }
7498
7499     // For big endian targets, swap the order of the pieces of each element.
7500     if (DAG.getDataLayout().isBigEndian())
7501       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7502   }
7503
7504   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7505 }
7506
7507 /// Try to perform FMA combining on a given FADD node.
7508 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7509   SDValue N0 = N->getOperand(0);
7510   SDValue N1 = N->getOperand(1);
7511   EVT VT = N->getValueType(0);
7512   SDLoc SL(N);
7513
7514   const TargetOptions &Options = DAG.getTarget().Options;
7515   bool AllowFusion =
7516       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7517
7518   // Floating-point multiply-add with intermediate rounding.
7519   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7520
7521   // Floating-point multiply-add without intermediate rounding.
7522   bool HasFMA =
7523       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7524       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7525
7526   // No valid opcode, do not combine.
7527   if (!HasFMAD && !HasFMA)
7528     return SDValue();
7529
7530   // Always prefer FMAD to FMA for precision.
7531   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7532   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7533   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7534
7535   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7536   // prefer to fold the multiply with fewer uses.
7537   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7538       N1.getOpcode() == ISD::FMUL) {
7539     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7540       std::swap(N0, N1);
7541   }
7542
7543   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7544   if (N0.getOpcode() == ISD::FMUL &&
7545       (Aggressive || N0->hasOneUse())) {
7546     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7547                        N0.getOperand(0), N0.getOperand(1), N1);
7548   }
7549
7550   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7551   // Note: Commutes FADD operands.
7552   if (N1.getOpcode() == ISD::FMUL &&
7553       (Aggressive || N1->hasOneUse())) {
7554     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7555                        N1.getOperand(0), N1.getOperand(1), N0);
7556   }
7557
7558   // Look through FP_EXTEND nodes to do more combining.
7559   if (AllowFusion && LookThroughFPExt) {
7560     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7561     if (N0.getOpcode() == ISD::FP_EXTEND) {
7562       SDValue N00 = N0.getOperand(0);
7563       if (N00.getOpcode() == ISD::FMUL)
7564         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7565                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7566                                        N00.getOperand(0)),
7567                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7568                                        N00.getOperand(1)), N1);
7569     }
7570
7571     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7572     // Note: Commutes FADD operands.
7573     if (N1.getOpcode() == ISD::FP_EXTEND) {
7574       SDValue N10 = N1.getOperand(0);
7575       if (N10.getOpcode() == ISD::FMUL)
7576         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7577                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7578                                        N10.getOperand(0)),
7579                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7580                                        N10.getOperand(1)), N0);
7581     }
7582   }
7583
7584   // More folding opportunities when target permits.
7585   if ((AllowFusion || HasFMAD)  && Aggressive) {
7586     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7587     if (N0.getOpcode() == PreferredFusedOpcode &&
7588         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7589       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7590                          N0.getOperand(0), N0.getOperand(1),
7591                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                                      N0.getOperand(2).getOperand(0),
7593                                      N0.getOperand(2).getOperand(1),
7594                                      N1));
7595     }
7596
7597     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7598     if (N1->getOpcode() == PreferredFusedOpcode &&
7599         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7600       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7601                          N1.getOperand(0), N1.getOperand(1),
7602                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7603                                      N1.getOperand(2).getOperand(0),
7604                                      N1.getOperand(2).getOperand(1),
7605                                      N0));
7606     }
7607
7608     if (AllowFusion && LookThroughFPExt) {
7609       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7610       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7611       auto FoldFAddFMAFPExtFMul = [&] (
7612           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7613         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7614                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7615                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7616                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7617                                        Z));
7618       };
7619       if (N0.getOpcode() == PreferredFusedOpcode) {
7620         SDValue N02 = N0.getOperand(2);
7621         if (N02.getOpcode() == ISD::FP_EXTEND) {
7622           SDValue N020 = N02.getOperand(0);
7623           if (N020.getOpcode() == ISD::FMUL)
7624             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7625                                         N020.getOperand(0), N020.getOperand(1),
7626                                         N1);
7627         }
7628       }
7629
7630       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7631       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7632       // FIXME: This turns two single-precision and one double-precision
7633       // operation into two double-precision operations, which might not be
7634       // interesting for all targets, especially GPUs.
7635       auto FoldFAddFPExtFMAFMul = [&] (
7636           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7637         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7639                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7640                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7641                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7642                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7643                                        Z));
7644       };
7645       if (N0.getOpcode() == ISD::FP_EXTEND) {
7646         SDValue N00 = N0.getOperand(0);
7647         if (N00.getOpcode() == PreferredFusedOpcode) {
7648           SDValue N002 = N00.getOperand(2);
7649           if (N002.getOpcode() == ISD::FMUL)
7650             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7651                                         N002.getOperand(0), N002.getOperand(1),
7652                                         N1);
7653         }
7654       }
7655
7656       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7657       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7658       if (N1.getOpcode() == PreferredFusedOpcode) {
7659         SDValue N12 = N1.getOperand(2);
7660         if (N12.getOpcode() == ISD::FP_EXTEND) {
7661           SDValue N120 = N12.getOperand(0);
7662           if (N120.getOpcode() == ISD::FMUL)
7663             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7664                                         N120.getOperand(0), N120.getOperand(1),
7665                                         N0);
7666         }
7667       }
7668
7669       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7670       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7671       // FIXME: This turns two single-precision and one double-precision
7672       // operation into two double-precision operations, which might not be
7673       // interesting for all targets, especially GPUs.
7674       if (N1.getOpcode() == ISD::FP_EXTEND) {
7675         SDValue N10 = N1.getOperand(0);
7676         if (N10.getOpcode() == PreferredFusedOpcode) {
7677           SDValue N102 = N10.getOperand(2);
7678           if (N102.getOpcode() == ISD::FMUL)
7679             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7680                                         N102.getOperand(0), N102.getOperand(1),
7681                                         N0);
7682         }
7683       }
7684     }
7685   }
7686
7687   return SDValue();
7688 }
7689
7690 /// Try to perform FMA combining on a given FSUB node.
7691 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7692   SDValue N0 = N->getOperand(0);
7693   SDValue N1 = N->getOperand(1);
7694   EVT VT = N->getValueType(0);
7695   SDLoc SL(N);
7696
7697   const TargetOptions &Options = DAG.getTarget().Options;
7698   bool AllowFusion =
7699       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7700
7701   // Floating-point multiply-add with intermediate rounding.
7702   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7703
7704   // Floating-point multiply-add without intermediate rounding.
7705   bool HasFMA =
7706       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7707       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7708
7709   // No valid opcode, do not combine.
7710   if (!HasFMAD && !HasFMA)
7711     return SDValue();
7712
7713   // Always prefer FMAD to FMA for precision.
7714   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7715   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7716   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7717
7718   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7719   if (N0.getOpcode() == ISD::FMUL &&
7720       (Aggressive || N0->hasOneUse())) {
7721     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7722                        N0.getOperand(0), N0.getOperand(1),
7723                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7724   }
7725
7726   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7727   // Note: Commutes FSUB operands.
7728   if (N1.getOpcode() == ISD::FMUL &&
7729       (Aggressive || N1->hasOneUse()))
7730     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7731                        DAG.getNode(ISD::FNEG, SL, VT,
7732                                    N1.getOperand(0)),
7733                        N1.getOperand(1), N0);
7734
7735   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7736   if (N0.getOpcode() == ISD::FNEG &&
7737       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7738       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7739     SDValue N00 = N0.getOperand(0).getOperand(0);
7740     SDValue N01 = N0.getOperand(0).getOperand(1);
7741     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7742                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7743                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7744   }
7745
7746   // Look through FP_EXTEND nodes to do more combining.
7747   if (AllowFusion && LookThroughFPExt) {
7748     // fold (fsub (fpext (fmul x, y)), z)
7749     //   -> (fma (fpext x), (fpext y), (fneg z))
7750     if (N0.getOpcode() == ISD::FP_EXTEND) {
7751       SDValue N00 = N0.getOperand(0);
7752       if (N00.getOpcode() == ISD::FMUL)
7753         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7754                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7755                                        N00.getOperand(0)),
7756                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7757                                        N00.getOperand(1)),
7758                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7759     }
7760
7761     // fold (fsub x, (fpext (fmul y, z)))
7762     //   -> (fma (fneg (fpext y)), (fpext z), x)
7763     // Note: Commutes FSUB operands.
7764     if (N1.getOpcode() == ISD::FP_EXTEND) {
7765       SDValue N10 = N1.getOperand(0);
7766       if (N10.getOpcode() == ISD::FMUL)
7767         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7768                            DAG.getNode(ISD::FNEG, SL, VT,
7769                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7770                                                    N10.getOperand(0))),
7771                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772                                        N10.getOperand(1)),
7773                            N0);
7774     }
7775
7776     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7777     //   -> (fneg (fma (fpext x), (fpext y), z))
7778     // Note: This could be removed with appropriate canonicalization of the
7779     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7780     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7781     // from implementing the canonicalization in visitFSUB.
7782     if (N0.getOpcode() == ISD::FP_EXTEND) {
7783       SDValue N00 = N0.getOperand(0);
7784       if (N00.getOpcode() == ISD::FNEG) {
7785         SDValue N000 = N00.getOperand(0);
7786         if (N000.getOpcode() == ISD::FMUL) {
7787           return DAG.getNode(ISD::FNEG, SL, VT,
7788                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7789                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7790                                                      N000.getOperand(0)),
7791                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7792                                                      N000.getOperand(1)),
7793                                          N1));
7794         }
7795       }
7796     }
7797
7798     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7799     //   -> (fneg (fma (fpext x)), (fpext y), z)
7800     // Note: This could be removed with appropriate canonicalization of the
7801     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7802     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7803     // from implementing the canonicalization in visitFSUB.
7804     if (N0.getOpcode() == ISD::FNEG) {
7805       SDValue N00 = N0.getOperand(0);
7806       if (N00.getOpcode() == ISD::FP_EXTEND) {
7807         SDValue N000 = N00.getOperand(0);
7808         if (N000.getOpcode() == ISD::FMUL) {
7809           return DAG.getNode(ISD::FNEG, SL, VT,
7810                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7811                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7812                                                      N000.getOperand(0)),
7813                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7814                                                      N000.getOperand(1)),
7815                                          N1));
7816         }
7817       }
7818     }
7819
7820   }
7821
7822   // More folding opportunities when target permits.
7823   if ((AllowFusion || HasFMAD) && Aggressive) {
7824     // fold (fsub (fma x, y, (fmul u, v)), z)
7825     //   -> (fma x, y (fma u, v, (fneg z)))
7826     if (N0.getOpcode() == PreferredFusedOpcode &&
7827         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7828       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7829                          N0.getOperand(0), N0.getOperand(1),
7830                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7831                                      N0.getOperand(2).getOperand(0),
7832                                      N0.getOperand(2).getOperand(1),
7833                                      DAG.getNode(ISD::FNEG, SL, VT,
7834                                                  N1)));
7835     }
7836
7837     // fold (fsub x, (fma y, z, (fmul u, v)))
7838     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7839     if (N1.getOpcode() == PreferredFusedOpcode &&
7840         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7841       SDValue N20 = N1.getOperand(2).getOperand(0);
7842       SDValue N21 = N1.getOperand(2).getOperand(1);
7843       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7844                          DAG.getNode(ISD::FNEG, SL, VT,
7845                                      N1.getOperand(0)),
7846                          N1.getOperand(1),
7847                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7848                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7849
7850                                      N21, N0));
7851     }
7852
7853     if (AllowFusion && LookThroughFPExt) {
7854       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7855       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7856       if (N0.getOpcode() == PreferredFusedOpcode) {
7857         SDValue N02 = N0.getOperand(2);
7858         if (N02.getOpcode() == ISD::FP_EXTEND) {
7859           SDValue N020 = N02.getOperand(0);
7860           if (N020.getOpcode() == ISD::FMUL)
7861             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7862                                N0.getOperand(0), N0.getOperand(1),
7863                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7864                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7865                                                        N020.getOperand(0)),
7866                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7867                                                        N020.getOperand(1)),
7868                                            DAG.getNode(ISD::FNEG, SL, VT,
7869                                                        N1)));
7870         }
7871       }
7872
7873       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7874       //   -> (fma (fpext x), (fpext y),
7875       //           (fma (fpext u), (fpext v), (fneg z)))
7876       // FIXME: This turns two single-precision and one double-precision
7877       // operation into two double-precision operations, which might not be
7878       // interesting for all targets, especially GPUs.
7879       if (N0.getOpcode() == ISD::FP_EXTEND) {
7880         SDValue N00 = N0.getOperand(0);
7881         if (N00.getOpcode() == PreferredFusedOpcode) {
7882           SDValue N002 = N00.getOperand(2);
7883           if (N002.getOpcode() == ISD::FMUL)
7884             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7885                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7886                                            N00.getOperand(0)),
7887                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888                                            N00.getOperand(1)),
7889                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7890                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7891                                                        N002.getOperand(0)),
7892                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7893                                                        N002.getOperand(1)),
7894                                            DAG.getNode(ISD::FNEG, SL, VT,
7895                                                        N1)));
7896         }
7897       }
7898
7899       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7900       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7901       if (N1.getOpcode() == PreferredFusedOpcode &&
7902         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7903         SDValue N120 = N1.getOperand(2).getOperand(0);
7904         if (N120.getOpcode() == ISD::FMUL) {
7905           SDValue N1200 = N120.getOperand(0);
7906           SDValue N1201 = N120.getOperand(1);
7907           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7908                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7909                              N1.getOperand(1),
7910                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7911                                          DAG.getNode(ISD::FNEG, SL, VT,
7912                                              DAG.getNode(ISD::FP_EXTEND, SL,
7913                                                          VT, N1200)),
7914                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7915                                                      N1201),
7916                                          N0));
7917         }
7918       }
7919
7920       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7921       //   -> (fma (fneg (fpext y)), (fpext z),
7922       //           (fma (fneg (fpext u)), (fpext v), x))
7923       // FIXME: This turns two single-precision and one double-precision
7924       // operation into two double-precision operations, which might not be
7925       // interesting for all targets, especially GPUs.
7926       if (N1.getOpcode() == ISD::FP_EXTEND &&
7927         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7928         SDValue N100 = N1.getOperand(0).getOperand(0);
7929         SDValue N101 = N1.getOperand(0).getOperand(1);
7930         SDValue N102 = N1.getOperand(0).getOperand(2);
7931         if (N102.getOpcode() == ISD::FMUL) {
7932           SDValue N1020 = N102.getOperand(0);
7933           SDValue N1021 = N102.getOperand(1);
7934           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7935                              DAG.getNode(ISD::FNEG, SL, VT,
7936                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7937                                                      N100)),
7938                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7939                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7940                                          DAG.getNode(ISD::FNEG, SL, VT,
7941                                              DAG.getNode(ISD::FP_EXTEND, SL,
7942                                                          VT, N1020)),
7943                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7944                                                      N1021),
7945                                          N0));
7946         }
7947       }
7948     }
7949   }
7950
7951   return SDValue();
7952 }
7953
7954 /// Try to perform FMA combining on a given FMUL node.
7955 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7956   SDValue N0 = N->getOperand(0);
7957   SDValue N1 = N->getOperand(1);
7958   EVT VT = N->getValueType(0);
7959   SDLoc SL(N);
7960
7961   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7962
7963   const TargetOptions &Options = DAG.getTarget().Options;
7964   bool AllowFusion =
7965       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7966
7967   // Floating-point multiply-add with intermediate rounding.
7968   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7969
7970   // Floating-point multiply-add without intermediate rounding.
7971   bool HasFMA =
7972       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7973       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7974
7975   // No valid opcode, do not combine.
7976   if (!HasFMAD && !HasFMA)
7977     return SDValue();
7978
7979   // Always prefer FMAD to FMA for precision.
7980   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7981   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7982
7983   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7984   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7985   auto FuseFADD = [&](SDValue X, SDValue Y) {
7986     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7987       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7988       if (XC1 && XC1->isExactlyValue(+1.0))
7989         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7990       if (XC1 && XC1->isExactlyValue(-1.0))
7991         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7992                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7993     }
7994     return SDValue();
7995   };
7996
7997   if (SDValue FMA = FuseFADD(N0, N1))
7998     return FMA;
7999   if (SDValue FMA = FuseFADD(N1, N0))
8000     return FMA;
8001
8002   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8003   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8004   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8005   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8006   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8007     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8008       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8009       if (XC0 && XC0->isExactlyValue(+1.0))
8010         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8011                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8012                            Y);
8013       if (XC0 && XC0->isExactlyValue(-1.0))
8014         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8015                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8016                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8017
8018       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8019       if (XC1 && XC1->isExactlyValue(+1.0))
8020         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8021                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8022       if (XC1 && XC1->isExactlyValue(-1.0))
8023         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8024     }
8025     return SDValue();
8026   };
8027
8028   if (SDValue FMA = FuseFSUB(N0, N1))
8029     return FMA;
8030   if (SDValue FMA = FuseFSUB(N1, N0))
8031     return FMA;
8032
8033   return SDValue();
8034 }
8035
8036 SDValue DAGCombiner::visitFADD(SDNode *N) {
8037   SDValue N0 = N->getOperand(0);
8038   SDValue N1 = N->getOperand(1);
8039   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8040   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8041   EVT VT = N->getValueType(0);
8042   SDLoc DL(N);
8043   const TargetOptions &Options = DAG.getTarget().Options;
8044   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8045
8046   // fold vector ops
8047   if (VT.isVector())
8048     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8049       return FoldedVOp;
8050
8051   // fold (fadd c1, c2) -> c1 + c2
8052   if (N0CFP && N1CFP)
8053     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8054
8055   // canonicalize constant to RHS
8056   if (N0CFP && !N1CFP)
8057     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8058
8059   // fold (fadd A, (fneg B)) -> (fsub A, B)
8060   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8061       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8062     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8063                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8064
8065   // fold (fadd (fneg A), B) -> (fsub B, A)
8066   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8067       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8068     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8069                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8070
8071   // If 'unsafe math' is enabled, fold lots of things.
8072   if (Options.UnsafeFPMath) {
8073     // No FP constant should be created after legalization as Instruction
8074     // Selection pass has a hard time dealing with FP constants.
8075     bool AllowNewConst = (Level < AfterLegalizeDAG);
8076
8077     // fold (fadd A, 0) -> A
8078     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8079       if (N1C->isZero())
8080         return N0;
8081
8082     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8083     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8084         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8085       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8086                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8087                                      Flags),
8088                          Flags);
8089
8090     // If allowed, fold (fadd (fneg x), x) -> 0.0
8091     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8092       return DAG.getConstantFP(0.0, DL, VT);
8093
8094     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8095     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8096       return DAG.getConstantFP(0.0, DL, VT);
8097
8098     // We can fold chains of FADD's of the same value into multiplications.
8099     // This transform is not safe in general because we are reducing the number
8100     // of rounding steps.
8101     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8102       if (N0.getOpcode() == ISD::FMUL) {
8103         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8104         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8105
8106         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8107         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8108           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8109                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8110           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8111         }
8112
8113         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8114         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8115             N1.getOperand(0) == N1.getOperand(1) &&
8116             N0.getOperand(0) == N1.getOperand(0)) {
8117           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8118                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8119           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8120         }
8121       }
8122
8123       if (N1.getOpcode() == ISD::FMUL) {
8124         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8125         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8126
8127         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8128         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8129           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8130                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8131           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8132         }
8133
8134         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8135         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8136             N0.getOperand(0) == N0.getOperand(1) &&
8137             N1.getOperand(0) == N0.getOperand(0)) {
8138           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8139                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8140           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8141         }
8142       }
8143
8144       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8145         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8146         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8147         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8148             (N0.getOperand(0) == N1)) {
8149           return DAG.getNode(ISD::FMUL, DL, VT,
8150                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8151         }
8152       }
8153
8154       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8155         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8156         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8157         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8158             N1.getOperand(0) == N0) {
8159           return DAG.getNode(ISD::FMUL, DL, VT,
8160                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8161         }
8162       }
8163
8164       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8165       if (AllowNewConst &&
8166           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8167           N0.getOperand(0) == N0.getOperand(1) &&
8168           N1.getOperand(0) == N1.getOperand(1) &&
8169           N0.getOperand(0) == N1.getOperand(0)) {
8170         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8171                            DAG.getConstantFP(4.0, DL, VT), Flags);
8172       }
8173     }
8174   } // enable-unsafe-fp-math
8175
8176   // FADD -> FMA combines:
8177   if (SDValue Fused = visitFADDForFMACombine(N)) {
8178     AddToWorklist(Fused.getNode());
8179     return Fused;
8180   }
8181
8182   return SDValue();
8183 }
8184
8185 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8186   SDValue N0 = N->getOperand(0);
8187   SDValue N1 = N->getOperand(1);
8188   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8189   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8190   EVT VT = N->getValueType(0);
8191   SDLoc dl(N);
8192   const TargetOptions &Options = DAG.getTarget().Options;
8193   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8194
8195   // fold vector ops
8196   if (VT.isVector())
8197     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8198       return FoldedVOp;
8199
8200   // fold (fsub c1, c2) -> c1-c2
8201   if (N0CFP && N1CFP)
8202     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8203
8204   // fold (fsub A, (fneg B)) -> (fadd A, B)
8205   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8206     return DAG.getNode(ISD::FADD, dl, VT, N0,
8207                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8208
8209   // If 'unsafe math' is enabled, fold lots of things.
8210   if (Options.UnsafeFPMath) {
8211     // (fsub A, 0) -> A
8212     if (N1CFP && N1CFP->isZero())
8213       return N0;
8214
8215     // (fsub 0, B) -> -B
8216     if (N0CFP && N0CFP->isZero()) {
8217       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8218         return GetNegatedExpression(N1, DAG, LegalOperations);
8219       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8220         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8221     }
8222
8223     // (fsub x, x) -> 0.0
8224     if (N0 == N1)
8225       return DAG.getConstantFP(0.0f, dl, VT);
8226
8227     // (fsub x, (fadd x, y)) -> (fneg y)
8228     // (fsub x, (fadd y, x)) -> (fneg y)
8229     if (N1.getOpcode() == ISD::FADD) {
8230       SDValue N10 = N1->getOperand(0);
8231       SDValue N11 = N1->getOperand(1);
8232
8233       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8234         return GetNegatedExpression(N11, DAG, LegalOperations);
8235
8236       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8237         return GetNegatedExpression(N10, DAG, LegalOperations);
8238     }
8239   }
8240
8241   // FSUB -> FMA combines:
8242   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8243     AddToWorklist(Fused.getNode());
8244     return Fused;
8245   }
8246
8247   return SDValue();
8248 }
8249
8250 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8251   SDValue N0 = N->getOperand(0);
8252   SDValue N1 = N->getOperand(1);
8253   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8254   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8255   EVT VT = N->getValueType(0);
8256   SDLoc DL(N);
8257   const TargetOptions &Options = DAG.getTarget().Options;
8258   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8259
8260   // fold vector ops
8261   if (VT.isVector()) {
8262     // This just handles C1 * C2 for vectors. Other vector folds are below.
8263     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8264       return FoldedVOp;
8265   }
8266
8267   // fold (fmul c1, c2) -> c1*c2
8268   if (N0CFP && N1CFP)
8269     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8270
8271   // canonicalize constant to RHS
8272   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8273      !isConstantFPBuildVectorOrConstantFP(N1))
8274     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8275
8276   // fold (fmul A, 1.0) -> A
8277   if (N1CFP && N1CFP->isExactlyValue(1.0))
8278     return N0;
8279
8280   if (Options.UnsafeFPMath) {
8281     // fold (fmul A, 0) -> 0
8282     if (N1CFP && N1CFP->isZero())
8283       return N1;
8284
8285     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8286     if (N0.getOpcode() == ISD::FMUL) {
8287       // Fold scalars or any vector constants (not just splats).
8288       // This fold is done in general by InstCombine, but extra fmul insts
8289       // may have been generated during lowering.
8290       SDValue N00 = N0.getOperand(0);
8291       SDValue N01 = N0.getOperand(1);
8292       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8293       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8294       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8295
8296       // Check 1: Make sure that the first operand of the inner multiply is NOT
8297       // a constant. Otherwise, we may induce infinite looping.
8298       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8299         // Check 2: Make sure that the second operand of the inner multiply and
8300         // the second operand of the outer multiply are constants.
8301         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8302             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8303           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8304           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8305         }
8306       }
8307     }
8308
8309     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8310     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8311     // during an early run of DAGCombiner can prevent folding with fmuls
8312     // inserted during lowering.
8313     if (N0.getOpcode() == ISD::FADD &&
8314         (N0.getOperand(0) == N0.getOperand(1)) &&
8315         N0.hasOneUse()) {
8316       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8317       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8318       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8319     }
8320   }
8321
8322   // fold (fmul X, 2.0) -> (fadd X, X)
8323   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8324     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8325
8326   // fold (fmul X, -1.0) -> (fneg X)
8327   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8328     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8329       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8330
8331   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8332   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8333     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8334       // Both can be negated for free, check to see if at least one is cheaper
8335       // negated.
8336       if (LHSNeg == 2 || RHSNeg == 2)
8337         return DAG.getNode(ISD::FMUL, DL, VT,
8338                            GetNegatedExpression(N0, DAG, LegalOperations),
8339                            GetNegatedExpression(N1, DAG, LegalOperations),
8340                            Flags);
8341     }
8342   }
8343
8344   // FMUL -> FMA combines:
8345   if (SDValue Fused = visitFMULForFMACombine(N)) {
8346     AddToWorklist(Fused.getNode());
8347     return Fused;
8348   }
8349
8350   return SDValue();
8351 }
8352
8353 SDValue DAGCombiner::visitFMA(SDNode *N) {
8354   SDValue N0 = N->getOperand(0);
8355   SDValue N1 = N->getOperand(1);
8356   SDValue N2 = N->getOperand(2);
8357   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8358   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8359   EVT VT = N->getValueType(0);
8360   SDLoc dl(N);
8361   const TargetOptions &Options = DAG.getTarget().Options;
8362
8363   // Constant fold FMA.
8364   if (isa<ConstantFPSDNode>(N0) &&
8365       isa<ConstantFPSDNode>(N1) &&
8366       isa<ConstantFPSDNode>(N2)) {
8367     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8368   }
8369
8370   if (Options.UnsafeFPMath) {
8371     if (N0CFP && N0CFP->isZero())
8372       return N2;
8373     if (N1CFP && N1CFP->isZero())
8374       return N2;
8375   }
8376   // TODO: The FMA node should have flags that propagate to these nodes.
8377   if (N0CFP && N0CFP->isExactlyValue(1.0))
8378     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8379   if (N1CFP && N1CFP->isExactlyValue(1.0))
8380     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8381
8382   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8383   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8384      !isConstantFPBuildVectorOrConstantFP(N1))
8385     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8386
8387   // TODO: FMA nodes should have flags that propagate to the created nodes.
8388   // For now, create a Flags object for use with all unsafe math transforms.
8389   SDNodeFlags Flags;
8390   Flags.setUnsafeAlgebra(true);
8391
8392   if (Options.UnsafeFPMath) {
8393     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8394     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8395         isConstantFPBuildVectorOrConstantFP(N1) &&
8396         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8397       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8398                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8399                                      &Flags), &Flags);
8400     }
8401
8402     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8403     if (N0.getOpcode() == ISD::FMUL &&
8404         isConstantFPBuildVectorOrConstantFP(N1) &&
8405         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8406       return DAG.getNode(ISD::FMA, dl, VT,
8407                          N0.getOperand(0),
8408                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8409                                      &Flags),
8410                          N2);
8411     }
8412   }
8413
8414   // (fma x, 1, y) -> (fadd x, y)
8415   // (fma x, -1, y) -> (fadd (fneg x), y)
8416   if (N1CFP) {
8417     if (N1CFP->isExactlyValue(1.0))
8418       // TODO: The FMA node should have flags that propagate to this node.
8419       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8420
8421     if (N1CFP->isExactlyValue(-1.0) &&
8422         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8423       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8424       AddToWorklist(RHSNeg.getNode());
8425       // TODO: The FMA node should have flags that propagate to this node.
8426       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8427     }
8428   }
8429
8430   if (Options.UnsafeFPMath) {
8431     // (fma x, c, x) -> (fmul x, (c+1))
8432     if (N1CFP && N0 == N2) {
8433     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8434                          DAG.getNode(ISD::FADD, dl, VT,
8435                                      N1, DAG.getConstantFP(1.0, dl, VT),
8436                                      &Flags), &Flags);
8437     }
8438
8439     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8440     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8441       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8442                          DAG.getNode(ISD::FADD, dl, VT,
8443                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8444                                      &Flags), &Flags);
8445     }
8446   }
8447
8448   return SDValue();
8449 }
8450
8451 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8452 // reciprocal.
8453 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8454 // Notice that this is not always beneficial. One reason is different target
8455 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8456 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8457 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8458 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8459   if (!DAG.getTarget().Options.UnsafeFPMath)
8460     return SDValue();
8461
8462   // Skip if current node is a reciprocal.
8463   SDValue N0 = N->getOperand(0);
8464   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8465   if (N0CFP && N0CFP->isExactlyValue(1.0))
8466     return SDValue();
8467
8468   // Exit early if the target does not want this transform or if there can't
8469   // possibly be enough uses of the divisor to make the transform worthwhile.
8470   SDValue N1 = N->getOperand(1);
8471   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8472   if (!MinUses || N1->use_size() < MinUses)
8473     return SDValue();
8474
8475   // Find all FDIV users of the same divisor.
8476   // Use a set because duplicates may be present in the user list.
8477   SetVector<SDNode *> Users;
8478   for (auto *U : N1->uses())
8479     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8480       Users.insert(U);
8481
8482   // Now that we have the actual number of divisor uses, make sure it meets
8483   // the minimum threshold specified by the target.
8484   if (Users.size() < MinUses)
8485     return SDValue();
8486
8487   EVT VT = N->getValueType(0);
8488   SDLoc DL(N);
8489   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8490   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8491   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8492
8493   // Dividend / Divisor -> Dividend * Reciprocal
8494   for (auto *U : Users) {
8495     SDValue Dividend = U->getOperand(0);
8496     if (Dividend != FPOne) {
8497       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8498                                     Reciprocal, Flags);
8499       CombineTo(U, NewNode);
8500     } else if (U != Reciprocal.getNode()) {
8501       // In the absence of fast-math-flags, this user node is always the
8502       // same node as Reciprocal, but with FMF they may be different nodes.
8503       CombineTo(U, Reciprocal);
8504     }
8505   }
8506   return SDValue(N, 0);  // N was replaced.
8507 }
8508
8509 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8510   SDValue N0 = N->getOperand(0);
8511   SDValue N1 = N->getOperand(1);
8512   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8513   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8514   EVT VT = N->getValueType(0);
8515   SDLoc DL(N);
8516   const TargetOptions &Options = DAG.getTarget().Options;
8517   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8518
8519   // fold vector ops
8520   if (VT.isVector())
8521     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8522       return FoldedVOp;
8523
8524   // fold (fdiv c1, c2) -> c1/c2
8525   if (N0CFP && N1CFP)
8526     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8527
8528   if (Options.UnsafeFPMath) {
8529     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8530     if (N1CFP) {
8531       // Compute the reciprocal 1.0 / c2.
8532       APFloat N1APF = N1CFP->getValueAPF();
8533       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8534       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8535       // Only do the transform if the reciprocal is a legal fp immediate that
8536       // isn't too nasty (eg NaN, denormal, ...).
8537       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8538           (!LegalOperations ||
8539            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8540            // backend)... we should handle this gracefully after Legalize.
8541            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8542            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8543            TLI.isFPImmLegal(Recip, VT)))
8544         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8545                            DAG.getConstantFP(Recip, DL, VT), Flags);
8546     }
8547
8548     // If this FDIV is part of a reciprocal square root, it may be folded
8549     // into a target-specific square root estimate instruction.
8550     if (N1.getOpcode() == ISD::FSQRT) {
8551       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8552         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8553       }
8554     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8555                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8556       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8557                                           Flags)) {
8558         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8559         AddToWorklist(RV.getNode());
8560         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8561       }
8562     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8563                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8564       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8565                                           Flags)) {
8566         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8567         AddToWorklist(RV.getNode());
8568         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8569       }
8570     } else if (N1.getOpcode() == ISD::FMUL) {
8571       // Look through an FMUL. Even though this won't remove the FDIV directly,
8572       // it's still worthwhile to get rid of the FSQRT if possible.
8573       SDValue SqrtOp;
8574       SDValue OtherOp;
8575       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8576         SqrtOp = N1.getOperand(0);
8577         OtherOp = N1.getOperand(1);
8578       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8579         SqrtOp = N1.getOperand(1);
8580         OtherOp = N1.getOperand(0);
8581       }
8582       if (SqrtOp.getNode()) {
8583         // We found a FSQRT, so try to make this fold:
8584         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8585         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8586           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8587           AddToWorklist(RV.getNode());
8588           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8589         }
8590       }
8591     }
8592
8593     // Fold into a reciprocal estimate and multiply instead of a real divide.
8594     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8595       AddToWorklist(RV.getNode());
8596       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8597     }
8598   }
8599
8600   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8601   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8602     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8603       // Both can be negated for free, check to see if at least one is cheaper
8604       // negated.
8605       if (LHSNeg == 2 || RHSNeg == 2)
8606         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8607                            GetNegatedExpression(N0, DAG, LegalOperations),
8608                            GetNegatedExpression(N1, DAG, LegalOperations),
8609                            Flags);
8610     }
8611   }
8612
8613   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8614     return CombineRepeatedDivisors;
8615
8616   return SDValue();
8617 }
8618
8619 SDValue DAGCombiner::visitFREM(SDNode *N) {
8620   SDValue N0 = N->getOperand(0);
8621   SDValue N1 = N->getOperand(1);
8622   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8623   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8624   EVT VT = N->getValueType(0);
8625
8626   // fold (frem c1, c2) -> fmod(c1,c2)
8627   if (N0CFP && N1CFP)
8628     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8629                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8630
8631   return SDValue();
8632 }
8633
8634 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8635   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8636     return SDValue();
8637
8638   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8639   // For now, create a Flags object for use with all unsafe math transforms.
8640   SDNodeFlags Flags;
8641   Flags.setUnsafeAlgebra(true);
8642
8643   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8644   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8645   if (!RV)
8646     return SDValue();
8647
8648   EVT VT = RV.getValueType();
8649   SDLoc DL(N);
8650   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8651   AddToWorklist(RV.getNode());
8652
8653   // Unfortunately, RV is now NaN if the input was exactly 0.
8654   // Select out this case and force the answer to 0.
8655   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8656   EVT CCVT = getSetCCResultType(VT);
8657   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8658   AddToWorklist(ZeroCmp.getNode());
8659   AddToWorklist(RV.getNode());
8660
8661   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8662                      ZeroCmp, Zero, RV);
8663 }
8664
8665 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8666   SDValue N0 = N->getOperand(0);
8667   SDValue N1 = N->getOperand(1);
8668   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8669   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8670   EVT VT = N->getValueType(0);
8671
8672   if (N0CFP && N1CFP)  // Constant fold
8673     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8674
8675   if (N1CFP) {
8676     const APFloat& V = N1CFP->getValueAPF();
8677     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8678     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8679     if (!V.isNegative()) {
8680       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8681         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8682     } else {
8683       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8684         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8685                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8686     }
8687   }
8688
8689   // copysign(fabs(x), y) -> copysign(x, y)
8690   // copysign(fneg(x), y) -> copysign(x, y)
8691   // copysign(copysign(x,z), y) -> copysign(x, y)
8692   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8693       N0.getOpcode() == ISD::FCOPYSIGN)
8694     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8695                        N0.getOperand(0), N1);
8696
8697   // copysign(x, abs(y)) -> abs(x)
8698   if (N1.getOpcode() == ISD::FABS)
8699     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8700
8701   // copysign(x, copysign(y,z)) -> copysign(x, z)
8702   if (N1.getOpcode() == ISD::FCOPYSIGN)
8703     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8704                        N0, N1.getOperand(1));
8705
8706   // copysign(x, fp_extend(y)) -> copysign(x, y)
8707   // copysign(x, fp_round(y)) -> copysign(x, y)
8708   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8709     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8710                        N0, N1.getOperand(0));
8711
8712   return SDValue();
8713 }
8714
8715 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8716   SDValue N0 = N->getOperand(0);
8717   EVT VT = N->getValueType(0);
8718   EVT OpVT = N0.getValueType();
8719
8720   // fold (sint_to_fp c1) -> c1fp
8721   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8722       // ...but only if the target supports immediate floating-point values
8723       (!LegalOperations ||
8724        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8725     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8726
8727   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8728   // but UINT_TO_FP is legal on this target, try to convert.
8729   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8730       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8731     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8732     if (DAG.SignBitIsZero(N0))
8733       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8734   }
8735
8736   // The next optimizations are desirable only if SELECT_CC can be lowered.
8737   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8738     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8739     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8740         !VT.isVector() &&
8741         (!LegalOperations ||
8742          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8743       SDLoc DL(N);
8744       SDValue Ops[] =
8745         { N0.getOperand(0), N0.getOperand(1),
8746           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8747           N0.getOperand(2) };
8748       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8749     }
8750
8751     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8752     //      (select_cc x, y, 1.0, 0.0,, cc)
8753     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8754         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8755         (!LegalOperations ||
8756          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8757       SDLoc DL(N);
8758       SDValue Ops[] =
8759         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8760           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8761           N0.getOperand(0).getOperand(2) };
8762       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8763     }
8764   }
8765
8766   return SDValue();
8767 }
8768
8769 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8770   SDValue N0 = N->getOperand(0);
8771   EVT VT = N->getValueType(0);
8772   EVT OpVT = N0.getValueType();
8773
8774   // fold (uint_to_fp c1) -> c1fp
8775   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8776       // ...but only if the target supports immediate floating-point values
8777       (!LegalOperations ||
8778        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8779     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8780
8781   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8782   // but SINT_TO_FP is legal on this target, try to convert.
8783   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8784       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8785     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8786     if (DAG.SignBitIsZero(N0))
8787       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8788   }
8789
8790   // The next optimizations are desirable only if SELECT_CC can be lowered.
8791   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8792     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8793
8794     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8795         (!LegalOperations ||
8796          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8797       SDLoc DL(N);
8798       SDValue Ops[] =
8799         { N0.getOperand(0), N0.getOperand(1),
8800           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8801           N0.getOperand(2) };
8802       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8803     }
8804   }
8805
8806   return SDValue();
8807 }
8808
8809 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8810 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8811   SDValue N0 = N->getOperand(0);
8812   EVT VT = N->getValueType(0);
8813
8814   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8815     return SDValue();
8816
8817   SDValue Src = N0.getOperand(0);
8818   EVT SrcVT = Src.getValueType();
8819   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8820   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8821
8822   // We can safely assume the conversion won't overflow the output range,
8823   // because (for example) (uint8_t)18293.f is undefined behavior.
8824
8825   // Since we can assume the conversion won't overflow, our decision as to
8826   // whether the input will fit in the float should depend on the minimum
8827   // of the input range and output range.
8828
8829   // This means this is also safe for a signed input and unsigned output, since
8830   // a negative input would lead to undefined behavior.
8831   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8832   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8833   unsigned ActualSize = std::min(InputSize, OutputSize);
8834   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8835
8836   // We can only fold away the float conversion if the input range can be
8837   // represented exactly in the float range.
8838   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8839     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8840       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8841                                                        : ISD::ZERO_EXTEND;
8842       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8843     }
8844     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8845       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8846     if (SrcVT == VT)
8847       return Src;
8848     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8849   }
8850   return SDValue();
8851 }
8852
8853 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8854   SDValue N0 = N->getOperand(0);
8855   EVT VT = N->getValueType(0);
8856
8857   // fold (fp_to_sint c1fp) -> c1
8858   if (isConstantFPBuildVectorOrConstantFP(N0))
8859     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8860
8861   return FoldIntToFPToInt(N, DAG);
8862 }
8863
8864 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8865   SDValue N0 = N->getOperand(0);
8866   EVT VT = N->getValueType(0);
8867
8868   // fold (fp_to_uint c1fp) -> c1
8869   if (isConstantFPBuildVectorOrConstantFP(N0))
8870     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8871
8872   return FoldIntToFPToInt(N, DAG);
8873 }
8874
8875 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8876   SDValue N0 = N->getOperand(0);
8877   SDValue N1 = N->getOperand(1);
8878   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8879   EVT VT = N->getValueType(0);
8880
8881   // fold (fp_round c1fp) -> c1fp
8882   if (N0CFP)
8883     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8884
8885   // fold (fp_round (fp_extend x)) -> x
8886   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8887     return N0.getOperand(0);
8888
8889   // fold (fp_round (fp_round x)) -> (fp_round x)
8890   if (N0.getOpcode() == ISD::FP_ROUND) {
8891     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8892     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8893     // If the first fp_round isn't a value preserving truncation, it might
8894     // introduce a tie in the second fp_round, that wouldn't occur in the
8895     // single-step fp_round we want to fold to.
8896     // In other words, double rounding isn't the same as rounding.
8897     // Also, this is a value preserving truncation iff both fp_round's are.
8898     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8899       SDLoc DL(N);
8900       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8901                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8902     }
8903   }
8904
8905   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8906   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8907     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8908                               N0.getOperand(0), N1);
8909     AddToWorklist(Tmp.getNode());
8910     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8911                        Tmp, N0.getOperand(1));
8912   }
8913
8914   return SDValue();
8915 }
8916
8917 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8918   SDValue N0 = N->getOperand(0);
8919   EVT VT = N->getValueType(0);
8920   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8921   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8922
8923   // fold (fp_round_inreg c1fp) -> c1fp
8924   if (N0CFP && isTypeLegal(EVT)) {
8925     SDLoc DL(N);
8926     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8927     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8928   }
8929
8930   return SDValue();
8931 }
8932
8933 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8934   SDValue N0 = N->getOperand(0);
8935   EVT VT = N->getValueType(0);
8936
8937   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8938   if (N->hasOneUse() &&
8939       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8940     return SDValue();
8941
8942   // fold (fp_extend c1fp) -> c1fp
8943   if (isConstantFPBuildVectorOrConstantFP(N0))
8944     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8945
8946   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8947   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8948       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8949     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8950
8951   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8952   // value of X.
8953   if (N0.getOpcode() == ISD::FP_ROUND
8954       && N0.getNode()->getConstantOperandVal(1) == 1) {
8955     SDValue In = N0.getOperand(0);
8956     if (In.getValueType() == VT) return In;
8957     if (VT.bitsLT(In.getValueType()))
8958       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8959                          In, N0.getOperand(1));
8960     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8961   }
8962
8963   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8964   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8965        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8966     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8967     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8968                                      LN0->getChain(),
8969                                      LN0->getBasePtr(), N0.getValueType(),
8970                                      LN0->getMemOperand());
8971     CombineTo(N, ExtLoad);
8972     CombineTo(N0.getNode(),
8973               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8974                           N0.getValueType(), ExtLoad,
8975                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8976               ExtLoad.getValue(1));
8977     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8978   }
8979
8980   return SDValue();
8981 }
8982
8983 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8984   SDValue N0 = N->getOperand(0);
8985   EVT VT = N->getValueType(0);
8986
8987   // fold (fceil c1) -> fceil(c1)
8988   if (isConstantFPBuildVectorOrConstantFP(N0))
8989     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8990
8991   return SDValue();
8992 }
8993
8994 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8995   SDValue N0 = N->getOperand(0);
8996   EVT VT = N->getValueType(0);
8997
8998   // fold (ftrunc c1) -> ftrunc(c1)
8999   if (isConstantFPBuildVectorOrConstantFP(N0))
9000     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9001
9002   return SDValue();
9003 }
9004
9005 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9006   SDValue N0 = N->getOperand(0);
9007   EVT VT = N->getValueType(0);
9008
9009   // fold (ffloor c1) -> ffloor(c1)
9010   if (isConstantFPBuildVectorOrConstantFP(N0))
9011     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9012
9013   return SDValue();
9014 }
9015
9016 // FIXME: FNEG and FABS have a lot in common; refactor.
9017 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9018   SDValue N0 = N->getOperand(0);
9019   EVT VT = N->getValueType(0);
9020
9021   // Constant fold FNEG.
9022   if (isConstantFPBuildVectorOrConstantFP(N0))
9023     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9024
9025   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9026                          &DAG.getTarget().Options))
9027     return GetNegatedExpression(N0, DAG, LegalOperations);
9028
9029   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9030   // constant pool values.
9031   if (!TLI.isFNegFree(VT) &&
9032       N0.getOpcode() == ISD::BITCAST &&
9033       N0.getNode()->hasOneUse()) {
9034     SDValue Int = N0.getOperand(0);
9035     EVT IntVT = Int.getValueType();
9036     if (IntVT.isInteger() && !IntVT.isVector()) {
9037       APInt SignMask;
9038       if (N0.getValueType().isVector()) {
9039         // For a vector, get a mask such as 0x80... per scalar element
9040         // and splat it.
9041         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9042         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9043       } else {
9044         // For a scalar, just generate 0x80...
9045         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9046       }
9047       SDLoc DL0(N0);
9048       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9049                         DAG.getConstant(SignMask, DL0, IntVT));
9050       AddToWorklist(Int.getNode());
9051       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9052     }
9053   }
9054
9055   // (fneg (fmul c, x)) -> (fmul -c, x)
9056   if (N0.getOpcode() == ISD::FMUL &&
9057       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9058     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9059     if (CFP1) {
9060       APFloat CVal = CFP1->getValueAPF();
9061       CVal.changeSign();
9062       if (Level >= AfterLegalizeDAG &&
9063           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9064            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9065         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9066                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9067                                        N0.getOperand(1)),
9068                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9069     }
9070   }
9071
9072   return SDValue();
9073 }
9074
9075 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9076   SDValue N0 = N->getOperand(0);
9077   SDValue N1 = N->getOperand(1);
9078   EVT VT = N->getValueType(0);
9079   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9080   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9081
9082   if (N0CFP && N1CFP) {
9083     const APFloat &C0 = N0CFP->getValueAPF();
9084     const APFloat &C1 = N1CFP->getValueAPF();
9085     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9086   }
9087
9088   // Canonicalize to constant on RHS.
9089   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9090      !isConstantFPBuildVectorOrConstantFP(N1))
9091     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9092
9093   return SDValue();
9094 }
9095
9096 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9097   SDValue N0 = N->getOperand(0);
9098   SDValue N1 = N->getOperand(1);
9099   EVT VT = N->getValueType(0);
9100   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9101   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9102
9103   if (N0CFP && N1CFP) {
9104     const APFloat &C0 = N0CFP->getValueAPF();
9105     const APFloat &C1 = N1CFP->getValueAPF();
9106     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9107   }
9108
9109   // Canonicalize to constant on RHS.
9110   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9111      !isConstantFPBuildVectorOrConstantFP(N1))
9112     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9113
9114   return SDValue();
9115 }
9116
9117 SDValue DAGCombiner::visitFABS(SDNode *N) {
9118   SDValue N0 = N->getOperand(0);
9119   EVT VT = N->getValueType(0);
9120
9121   // fold (fabs c1) -> fabs(c1)
9122   if (isConstantFPBuildVectorOrConstantFP(N0))
9123     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9124
9125   // fold (fabs (fabs x)) -> (fabs x)
9126   if (N0.getOpcode() == ISD::FABS)
9127     return N->getOperand(0);
9128
9129   // fold (fabs (fneg x)) -> (fabs x)
9130   // fold (fabs (fcopysign x, y)) -> (fabs x)
9131   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9132     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9133
9134   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9135   // constant pool values.
9136   if (!TLI.isFAbsFree(VT) &&
9137       N0.getOpcode() == ISD::BITCAST &&
9138       N0.getNode()->hasOneUse()) {
9139     SDValue Int = N0.getOperand(0);
9140     EVT IntVT = Int.getValueType();
9141     if (IntVT.isInteger() && !IntVT.isVector()) {
9142       APInt SignMask;
9143       if (N0.getValueType().isVector()) {
9144         // For a vector, get a mask such as 0x7f... per scalar element
9145         // and splat it.
9146         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9147         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9148       } else {
9149         // For a scalar, just generate 0x7f...
9150         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9151       }
9152       SDLoc DL(N0);
9153       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9154                         DAG.getConstant(SignMask, DL, IntVT));
9155       AddToWorklist(Int.getNode());
9156       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9157     }
9158   }
9159
9160   return SDValue();
9161 }
9162
9163 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9164   SDValue Chain = N->getOperand(0);
9165   SDValue N1 = N->getOperand(1);
9166   SDValue N2 = N->getOperand(2);
9167
9168   // If N is a constant we could fold this into a fallthrough or unconditional
9169   // branch. However that doesn't happen very often in normal code, because
9170   // Instcombine/SimplifyCFG should have handled the available opportunities.
9171   // If we did this folding here, it would be necessary to update the
9172   // MachineBasicBlock CFG, which is awkward.
9173
9174   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9175   // on the target.
9176   if (N1.getOpcode() == ISD::SETCC &&
9177       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9178                                    N1.getOperand(0).getValueType())) {
9179     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9180                        Chain, N1.getOperand(2),
9181                        N1.getOperand(0), N1.getOperand(1), N2);
9182   }
9183
9184   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9185       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9186        (N1.getOperand(0).hasOneUse() &&
9187         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9188     SDNode *Trunc = nullptr;
9189     if (N1.getOpcode() == ISD::TRUNCATE) {
9190       // Look pass the truncate.
9191       Trunc = N1.getNode();
9192       N1 = N1.getOperand(0);
9193     }
9194
9195     // Match this pattern so that we can generate simpler code:
9196     //
9197     //   %a = ...
9198     //   %b = and i32 %a, 2
9199     //   %c = srl i32 %b, 1
9200     //   brcond i32 %c ...
9201     //
9202     // into
9203     //
9204     //   %a = ...
9205     //   %b = and i32 %a, 2
9206     //   %c = setcc eq %b, 0
9207     //   brcond %c ...
9208     //
9209     // This applies only when the AND constant value has one bit set and the
9210     // SRL constant is equal to the log2 of the AND constant. The back-end is
9211     // smart enough to convert the result into a TEST/JMP sequence.
9212     SDValue Op0 = N1.getOperand(0);
9213     SDValue Op1 = N1.getOperand(1);
9214
9215     if (Op0.getOpcode() == ISD::AND &&
9216         Op1.getOpcode() == ISD::Constant) {
9217       SDValue AndOp1 = Op0.getOperand(1);
9218
9219       if (AndOp1.getOpcode() == ISD::Constant) {
9220         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9221
9222         if (AndConst.isPowerOf2() &&
9223             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9224           SDLoc DL(N);
9225           SDValue SetCC =
9226             DAG.getSetCC(DL,
9227                          getSetCCResultType(Op0.getValueType()),
9228                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9229                          ISD::SETNE);
9230
9231           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9232                                           MVT::Other, Chain, SetCC, N2);
9233           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9234           // will convert it back to (X & C1) >> C2.
9235           CombineTo(N, NewBRCond, false);
9236           // Truncate is dead.
9237           if (Trunc)
9238             deleteAndRecombine(Trunc);
9239           // Replace the uses of SRL with SETCC
9240           WorklistRemover DeadNodes(*this);
9241           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9242           deleteAndRecombine(N1.getNode());
9243           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9244         }
9245       }
9246     }
9247
9248     if (Trunc)
9249       // Restore N1 if the above transformation doesn't match.
9250       N1 = N->getOperand(1);
9251   }
9252
9253   // Transform br(xor(x, y)) -> br(x != y)
9254   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9255   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9256     SDNode *TheXor = N1.getNode();
9257     SDValue Op0 = TheXor->getOperand(0);
9258     SDValue Op1 = TheXor->getOperand(1);
9259     if (Op0.getOpcode() == Op1.getOpcode()) {
9260       // Avoid missing important xor optimizations.
9261       if (SDValue Tmp = visitXOR(TheXor)) {
9262         if (Tmp.getNode() != TheXor) {
9263           DEBUG(dbgs() << "\nReplacing.8 ";
9264                 TheXor->dump(&DAG);
9265                 dbgs() << "\nWith: ";
9266                 Tmp.getNode()->dump(&DAG);
9267                 dbgs() << '\n');
9268           WorklistRemover DeadNodes(*this);
9269           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9270           deleteAndRecombine(TheXor);
9271           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9272                              MVT::Other, Chain, Tmp, N2);
9273         }
9274
9275         // visitXOR has changed XOR's operands or replaced the XOR completely,
9276         // bail out.
9277         return SDValue(N, 0);
9278       }
9279     }
9280
9281     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9282       bool Equal = false;
9283       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9284           Op0.getOpcode() == ISD::XOR) {
9285         TheXor = Op0.getNode();
9286         Equal = true;
9287       }
9288
9289       EVT SetCCVT = N1.getValueType();
9290       if (LegalTypes)
9291         SetCCVT = getSetCCResultType(SetCCVT);
9292       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9293                                    SetCCVT,
9294                                    Op0, Op1,
9295                                    Equal ? ISD::SETEQ : ISD::SETNE);
9296       // Replace the uses of XOR with SETCC
9297       WorklistRemover DeadNodes(*this);
9298       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9299       deleteAndRecombine(N1.getNode());
9300       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9301                          MVT::Other, Chain, SetCC, N2);
9302     }
9303   }
9304
9305   return SDValue();
9306 }
9307
9308 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9309 //
9310 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9311   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9312   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9313
9314   // If N is a constant we could fold this into a fallthrough or unconditional
9315   // branch. However that doesn't happen very often in normal code, because
9316   // Instcombine/SimplifyCFG should have handled the available opportunities.
9317   // If we did this folding here, it would be necessary to update the
9318   // MachineBasicBlock CFG, which is awkward.
9319
9320   // Use SimplifySetCC to simplify SETCC's.
9321   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9322                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9323                                false);
9324   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9325
9326   // fold to a simpler setcc
9327   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9328     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9329                        N->getOperand(0), Simp.getOperand(2),
9330                        Simp.getOperand(0), Simp.getOperand(1),
9331                        N->getOperand(4));
9332
9333   return SDValue();
9334 }
9335
9336 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9337 /// and that N may be folded in the load / store addressing mode.
9338 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9339                                     SelectionDAG &DAG,
9340                                     const TargetLowering &TLI) {
9341   EVT VT;
9342   unsigned AS;
9343
9344   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9345     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9346       return false;
9347     VT = LD->getMemoryVT();
9348     AS = LD->getAddressSpace();
9349   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9350     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9351       return false;
9352     VT = ST->getMemoryVT();
9353     AS = ST->getAddressSpace();
9354   } else
9355     return false;
9356
9357   TargetLowering::AddrMode AM;
9358   if (N->getOpcode() == ISD::ADD) {
9359     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9360     if (Offset)
9361       // [reg +/- imm]
9362       AM.BaseOffs = Offset->getSExtValue();
9363     else
9364       // [reg +/- reg]
9365       AM.Scale = 1;
9366   } else if (N->getOpcode() == ISD::SUB) {
9367     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9368     if (Offset)
9369       // [reg +/- imm]
9370       AM.BaseOffs = -Offset->getSExtValue();
9371     else
9372       // [reg +/- reg]
9373       AM.Scale = 1;
9374   } else
9375     return false;
9376
9377   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9378                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9379 }
9380
9381 /// Try turning a load/store into a pre-indexed load/store when the base
9382 /// pointer is an add or subtract and it has other uses besides the load/store.
9383 /// After the transformation, the new indexed load/store has effectively folded
9384 /// the add/subtract in and all of its other uses are redirected to the
9385 /// new load/store.
9386 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9387   if (Level < AfterLegalizeDAG)
9388     return false;
9389
9390   bool isLoad = true;
9391   SDValue Ptr;
9392   EVT VT;
9393   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9394     if (LD->isIndexed())
9395       return false;
9396     VT = LD->getMemoryVT();
9397     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9398         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9399       return false;
9400     Ptr = LD->getBasePtr();
9401   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9402     if (ST->isIndexed())
9403       return false;
9404     VT = ST->getMemoryVT();
9405     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9406         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9407       return false;
9408     Ptr = ST->getBasePtr();
9409     isLoad = false;
9410   } else {
9411     return false;
9412   }
9413
9414   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9415   // out.  There is no reason to make this a preinc/predec.
9416   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9417       Ptr.getNode()->hasOneUse())
9418     return false;
9419
9420   // Ask the target to do addressing mode selection.
9421   SDValue BasePtr;
9422   SDValue Offset;
9423   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9424   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9425     return false;
9426
9427   // Backends without true r+i pre-indexed forms may need to pass a
9428   // constant base with a variable offset so that constant coercion
9429   // will work with the patterns in canonical form.
9430   bool Swapped = false;
9431   if (isa<ConstantSDNode>(BasePtr)) {
9432     std::swap(BasePtr, Offset);
9433     Swapped = true;
9434   }
9435
9436   // Don't create a indexed load / store with zero offset.
9437   if (isNullConstant(Offset))
9438     return false;
9439
9440   // Try turning it into a pre-indexed load / store except when:
9441   // 1) The new base ptr is a frame index.
9442   // 2) If N is a store and the new base ptr is either the same as or is a
9443   //    predecessor of the value being stored.
9444   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9445   //    that would create a cycle.
9446   // 4) All uses are load / store ops that use it as old base ptr.
9447
9448   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9449   // (plus the implicit offset) to a register to preinc anyway.
9450   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9451     return false;
9452
9453   // Check #2.
9454   if (!isLoad) {
9455     SDValue Val = cast<StoreSDNode>(N)->getValue();
9456     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9457       return false;
9458   }
9459
9460   // If the offset is a constant, there may be other adds of constants that
9461   // can be folded with this one. We should do this to avoid having to keep
9462   // a copy of the original base pointer.
9463   SmallVector<SDNode *, 16> OtherUses;
9464   if (isa<ConstantSDNode>(Offset))
9465     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9466                               UE = BasePtr.getNode()->use_end();
9467          UI != UE; ++UI) {
9468       SDUse &Use = UI.getUse();
9469       // Skip the use that is Ptr and uses of other results from BasePtr's
9470       // node (important for nodes that return multiple results).
9471       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9472         continue;
9473
9474       if (Use.getUser()->isPredecessorOf(N))
9475         continue;
9476
9477       if (Use.getUser()->getOpcode() != ISD::ADD &&
9478           Use.getUser()->getOpcode() != ISD::SUB) {
9479         OtherUses.clear();
9480         break;
9481       }
9482
9483       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9484       if (!isa<ConstantSDNode>(Op1)) {
9485         OtherUses.clear();
9486         break;
9487       }
9488
9489       // FIXME: In some cases, we can be smarter about this.
9490       if (Op1.getValueType() != Offset.getValueType()) {
9491         OtherUses.clear();
9492         break;
9493       }
9494
9495       OtherUses.push_back(Use.getUser());
9496     }
9497
9498   if (Swapped)
9499     std::swap(BasePtr, Offset);
9500
9501   // Now check for #3 and #4.
9502   bool RealUse = false;
9503
9504   // Caches for hasPredecessorHelper
9505   SmallPtrSet<const SDNode *, 32> Visited;
9506   SmallVector<const SDNode *, 16> Worklist;
9507
9508   for (SDNode *Use : Ptr.getNode()->uses()) {
9509     if (Use == N)
9510       continue;
9511     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9512       return false;
9513
9514     // If Ptr may be folded in addressing mode of other use, then it's
9515     // not profitable to do this transformation.
9516     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9517       RealUse = true;
9518   }
9519
9520   if (!RealUse)
9521     return false;
9522
9523   SDValue Result;
9524   if (isLoad)
9525     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9526                                 BasePtr, Offset, AM);
9527   else
9528     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9529                                  BasePtr, Offset, AM);
9530   ++PreIndexedNodes;
9531   ++NodesCombined;
9532   DEBUG(dbgs() << "\nReplacing.4 ";
9533         N->dump(&DAG);
9534         dbgs() << "\nWith: ";
9535         Result.getNode()->dump(&DAG);
9536         dbgs() << '\n');
9537   WorklistRemover DeadNodes(*this);
9538   if (isLoad) {
9539     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9540     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9541   } else {
9542     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9543   }
9544
9545   // Finally, since the node is now dead, remove it from the graph.
9546   deleteAndRecombine(N);
9547
9548   if (Swapped)
9549     std::swap(BasePtr, Offset);
9550
9551   // Replace other uses of BasePtr that can be updated to use Ptr
9552   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9553     unsigned OffsetIdx = 1;
9554     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9555       OffsetIdx = 0;
9556     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9557            BasePtr.getNode() && "Expected BasePtr operand");
9558
9559     // We need to replace ptr0 in the following expression:
9560     //   x0 * offset0 + y0 * ptr0 = t0
9561     // knowing that
9562     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9563     //
9564     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9565     // indexed load/store and the expresion that needs to be re-written.
9566     //
9567     // Therefore, we have:
9568     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9569
9570     ConstantSDNode *CN =
9571       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9572     int X0, X1, Y0, Y1;
9573     APInt Offset0 = CN->getAPIntValue();
9574     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9575
9576     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9577     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9578     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9579     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9580
9581     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9582
9583     APInt CNV = Offset0;
9584     if (X0 < 0) CNV = -CNV;
9585     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9586     else CNV = CNV - Offset1;
9587
9588     SDLoc DL(OtherUses[i]);
9589
9590     // We can now generate the new expression.
9591     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9592     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9593
9594     SDValue NewUse = DAG.getNode(Opcode,
9595                                  DL,
9596                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9597     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9598     deleteAndRecombine(OtherUses[i]);
9599   }
9600
9601   // Replace the uses of Ptr with uses of the updated base value.
9602   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9603   deleteAndRecombine(Ptr.getNode());
9604
9605   return true;
9606 }
9607
9608 /// Try to combine a load/store with a add/sub of the base pointer node into a
9609 /// post-indexed load/store. The transformation folded the add/subtract into the
9610 /// new indexed load/store effectively and all of its uses are redirected to the
9611 /// new load/store.
9612 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9613   if (Level < AfterLegalizeDAG)
9614     return false;
9615
9616   bool isLoad = true;
9617   SDValue Ptr;
9618   EVT VT;
9619   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9620     if (LD->isIndexed())
9621       return false;
9622     VT = LD->getMemoryVT();
9623     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9624         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9625       return false;
9626     Ptr = LD->getBasePtr();
9627   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9628     if (ST->isIndexed())
9629       return false;
9630     VT = ST->getMemoryVT();
9631     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9632         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9633       return false;
9634     Ptr = ST->getBasePtr();
9635     isLoad = false;
9636   } else {
9637     return false;
9638   }
9639
9640   if (Ptr.getNode()->hasOneUse())
9641     return false;
9642
9643   for (SDNode *Op : Ptr.getNode()->uses()) {
9644     if (Op == N ||
9645         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9646       continue;
9647
9648     SDValue BasePtr;
9649     SDValue Offset;
9650     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9651     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9652       // Don't create a indexed load / store with zero offset.
9653       if (isNullConstant(Offset))
9654         continue;
9655
9656       // Try turning it into a post-indexed load / store except when
9657       // 1) All uses are load / store ops that use it as base ptr (and
9658       //    it may be folded as addressing mmode).
9659       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9660       //    nor a successor of N. Otherwise, if Op is folded that would
9661       //    create a cycle.
9662
9663       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9664         continue;
9665
9666       // Check for #1.
9667       bool TryNext = false;
9668       for (SDNode *Use : BasePtr.getNode()->uses()) {
9669         if (Use == Ptr.getNode())
9670           continue;
9671
9672         // If all the uses are load / store addresses, then don't do the
9673         // transformation.
9674         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9675           bool RealUse = false;
9676           for (SDNode *UseUse : Use->uses()) {
9677             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9678               RealUse = true;
9679           }
9680
9681           if (!RealUse) {
9682             TryNext = true;
9683             break;
9684           }
9685         }
9686       }
9687
9688       if (TryNext)
9689         continue;
9690
9691       // Check for #2
9692       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9693         SDValue Result = isLoad
9694           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9695                                BasePtr, Offset, AM)
9696           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9697                                 BasePtr, Offset, AM);
9698         ++PostIndexedNodes;
9699         ++NodesCombined;
9700         DEBUG(dbgs() << "\nReplacing.5 ";
9701               N->dump(&DAG);
9702               dbgs() << "\nWith: ";
9703               Result.getNode()->dump(&DAG);
9704               dbgs() << '\n');
9705         WorklistRemover DeadNodes(*this);
9706         if (isLoad) {
9707           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9708           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9709         } else {
9710           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9711         }
9712
9713         // Finally, since the node is now dead, remove it from the graph.
9714         deleteAndRecombine(N);
9715
9716         // Replace the uses of Use with uses of the updated base value.
9717         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9718                                       Result.getValue(isLoad ? 1 : 0));
9719         deleteAndRecombine(Op);
9720         return true;
9721       }
9722     }
9723   }
9724
9725   return false;
9726 }
9727
9728 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9729 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9730   ISD::MemIndexedMode AM = LD->getAddressingMode();
9731   assert(AM != ISD::UNINDEXED);
9732   SDValue BP = LD->getOperand(1);
9733   SDValue Inc = LD->getOperand(2);
9734
9735   // Some backends use TargetConstants for load offsets, but don't expect
9736   // TargetConstants in general ADD nodes. We can convert these constants into
9737   // regular Constants (if the constant is not opaque).
9738   assert((Inc.getOpcode() != ISD::TargetConstant ||
9739           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9740          "Cannot split out indexing using opaque target constants");
9741   if (Inc.getOpcode() == ISD::TargetConstant) {
9742     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9743     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9744                           ConstInc->getValueType(0));
9745   }
9746
9747   unsigned Opc =
9748       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9749   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9750 }
9751
9752 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9753   LoadSDNode *LD  = cast<LoadSDNode>(N);
9754   SDValue Chain = LD->getChain();
9755   SDValue Ptr   = LD->getBasePtr();
9756
9757   // If load is not volatile and there are no uses of the loaded value (and
9758   // the updated indexed value in case of indexed loads), change uses of the
9759   // chain value into uses of the chain input (i.e. delete the dead load).
9760   if (!LD->isVolatile()) {
9761     if (N->getValueType(1) == MVT::Other) {
9762       // Unindexed loads.
9763       if (!N->hasAnyUseOfValue(0)) {
9764         // It's not safe to use the two value CombineTo variant here. e.g.
9765         // v1, chain2 = load chain1, loc
9766         // v2, chain3 = load chain2, loc
9767         // v3         = add v2, c
9768         // Now we replace use of chain2 with chain1.  This makes the second load
9769         // isomorphic to the one we are deleting, and thus makes this load live.
9770         DEBUG(dbgs() << "\nReplacing.6 ";
9771               N->dump(&DAG);
9772               dbgs() << "\nWith chain: ";
9773               Chain.getNode()->dump(&DAG);
9774               dbgs() << "\n");
9775         WorklistRemover DeadNodes(*this);
9776         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9777
9778         if (N->use_empty())
9779           deleteAndRecombine(N);
9780
9781         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9782       }
9783     } else {
9784       // Indexed loads.
9785       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9786
9787       // If this load has an opaque TargetConstant offset, then we cannot split
9788       // the indexing into an add/sub directly (that TargetConstant may not be
9789       // valid for a different type of node, and we cannot convert an opaque
9790       // target constant into a regular constant).
9791       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9792                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9793
9794       if (!N->hasAnyUseOfValue(0) &&
9795           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9796         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9797         SDValue Index;
9798         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9799           Index = SplitIndexingFromLoad(LD);
9800           // Try to fold the base pointer arithmetic into subsequent loads and
9801           // stores.
9802           AddUsersToWorklist(N);
9803         } else
9804           Index = DAG.getUNDEF(N->getValueType(1));
9805         DEBUG(dbgs() << "\nReplacing.7 ";
9806               N->dump(&DAG);
9807               dbgs() << "\nWith: ";
9808               Undef.getNode()->dump(&DAG);
9809               dbgs() << " and 2 other values\n");
9810         WorklistRemover DeadNodes(*this);
9811         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9812         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9813         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9814         deleteAndRecombine(N);
9815         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9816       }
9817     }
9818   }
9819
9820   // If this load is directly stored, replace the load value with the stored
9821   // value.
9822   // TODO: Handle store large -> read small portion.
9823   // TODO: Handle TRUNCSTORE/LOADEXT
9824   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9825     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9826       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9827       if (PrevST->getBasePtr() == Ptr &&
9828           PrevST->getValue().getValueType() == N->getValueType(0))
9829       return CombineTo(N, Chain.getOperand(1), Chain);
9830     }
9831   }
9832
9833   // Try to infer better alignment information than the load already has.
9834   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9835     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9836       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9837         SDValue NewLoad =
9838                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9839                               LD->getValueType(0),
9840                               Chain, Ptr, LD->getPointerInfo(),
9841                               LD->getMemoryVT(),
9842                               LD->isVolatile(), LD->isNonTemporal(),
9843                               LD->isInvariant(), Align, LD->getAAInfo());
9844         if (NewLoad.getNode() != N)
9845           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9846       }
9847     }
9848   }
9849
9850   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9851                                                   : DAG.getSubtarget().useAA();
9852 #ifndef NDEBUG
9853   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9854       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9855     UseAA = false;
9856 #endif
9857   if (UseAA && LD->isUnindexed()) {
9858     // Walk up chain skipping non-aliasing memory nodes.
9859     SDValue BetterChain = FindBetterChain(N, Chain);
9860
9861     // If there is a better chain.
9862     if (Chain != BetterChain) {
9863       SDValue ReplLoad;
9864
9865       // Replace the chain to void dependency.
9866       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9867         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9868                                BetterChain, Ptr, LD->getMemOperand());
9869       } else {
9870         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9871                                   LD->getValueType(0),
9872                                   BetterChain, Ptr, LD->getMemoryVT(),
9873                                   LD->getMemOperand());
9874       }
9875
9876       // Create token factor to keep old chain connected.
9877       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9878                                   MVT::Other, Chain, ReplLoad.getValue(1));
9879
9880       // Make sure the new and old chains are cleaned up.
9881       AddToWorklist(Token.getNode());
9882
9883       // Replace uses with load result and token factor. Don't add users
9884       // to work list.
9885       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9886     }
9887   }
9888
9889   // Try transforming N to an indexed load.
9890   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9891     return SDValue(N, 0);
9892
9893   // Try to slice up N to more direct loads if the slices are mapped to
9894   // different register banks or pairing can take place.
9895   if (SliceUpLoad(N))
9896     return SDValue(N, 0);
9897
9898   return SDValue();
9899 }
9900
9901 namespace {
9902 /// \brief Helper structure used to slice a load in smaller loads.
9903 /// Basically a slice is obtained from the following sequence:
9904 /// Origin = load Ty1, Base
9905 /// Shift = srl Ty1 Origin, CstTy Amount
9906 /// Inst = trunc Shift to Ty2
9907 ///
9908 /// Then, it will be rewriten into:
9909 /// Slice = load SliceTy, Base + SliceOffset
9910 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9911 ///
9912 /// SliceTy is deduced from the number of bits that are actually used to
9913 /// build Inst.
9914 struct LoadedSlice {
9915   /// \brief Helper structure used to compute the cost of a slice.
9916   struct Cost {
9917     /// Are we optimizing for code size.
9918     bool ForCodeSize;
9919     /// Various cost.
9920     unsigned Loads;
9921     unsigned Truncates;
9922     unsigned CrossRegisterBanksCopies;
9923     unsigned ZExts;
9924     unsigned Shift;
9925
9926     Cost(bool ForCodeSize = false)
9927         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9928           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9929
9930     /// \brief Get the cost of one isolated slice.
9931     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9932         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9933           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9934       EVT TruncType = LS.Inst->getValueType(0);
9935       EVT LoadedType = LS.getLoadedType();
9936       if (TruncType != LoadedType &&
9937           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9938         ZExts = 1;
9939     }
9940
9941     /// \brief Account for slicing gain in the current cost.
9942     /// Slicing provide a few gains like removing a shift or a
9943     /// truncate. This method allows to grow the cost of the original
9944     /// load with the gain from this slice.
9945     void addSliceGain(const LoadedSlice &LS) {
9946       // Each slice saves a truncate.
9947       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9948       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9949                               LS.Inst->getValueType(0)))
9950         ++Truncates;
9951       // If there is a shift amount, this slice gets rid of it.
9952       if (LS.Shift)
9953         ++Shift;
9954       // If this slice can merge a cross register bank copy, account for it.
9955       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9956         ++CrossRegisterBanksCopies;
9957     }
9958
9959     Cost &operator+=(const Cost &RHS) {
9960       Loads += RHS.Loads;
9961       Truncates += RHS.Truncates;
9962       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9963       ZExts += RHS.ZExts;
9964       Shift += RHS.Shift;
9965       return *this;
9966     }
9967
9968     bool operator==(const Cost &RHS) const {
9969       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9970              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9971              ZExts == RHS.ZExts && Shift == RHS.Shift;
9972     }
9973
9974     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9975
9976     bool operator<(const Cost &RHS) const {
9977       // Assume cross register banks copies are as expensive as loads.
9978       // FIXME: Do we want some more target hooks?
9979       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9980       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9981       // Unless we are optimizing for code size, consider the
9982       // expensive operation first.
9983       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9984         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9985       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9986              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9987     }
9988
9989     bool operator>(const Cost &RHS) const { return RHS < *this; }
9990
9991     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9992
9993     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9994   };
9995   // The last instruction that represent the slice. This should be a
9996   // truncate instruction.
9997   SDNode *Inst;
9998   // The original load instruction.
9999   LoadSDNode *Origin;
10000   // The right shift amount in bits from the original load.
10001   unsigned Shift;
10002   // The DAG from which Origin came from.
10003   // This is used to get some contextual information about legal types, etc.
10004   SelectionDAG *DAG;
10005
10006   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10007               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10008       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10009
10010   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10011   /// \return Result is \p BitWidth and has used bits set to 1 and
10012   ///         not used bits set to 0.
10013   APInt getUsedBits() const {
10014     // Reproduce the trunc(lshr) sequence:
10015     // - Start from the truncated value.
10016     // - Zero extend to the desired bit width.
10017     // - Shift left.
10018     assert(Origin && "No original load to compare against.");
10019     unsigned BitWidth = Origin->getValueSizeInBits(0);
10020     assert(Inst && "This slice is not bound to an instruction");
10021     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10022            "Extracted slice is bigger than the whole type!");
10023     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10024     UsedBits.setAllBits();
10025     UsedBits = UsedBits.zext(BitWidth);
10026     UsedBits <<= Shift;
10027     return UsedBits;
10028   }
10029
10030   /// \brief Get the size of the slice to be loaded in bytes.
10031   unsigned getLoadedSize() const {
10032     unsigned SliceSize = getUsedBits().countPopulation();
10033     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10034     return SliceSize / 8;
10035   }
10036
10037   /// \brief Get the type that will be loaded for this slice.
10038   /// Note: This may not be the final type for the slice.
10039   EVT getLoadedType() const {
10040     assert(DAG && "Missing context");
10041     LLVMContext &Ctxt = *DAG->getContext();
10042     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10043   }
10044
10045   /// \brief Get the alignment of the load used for this slice.
10046   unsigned getAlignment() const {
10047     unsigned Alignment = Origin->getAlignment();
10048     unsigned Offset = getOffsetFromBase();
10049     if (Offset != 0)
10050       Alignment = MinAlign(Alignment, Alignment + Offset);
10051     return Alignment;
10052   }
10053
10054   /// \brief Check if this slice can be rewritten with legal operations.
10055   bool isLegal() const {
10056     // An invalid slice is not legal.
10057     if (!Origin || !Inst || !DAG)
10058       return false;
10059
10060     // Offsets are for indexed load only, we do not handle that.
10061     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10062       return false;
10063
10064     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10065
10066     // Check that the type is legal.
10067     EVT SliceType = getLoadedType();
10068     if (!TLI.isTypeLegal(SliceType))
10069       return false;
10070
10071     // Check that the load is legal for this type.
10072     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10073       return false;
10074
10075     // Check that the offset can be computed.
10076     // 1. Check its type.
10077     EVT PtrType = Origin->getBasePtr().getValueType();
10078     if (PtrType == MVT::Untyped || PtrType.isExtended())
10079       return false;
10080
10081     // 2. Check that it fits in the immediate.
10082     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10083       return false;
10084
10085     // 3. Check that the computation is legal.
10086     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10087       return false;
10088
10089     // Check that the zext is legal if it needs one.
10090     EVT TruncateType = Inst->getValueType(0);
10091     if (TruncateType != SliceType &&
10092         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10093       return false;
10094
10095     return true;
10096   }
10097
10098   /// \brief Get the offset in bytes of this slice in the original chunk of
10099   /// bits.
10100   /// \pre DAG != nullptr.
10101   uint64_t getOffsetFromBase() const {
10102     assert(DAG && "Missing context.");
10103     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10104     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10105     uint64_t Offset = Shift / 8;
10106     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10107     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10108            "The size of the original loaded type is not a multiple of a"
10109            " byte.");
10110     // If Offset is bigger than TySizeInBytes, it means we are loading all
10111     // zeros. This should have been optimized before in the process.
10112     assert(TySizeInBytes > Offset &&
10113            "Invalid shift amount for given loaded size");
10114     if (IsBigEndian)
10115       Offset = TySizeInBytes - Offset - getLoadedSize();
10116     return Offset;
10117   }
10118
10119   /// \brief Generate the sequence of instructions to load the slice
10120   /// represented by this object and redirect the uses of this slice to
10121   /// this new sequence of instructions.
10122   /// \pre this->Inst && this->Origin are valid Instructions and this
10123   /// object passed the legal check: LoadedSlice::isLegal returned true.
10124   /// \return The last instruction of the sequence used to load the slice.
10125   SDValue loadSlice() const {
10126     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10127     const SDValue &OldBaseAddr = Origin->getBasePtr();
10128     SDValue BaseAddr = OldBaseAddr;
10129     // Get the offset in that chunk of bytes w.r.t. the endianess.
10130     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10131     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10132     if (Offset) {
10133       // BaseAddr = BaseAddr + Offset.
10134       EVT ArithType = BaseAddr.getValueType();
10135       SDLoc DL(Origin);
10136       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10137                               DAG->getConstant(Offset, DL, ArithType));
10138     }
10139
10140     // Create the type of the loaded slice according to its size.
10141     EVT SliceType = getLoadedType();
10142
10143     // Create the load for the slice.
10144     SDValue LastInst = DAG->getLoad(
10145         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10146         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10147         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10148     // If the final type is not the same as the loaded type, this means that
10149     // we have to pad with zero. Create a zero extend for that.
10150     EVT FinalType = Inst->getValueType(0);
10151     if (SliceType != FinalType)
10152       LastInst =
10153           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10154     return LastInst;
10155   }
10156
10157   /// \brief Check if this slice can be merged with an expensive cross register
10158   /// bank copy. E.g.,
10159   /// i = load i32
10160   /// f = bitcast i32 i to float
10161   bool canMergeExpensiveCrossRegisterBankCopy() const {
10162     if (!Inst || !Inst->hasOneUse())
10163       return false;
10164     SDNode *Use = *Inst->use_begin();
10165     if (Use->getOpcode() != ISD::BITCAST)
10166       return false;
10167     assert(DAG && "Missing context");
10168     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10169     EVT ResVT = Use->getValueType(0);
10170     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10171     const TargetRegisterClass *ArgRC =
10172         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10173     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10174       return false;
10175
10176     // At this point, we know that we perform a cross-register-bank copy.
10177     // Check if it is expensive.
10178     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10179     // Assume bitcasts are cheap, unless both register classes do not
10180     // explicitly share a common sub class.
10181     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10182       return false;
10183
10184     // Check if it will be merged with the load.
10185     // 1. Check the alignment constraint.
10186     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10187         ResVT.getTypeForEVT(*DAG->getContext()));
10188
10189     if (RequiredAlignment > getAlignment())
10190       return false;
10191
10192     // 2. Check that the load is a legal operation for that type.
10193     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10194       return false;
10195
10196     // 3. Check that we do not have a zext in the way.
10197     if (Inst->getValueType(0) != getLoadedType())
10198       return false;
10199
10200     return true;
10201   }
10202 };
10203 }
10204
10205 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10206 /// \p UsedBits looks like 0..0 1..1 0..0.
10207 static bool areUsedBitsDense(const APInt &UsedBits) {
10208   // If all the bits are one, this is dense!
10209   if (UsedBits.isAllOnesValue())
10210     return true;
10211
10212   // Get rid of the unused bits on the right.
10213   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10214   // Get rid of the unused bits on the left.
10215   if (NarrowedUsedBits.countLeadingZeros())
10216     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10217   // Check that the chunk of bits is completely used.
10218   return NarrowedUsedBits.isAllOnesValue();
10219 }
10220
10221 /// \brief Check whether or not \p First and \p Second are next to each other
10222 /// in memory. This means that there is no hole between the bits loaded
10223 /// by \p First and the bits loaded by \p Second.
10224 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10225                                      const LoadedSlice &Second) {
10226   assert(First.Origin == Second.Origin && First.Origin &&
10227          "Unable to match different memory origins.");
10228   APInt UsedBits = First.getUsedBits();
10229   assert((UsedBits & Second.getUsedBits()) == 0 &&
10230          "Slices are not supposed to overlap.");
10231   UsedBits |= Second.getUsedBits();
10232   return areUsedBitsDense(UsedBits);
10233 }
10234
10235 /// \brief Adjust the \p GlobalLSCost according to the target
10236 /// paring capabilities and the layout of the slices.
10237 /// \pre \p GlobalLSCost should account for at least as many loads as
10238 /// there is in the slices in \p LoadedSlices.
10239 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10240                                  LoadedSlice::Cost &GlobalLSCost) {
10241   unsigned NumberOfSlices = LoadedSlices.size();
10242   // If there is less than 2 elements, no pairing is possible.
10243   if (NumberOfSlices < 2)
10244     return;
10245
10246   // Sort the slices so that elements that are likely to be next to each
10247   // other in memory are next to each other in the list.
10248   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10249             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10250     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10251     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10252   });
10253   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10254   // First (resp. Second) is the first (resp. Second) potentially candidate
10255   // to be placed in a paired load.
10256   const LoadedSlice *First = nullptr;
10257   const LoadedSlice *Second = nullptr;
10258   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10259                 // Set the beginning of the pair.
10260                                                            First = Second) {
10261
10262     Second = &LoadedSlices[CurrSlice];
10263
10264     // If First is NULL, it means we start a new pair.
10265     // Get to the next slice.
10266     if (!First)
10267       continue;
10268
10269     EVT LoadedType = First->getLoadedType();
10270
10271     // If the types of the slices are different, we cannot pair them.
10272     if (LoadedType != Second->getLoadedType())
10273       continue;
10274
10275     // Check if the target supplies paired loads for this type.
10276     unsigned RequiredAlignment = 0;
10277     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10278       // move to the next pair, this type is hopeless.
10279       Second = nullptr;
10280       continue;
10281     }
10282     // Check if we meet the alignment requirement.
10283     if (RequiredAlignment > First->getAlignment())
10284       continue;
10285
10286     // Check that both loads are next to each other in memory.
10287     if (!areSlicesNextToEachOther(*First, *Second))
10288       continue;
10289
10290     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10291     --GlobalLSCost.Loads;
10292     // Move to the next pair.
10293     Second = nullptr;
10294   }
10295 }
10296
10297 /// \brief Check the profitability of all involved LoadedSlice.
10298 /// Currently, it is considered profitable if there is exactly two
10299 /// involved slices (1) which are (2) next to each other in memory, and
10300 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10301 ///
10302 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10303 /// the elements themselves.
10304 ///
10305 /// FIXME: When the cost model will be mature enough, we can relax
10306 /// constraints (1) and (2).
10307 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10308                                 const APInt &UsedBits, bool ForCodeSize) {
10309   unsigned NumberOfSlices = LoadedSlices.size();
10310   if (StressLoadSlicing)
10311     return NumberOfSlices > 1;
10312
10313   // Check (1).
10314   if (NumberOfSlices != 2)
10315     return false;
10316
10317   // Check (2).
10318   if (!areUsedBitsDense(UsedBits))
10319     return false;
10320
10321   // Check (3).
10322   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10323   // The original code has one big load.
10324   OrigCost.Loads = 1;
10325   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10326     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10327     // Accumulate the cost of all the slices.
10328     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10329     GlobalSlicingCost += SliceCost;
10330
10331     // Account as cost in the original configuration the gain obtained
10332     // with the current slices.
10333     OrigCost.addSliceGain(LS);
10334   }
10335
10336   // If the target supports paired load, adjust the cost accordingly.
10337   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10338   return OrigCost > GlobalSlicingCost;
10339 }
10340
10341 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10342 /// operations, split it in the various pieces being extracted.
10343 ///
10344 /// This sort of thing is introduced by SROA.
10345 /// This slicing takes care not to insert overlapping loads.
10346 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10347 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10348   if (Level < AfterLegalizeDAG)
10349     return false;
10350
10351   LoadSDNode *LD = cast<LoadSDNode>(N);
10352   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10353       !LD->getValueType(0).isInteger())
10354     return false;
10355
10356   // Keep track of already used bits to detect overlapping values.
10357   // In that case, we will just abort the transformation.
10358   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10359
10360   SmallVector<LoadedSlice, 4> LoadedSlices;
10361
10362   // Check if this load is used as several smaller chunks of bits.
10363   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10364   // of computation for each trunc.
10365   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10366        UI != UIEnd; ++UI) {
10367     // Skip the uses of the chain.
10368     if (UI.getUse().getResNo() != 0)
10369       continue;
10370
10371     SDNode *User = *UI;
10372     unsigned Shift = 0;
10373
10374     // Check if this is a trunc(lshr).
10375     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10376         isa<ConstantSDNode>(User->getOperand(1))) {
10377       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10378       User = *User->use_begin();
10379     }
10380
10381     // At this point, User is a Truncate, iff we encountered, trunc or
10382     // trunc(lshr).
10383     if (User->getOpcode() != ISD::TRUNCATE)
10384       return false;
10385
10386     // The width of the type must be a power of 2 and greater than 8-bits.
10387     // Otherwise the load cannot be represented in LLVM IR.
10388     // Moreover, if we shifted with a non-8-bits multiple, the slice
10389     // will be across several bytes. We do not support that.
10390     unsigned Width = User->getValueSizeInBits(0);
10391     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10392       return 0;
10393
10394     // Build the slice for this chain of computations.
10395     LoadedSlice LS(User, LD, Shift, &DAG);
10396     APInt CurrentUsedBits = LS.getUsedBits();
10397
10398     // Check if this slice overlaps with another.
10399     if ((CurrentUsedBits & UsedBits) != 0)
10400       return false;
10401     // Update the bits used globally.
10402     UsedBits |= CurrentUsedBits;
10403
10404     // Check if the new slice would be legal.
10405     if (!LS.isLegal())
10406       return false;
10407
10408     // Record the slice.
10409     LoadedSlices.push_back(LS);
10410   }
10411
10412   // Abort slicing if it does not seem to be profitable.
10413   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10414     return false;
10415
10416   ++SlicedLoads;
10417
10418   // Rewrite each chain to use an independent load.
10419   // By construction, each chain can be represented by a unique load.
10420
10421   // Prepare the argument for the new token factor for all the slices.
10422   SmallVector<SDValue, 8> ArgChains;
10423   for (SmallVectorImpl<LoadedSlice>::const_iterator
10424            LSIt = LoadedSlices.begin(),
10425            LSItEnd = LoadedSlices.end();
10426        LSIt != LSItEnd; ++LSIt) {
10427     SDValue SliceInst = LSIt->loadSlice();
10428     CombineTo(LSIt->Inst, SliceInst, true);
10429     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10430       SliceInst = SliceInst.getOperand(0);
10431     assert(SliceInst->getOpcode() == ISD::LOAD &&
10432            "It takes more than a zext to get to the loaded slice!!");
10433     ArgChains.push_back(SliceInst.getValue(1));
10434   }
10435
10436   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10437                               ArgChains);
10438   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10439   return true;
10440 }
10441
10442 /// Check to see if V is (and load (ptr), imm), where the load is having
10443 /// specific bytes cleared out.  If so, return the byte size being masked out
10444 /// and the shift amount.
10445 static std::pair<unsigned, unsigned>
10446 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10447   std::pair<unsigned, unsigned> Result(0, 0);
10448
10449   // Check for the structure we're looking for.
10450   if (V->getOpcode() != ISD::AND ||
10451       !isa<ConstantSDNode>(V->getOperand(1)) ||
10452       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10453     return Result;
10454
10455   // Check the chain and pointer.
10456   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10457   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10458
10459   // The store should be chained directly to the load or be an operand of a
10460   // tokenfactor.
10461   if (LD == Chain.getNode())
10462     ; // ok.
10463   else if (Chain->getOpcode() != ISD::TokenFactor)
10464     return Result; // Fail.
10465   else {
10466     bool isOk = false;
10467     for (const SDValue &ChainOp : Chain->op_values())
10468       if (ChainOp.getNode() == LD) {
10469         isOk = true;
10470         break;
10471       }
10472     if (!isOk) return Result;
10473   }
10474
10475   // This only handles simple types.
10476   if (V.getValueType() != MVT::i16 &&
10477       V.getValueType() != MVT::i32 &&
10478       V.getValueType() != MVT::i64)
10479     return Result;
10480
10481   // Check the constant mask.  Invert it so that the bits being masked out are
10482   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10483   // follow the sign bit for uniformity.
10484   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10485   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10486   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10487   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10488   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10489   if (NotMaskLZ == 64) return Result;  // All zero mask.
10490
10491   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10492   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10493     return Result;
10494
10495   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10496   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10497     NotMaskLZ -= 64-V.getValueSizeInBits();
10498
10499   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10500   switch (MaskedBytes) {
10501   case 1:
10502   case 2:
10503   case 4: break;
10504   default: return Result; // All one mask, or 5-byte mask.
10505   }
10506
10507   // Verify that the first bit starts at a multiple of mask so that the access
10508   // is aligned the same as the access width.
10509   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10510
10511   Result.first = MaskedBytes;
10512   Result.second = NotMaskTZ/8;
10513   return Result;
10514 }
10515
10516
10517 /// Check to see if IVal is something that provides a value as specified by
10518 /// MaskInfo. If so, replace the specified store with a narrower store of
10519 /// truncated IVal.
10520 static SDNode *
10521 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10522                                 SDValue IVal, StoreSDNode *St,
10523                                 DAGCombiner *DC) {
10524   unsigned NumBytes = MaskInfo.first;
10525   unsigned ByteShift = MaskInfo.second;
10526   SelectionDAG &DAG = DC->getDAG();
10527
10528   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10529   // that uses this.  If not, this is not a replacement.
10530   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10531                                   ByteShift*8, (ByteShift+NumBytes)*8);
10532   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10533
10534   // Check that it is legal on the target to do this.  It is legal if the new
10535   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10536   // legalization.
10537   MVT VT = MVT::getIntegerVT(NumBytes*8);
10538   if (!DC->isTypeLegal(VT))
10539     return nullptr;
10540
10541   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10542   // shifted by ByteShift and truncated down to NumBytes.
10543   if (ByteShift) {
10544     SDLoc DL(IVal);
10545     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10546                        DAG.getConstant(ByteShift*8, DL,
10547                                     DC->getShiftAmountTy(IVal.getValueType())));
10548   }
10549
10550   // Figure out the offset for the store and the alignment of the access.
10551   unsigned StOffset;
10552   unsigned NewAlign = St->getAlignment();
10553
10554   if (DAG.getDataLayout().isLittleEndian())
10555     StOffset = ByteShift;
10556   else
10557     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10558
10559   SDValue Ptr = St->getBasePtr();
10560   if (StOffset) {
10561     SDLoc DL(IVal);
10562     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10563                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10564     NewAlign = MinAlign(NewAlign, StOffset);
10565   }
10566
10567   // Truncate down to the new size.
10568   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10569
10570   ++OpsNarrowed;
10571   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10572                       St->getPointerInfo().getWithOffset(StOffset),
10573                       false, false, NewAlign).getNode();
10574 }
10575
10576
10577 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10578 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10579 /// narrowing the load and store if it would end up being a win for performance
10580 /// or code size.
10581 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10582   StoreSDNode *ST  = cast<StoreSDNode>(N);
10583   if (ST->isVolatile())
10584     return SDValue();
10585
10586   SDValue Chain = ST->getChain();
10587   SDValue Value = ST->getValue();
10588   SDValue Ptr   = ST->getBasePtr();
10589   EVT VT = Value.getValueType();
10590
10591   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10592     return SDValue();
10593
10594   unsigned Opc = Value.getOpcode();
10595
10596   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10597   // is a byte mask indicating a consecutive number of bytes, check to see if
10598   // Y is known to provide just those bytes.  If so, we try to replace the
10599   // load + replace + store sequence with a single (narrower) store, which makes
10600   // the load dead.
10601   if (Opc == ISD::OR) {
10602     std::pair<unsigned, unsigned> MaskedLoad;
10603     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10604     if (MaskedLoad.first)
10605       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10606                                                   Value.getOperand(1), ST,this))
10607         return SDValue(NewST, 0);
10608
10609     // Or is commutative, so try swapping X and Y.
10610     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10611     if (MaskedLoad.first)
10612       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10613                                                   Value.getOperand(0), ST,this))
10614         return SDValue(NewST, 0);
10615   }
10616
10617   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10618       Value.getOperand(1).getOpcode() != ISD::Constant)
10619     return SDValue();
10620
10621   SDValue N0 = Value.getOperand(0);
10622   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10623       Chain == SDValue(N0.getNode(), 1)) {
10624     LoadSDNode *LD = cast<LoadSDNode>(N0);
10625     if (LD->getBasePtr() != Ptr ||
10626         LD->getPointerInfo().getAddrSpace() !=
10627         ST->getPointerInfo().getAddrSpace())
10628       return SDValue();
10629
10630     // Find the type to narrow it the load / op / store to.
10631     SDValue N1 = Value.getOperand(1);
10632     unsigned BitWidth = N1.getValueSizeInBits();
10633     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10634     if (Opc == ISD::AND)
10635       Imm ^= APInt::getAllOnesValue(BitWidth);
10636     if (Imm == 0 || Imm.isAllOnesValue())
10637       return SDValue();
10638     unsigned ShAmt = Imm.countTrailingZeros();
10639     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10640     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10641     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10642     // The narrowing should be profitable, the load/store operation should be
10643     // legal (or custom) and the store size should be equal to the NewVT width.
10644     while (NewBW < BitWidth &&
10645            (NewVT.getStoreSizeInBits() != NewBW ||
10646             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10647             !TLI.isNarrowingProfitable(VT, NewVT))) {
10648       NewBW = NextPowerOf2(NewBW);
10649       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10650     }
10651     if (NewBW >= BitWidth)
10652       return SDValue();
10653
10654     // If the lsb changed does not start at the type bitwidth boundary,
10655     // start at the previous one.
10656     if (ShAmt % NewBW)
10657       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10658     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10659                                    std::min(BitWidth, ShAmt + NewBW));
10660     if ((Imm & Mask) == Imm) {
10661       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10662       if (Opc == ISD::AND)
10663         NewImm ^= APInt::getAllOnesValue(NewBW);
10664       uint64_t PtrOff = ShAmt / 8;
10665       // For big endian targets, we need to adjust the offset to the pointer to
10666       // load the correct bytes.
10667       if (DAG.getDataLayout().isBigEndian())
10668         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10669
10670       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10671       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10672       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10673         return SDValue();
10674
10675       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10676                                    Ptr.getValueType(), Ptr,
10677                                    DAG.getConstant(PtrOff, SDLoc(LD),
10678                                                    Ptr.getValueType()));
10679       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10680                                   LD->getChain(), NewPtr,
10681                                   LD->getPointerInfo().getWithOffset(PtrOff),
10682                                   LD->isVolatile(), LD->isNonTemporal(),
10683                                   LD->isInvariant(), NewAlign,
10684                                   LD->getAAInfo());
10685       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10686                                    DAG.getConstant(NewImm, SDLoc(Value),
10687                                                    NewVT));
10688       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10689                                    NewVal, NewPtr,
10690                                    ST->getPointerInfo().getWithOffset(PtrOff),
10691                                    false, false, NewAlign);
10692
10693       AddToWorklist(NewPtr.getNode());
10694       AddToWorklist(NewLD.getNode());
10695       AddToWorklist(NewVal.getNode());
10696       WorklistRemover DeadNodes(*this);
10697       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10698       ++OpsNarrowed;
10699       return NewST;
10700     }
10701   }
10702
10703   return SDValue();
10704 }
10705
10706 /// For a given floating point load / store pair, if the load value isn't used
10707 /// by any other operations, then consider transforming the pair to integer
10708 /// load / store operations if the target deems the transformation profitable.
10709 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10710   StoreSDNode *ST  = cast<StoreSDNode>(N);
10711   SDValue Chain = ST->getChain();
10712   SDValue Value = ST->getValue();
10713   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10714       Value.hasOneUse() &&
10715       Chain == SDValue(Value.getNode(), 1)) {
10716     LoadSDNode *LD = cast<LoadSDNode>(Value);
10717     EVT VT = LD->getMemoryVT();
10718     if (!VT.isFloatingPoint() ||
10719         VT != ST->getMemoryVT() ||
10720         LD->isNonTemporal() ||
10721         ST->isNonTemporal() ||
10722         LD->getPointerInfo().getAddrSpace() != 0 ||
10723         ST->getPointerInfo().getAddrSpace() != 0)
10724       return SDValue();
10725
10726     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10727     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10728         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10729         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10730         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10731       return SDValue();
10732
10733     unsigned LDAlign = LD->getAlignment();
10734     unsigned STAlign = ST->getAlignment();
10735     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10736     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10737     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10738       return SDValue();
10739
10740     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10741                                 LD->getChain(), LD->getBasePtr(),
10742                                 LD->getPointerInfo(),
10743                                 false, false, false, LDAlign);
10744
10745     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10746                                  NewLD, ST->getBasePtr(),
10747                                  ST->getPointerInfo(),
10748                                  false, false, STAlign);
10749
10750     AddToWorklist(NewLD.getNode());
10751     AddToWorklist(NewST.getNode());
10752     WorklistRemover DeadNodes(*this);
10753     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10754     ++LdStFP2Int;
10755     return NewST;
10756   }
10757
10758   return SDValue();
10759 }
10760
10761 namespace {
10762 /// Helper struct to parse and store a memory address as base + index + offset.
10763 /// We ignore sign extensions when it is safe to do so.
10764 /// The following two expressions are not equivalent. To differentiate we need
10765 /// to store whether there was a sign extension involved in the index
10766 /// computation.
10767 ///  (load (i64 add (i64 copyfromreg %c)
10768 ///                 (i64 signextend (add (i8 load %index)
10769 ///                                      (i8 1))))
10770 /// vs
10771 ///
10772 /// (load (i64 add (i64 copyfromreg %c)
10773 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10774 ///                                         (i32 1)))))
10775 struct BaseIndexOffset {
10776   SDValue Base;
10777   SDValue Index;
10778   int64_t Offset;
10779   bool IsIndexSignExt;
10780
10781   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10782
10783   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10784                   bool IsIndexSignExt) :
10785     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10786
10787   bool equalBaseIndex(const BaseIndexOffset &Other) {
10788     return Other.Base == Base && Other.Index == Index &&
10789       Other.IsIndexSignExt == IsIndexSignExt;
10790   }
10791
10792   /// Parses tree in Ptr for base, index, offset addresses.
10793   static BaseIndexOffset match(SDValue Ptr) {
10794     bool IsIndexSignExt = false;
10795
10796     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10797     // instruction, then it could be just the BASE or everything else we don't
10798     // know how to handle. Just use Ptr as BASE and give up.
10799     if (Ptr->getOpcode() != ISD::ADD)
10800       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10801
10802     // We know that we have at least an ADD instruction. Try to pattern match
10803     // the simple case of BASE + OFFSET.
10804     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10805       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10806       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10807                               IsIndexSignExt);
10808     }
10809
10810     // Inside a loop the current BASE pointer is calculated using an ADD and a
10811     // MUL instruction. In this case Ptr is the actual BASE pointer.
10812     // (i64 add (i64 %array_ptr)
10813     //          (i64 mul (i64 %induction_var)
10814     //                   (i64 %element_size)))
10815     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10816       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10817
10818     // Look at Base + Index + Offset cases.
10819     SDValue Base = Ptr->getOperand(0);
10820     SDValue IndexOffset = Ptr->getOperand(1);
10821
10822     // Skip signextends.
10823     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10824       IndexOffset = IndexOffset->getOperand(0);
10825       IsIndexSignExt = true;
10826     }
10827
10828     // Either the case of Base + Index (no offset) or something else.
10829     if (IndexOffset->getOpcode() != ISD::ADD)
10830       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10831
10832     // Now we have the case of Base + Index + offset.
10833     SDValue Index = IndexOffset->getOperand(0);
10834     SDValue Offset = IndexOffset->getOperand(1);
10835
10836     if (!isa<ConstantSDNode>(Offset))
10837       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10838
10839     // Ignore signextends.
10840     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10841       Index = Index->getOperand(0);
10842       IsIndexSignExt = true;
10843     } else IsIndexSignExt = false;
10844
10845     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10846     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10847   }
10848 };
10849 } // namespace
10850
10851 // This is a helper function for visitMUL to check the profitability
10852 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10853 // MulNode is the original multiply, AddNode is (add x, c1),
10854 // and ConstNode is c2.
10855 //
10856 // If the (add x, c1) has multiple uses, we could increase
10857 // the number of adds if we make this transformation.
10858 // It would only be worth doing this if we can remove a
10859 // multiply in the process. Check for that here.
10860 // To illustrate:
10861 //     (A + c1) * c3
10862 //     (A + c2) * c3
10863 // We're checking for cases where we have common "c3 * A" expressions.
10864 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10865                                               SDValue &AddNode,
10866                                               SDValue &ConstNode) {
10867   APInt Val;
10868
10869   // If the add only has one use, this would be OK to do.
10870   if (AddNode.getNode()->hasOneUse())
10871     return true;
10872
10873   // Walk all the users of the constant with which we're multiplying.
10874   for (SDNode *Use : ConstNode->uses()) {
10875
10876     if (Use == MulNode) // This use is the one we're on right now. Skip it.
10877       continue;
10878
10879     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10880       SDNode *OtherOp;
10881       SDNode *MulVar = AddNode.getOperand(0).getNode();
10882
10883       // OtherOp is what we're multiplying against the constant.
10884       if (Use->getOperand(0) == ConstNode)
10885         OtherOp = Use->getOperand(1).getNode();
10886       else
10887         OtherOp = Use->getOperand(0).getNode();
10888
10889       // Check to see if multiply is with the same operand of our "add".
10890       //
10891       //     ConstNode  = CONST
10892       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
10893       //     ...
10894       //     AddNode  = (A + c1)  <-- MulVar is A.
10895       //         = AddNode * ConstNode   <-- current visiting instruction.
10896       //
10897       // If we make this transformation, we will have a common
10898       // multiply (ConstNode * A) that we can save.
10899       if (OtherOp == MulVar)
10900         return true;
10901
10902       // Now check to see if a future expansion will give us a common
10903       // multiply.
10904       //
10905       //     ConstNode  = CONST
10906       //     AddNode    = (A + c1)
10907       //     ...   = AddNode * ConstNode <-- current visiting instruction.
10908       //     ...
10909       //     OtherOp = (A + c2)
10910       //     Use     = OtherOp * ConstNode <-- visiting Use.
10911       //
10912       // If we make this transformation, we will have a common
10913       // multiply (CONST * A) after we also do the same transformation
10914       // to the "t2" instruction.
10915       if (OtherOp->getOpcode() == ISD::ADD &&
10916           isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10917           OtherOp->getOperand(0).getNode() == MulVar)
10918         return true;
10919     }
10920   }
10921
10922   // Didn't find a case where this would be profitable.
10923   return false;
10924 }
10925
10926 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10927                                                   SDLoc SL,
10928                                                   ArrayRef<MemOpLink> Stores,
10929                                                   SmallVectorImpl<SDValue> &Chains,
10930                                                   EVT Ty) const {
10931   SmallVector<SDValue, 8> BuildVector;
10932
10933   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10934     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10935     Chains.push_back(St->getChain());
10936     BuildVector.push_back(St->getValue());
10937   }
10938
10939   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10940 }
10941
10942 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10943                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10944                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10945   // Make sure we have something to merge.
10946   if (NumStores < 2)
10947     return false;
10948
10949   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10950   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10951   unsigned LatestNodeUsed = 0;
10952
10953   for (unsigned i=0; i < NumStores; ++i) {
10954     // Find a chain for the new wide-store operand. Notice that some
10955     // of the store nodes that we found may not be selected for inclusion
10956     // in the wide store. The chain we use needs to be the chain of the
10957     // latest store node which is *used* and replaced by the wide store.
10958     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10959       LatestNodeUsed = i;
10960   }
10961
10962   SmallVector<SDValue, 8> Chains;
10963
10964   // The latest Node in the DAG.
10965   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10966   SDLoc DL(StoreNodes[0].MemNode);
10967
10968   SDValue StoredVal;
10969   if (UseVector) {
10970     bool IsVec = MemVT.isVector();
10971     unsigned Elts = NumStores;
10972     if (IsVec) {
10973       // When merging vector stores, get the total number of elements.
10974       Elts *= MemVT.getVectorNumElements();
10975     }
10976     // Get the type for the merged vector store.
10977     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10978     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10979
10980     if (IsConstantSrc) {
10981       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10982     } else {
10983       SmallVector<SDValue, 8> Ops;
10984       for (unsigned i = 0; i < NumStores; ++i) {
10985         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10986         SDValue Val = St->getValue();
10987         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10988         if (Val.getValueType() != MemVT)
10989           return false;
10990         Ops.push_back(Val);
10991         Chains.push_back(St->getChain());
10992       }
10993
10994       // Build the extracted vector elements back into a vector.
10995       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10996                               DL, Ty, Ops);    }
10997   } else {
10998     // We should always use a vector store when merging extracted vector
10999     // elements, so this path implies a store of constants.
11000     assert(IsConstantSrc && "Merged vector elements should use vector store");
11001
11002     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11003     APInt StoreInt(SizeInBits, 0);
11004
11005     // Construct a single integer constant which is made of the smaller
11006     // constant inputs.
11007     bool IsLE = DAG.getDataLayout().isLittleEndian();
11008     for (unsigned i = 0; i < NumStores; ++i) {
11009       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11010       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11011       Chains.push_back(St->getChain());
11012
11013       SDValue Val = St->getValue();
11014       StoreInt <<= ElementSizeBytes * 8;
11015       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11016         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11017       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11018         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11019       } else {
11020         llvm_unreachable("Invalid constant element type");
11021       }
11022     }
11023
11024     // Create the new Load and Store operations.
11025     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11026     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11027   }
11028
11029   assert(!Chains.empty());
11030
11031   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11032   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11033                                   FirstInChain->getBasePtr(),
11034                                   FirstInChain->getPointerInfo(),
11035                                   false, false,
11036                                   FirstInChain->getAlignment());
11037
11038   // Replace the last store with the new store
11039   CombineTo(LatestOp, NewStore);
11040   // Erase all other stores.
11041   for (unsigned i = 0; i < NumStores; ++i) {
11042     if (StoreNodes[i].MemNode == LatestOp)
11043       continue;
11044     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11045     // ReplaceAllUsesWith will replace all uses that existed when it was
11046     // called, but graph optimizations may cause new ones to appear. For
11047     // example, the case in pr14333 looks like
11048     //
11049     //  St's chain -> St -> another store -> X
11050     //
11051     // And the only difference from St to the other store is the chain.
11052     // When we change it's chain to be St's chain they become identical,
11053     // get CSEed and the net result is that X is now a use of St.
11054     // Since we know that St is redundant, just iterate.
11055     while (!St->use_empty())
11056       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11057     deleteAndRecombine(St);
11058   }
11059
11060   return true;
11061 }
11062
11063 void DAGCombiner::getStoreMergeAndAliasCandidates(
11064     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11065     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11066   // This holds the base pointer, index, and the offset in bytes from the base
11067   // pointer.
11068   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11069
11070   // We must have a base and an offset.
11071   if (!BasePtr.Base.getNode())
11072     return;
11073
11074   // Do not handle stores to undef base pointers.
11075   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11076     return;
11077
11078   // Walk up the chain and look for nodes with offsets from the same
11079   // base pointer. Stop when reaching an instruction with a different kind
11080   // or instruction which has a different base pointer.
11081   EVT MemVT = St->getMemoryVT();
11082   unsigned Seq = 0;
11083   StoreSDNode *Index = St;
11084
11085
11086   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11087                                                   : DAG.getSubtarget().useAA();
11088
11089   if (UseAA) {
11090     // Look at other users of the same chain. Stores on the same chain do not
11091     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11092     // to be on the same chain, so don't bother looking at adjacent chains.
11093
11094     SDValue Chain = St->getChain();
11095     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11096       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11097         if (I.getOperandNo() != 0)
11098           continue;
11099
11100         if (OtherST->isVolatile() || OtherST->isIndexed())
11101           continue;
11102
11103         if (OtherST->getMemoryVT() != MemVT)
11104           continue;
11105
11106         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11107
11108         if (Ptr.equalBaseIndex(BasePtr))
11109           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11110       }
11111     }
11112
11113     return;
11114   }
11115
11116   while (Index) {
11117     // If the chain has more than one use, then we can't reorder the mem ops.
11118     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11119       break;
11120
11121     // Find the base pointer and offset for this memory node.
11122     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11123
11124     // Check that the base pointer is the same as the original one.
11125     if (!Ptr.equalBaseIndex(BasePtr))
11126       break;
11127
11128     // The memory operands must not be volatile.
11129     if (Index->isVolatile() || Index->isIndexed())
11130       break;
11131
11132     // No truncation.
11133     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11134       if (St->isTruncatingStore())
11135         break;
11136
11137     // The stored memory type must be the same.
11138     if (Index->getMemoryVT() != MemVT)
11139       break;
11140
11141     // We found a potential memory operand to merge.
11142     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11143
11144     // Find the next memory operand in the chain. If the next operand in the
11145     // chain is a store then move up and continue the scan with the next
11146     // memory operand. If the next operand is a load save it and use alias
11147     // information to check if it interferes with anything.
11148     SDNode *NextInChain = Index->getChain().getNode();
11149     while (1) {
11150       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11151         // We found a store node. Use it for the next iteration.
11152         Index = STn;
11153         break;
11154       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11155         if (Ldn->isVolatile()) {
11156           Index = nullptr;
11157           break;
11158         }
11159
11160         // Save the load node for later. Continue the scan.
11161         AliasLoadNodes.push_back(Ldn);
11162         NextInChain = Ldn->getChain().getNode();
11163         continue;
11164       } else {
11165         Index = nullptr;
11166         break;
11167       }
11168     }
11169   }
11170 }
11171
11172 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11173   if (OptLevel == CodeGenOpt::None)
11174     return false;
11175
11176   EVT MemVT = St->getMemoryVT();
11177   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11178   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11179       Attribute::NoImplicitFloat);
11180
11181   // This function cannot currently deal with non-byte-sized memory sizes.
11182   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11183     return false;
11184
11185   if (!MemVT.isSimple())
11186     return false;
11187
11188   // Perform an early exit check. Do not bother looking at stored values that
11189   // are not constants, loads, or extracted vector elements.
11190   SDValue StoredVal = St->getValue();
11191   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11192   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11193                        isa<ConstantFPSDNode>(StoredVal);
11194   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11195                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11196
11197   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11198     return false;
11199
11200   // Don't merge vectors into wider vectors if the source data comes from loads.
11201   // TODO: This restriction can be lifted by using logic similar to the
11202   // ExtractVecSrc case.
11203   if (MemVT.isVector() && IsLoadSrc)
11204     return false;
11205
11206   // Only look at ends of store sequences.
11207   SDValue Chain = SDValue(St, 0);
11208   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11209     return false;
11210
11211   // Save the LoadSDNodes that we find in the chain.
11212   // We need to make sure that these nodes do not interfere with
11213   // any of the store nodes.
11214   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11215
11216   // Save the StoreSDNodes that we find in the chain.
11217   SmallVector<MemOpLink, 8> StoreNodes;
11218
11219   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11220
11221   // Check if there is anything to merge.
11222   if (StoreNodes.size() < 2)
11223     return false;
11224
11225   // Sort the memory operands according to their distance from the base pointer.
11226   std::sort(StoreNodes.begin(), StoreNodes.end(),
11227             [](MemOpLink LHS, MemOpLink RHS) {
11228     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11229            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11230             LHS.SequenceNum > RHS.SequenceNum);
11231   });
11232
11233   // Scan the memory operations on the chain and find the first non-consecutive
11234   // store memory address.
11235   unsigned LastConsecutiveStore = 0;
11236   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11237   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11238
11239     // Check that the addresses are consecutive starting from the second
11240     // element in the list of stores.
11241     if (i > 0) {
11242       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11243       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11244         break;
11245     }
11246
11247     bool Alias = false;
11248     // Check if this store interferes with any of the loads that we found.
11249     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11250       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11251         Alias = true;
11252         break;
11253       }
11254     // We found a load that alias with this store. Stop the sequence.
11255     if (Alias)
11256       break;
11257
11258     // Mark this node as useful.
11259     LastConsecutiveStore = i;
11260   }
11261
11262   // The node with the lowest store address.
11263   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11264   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11265   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11266   LLVMContext &Context = *DAG.getContext();
11267   const DataLayout &DL = DAG.getDataLayout();
11268
11269   // Store the constants into memory as one consecutive store.
11270   if (IsConstantSrc) {
11271     unsigned LastLegalType = 0;
11272     unsigned LastLegalVectorType = 0;
11273     bool NonZero = false;
11274     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11275       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11276       SDValue StoredVal = St->getValue();
11277
11278       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11279         NonZero |= !C->isNullValue();
11280       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11281         NonZero |= !C->getConstantFPValue()->isNullValue();
11282       } else {
11283         // Non-constant.
11284         break;
11285       }
11286
11287       // Find a legal type for the constant store.
11288       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11289       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11290       bool IsFast;
11291       if (TLI.isTypeLegal(StoreTy) &&
11292           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11293                                  FirstStoreAlign, &IsFast) && IsFast) {
11294         LastLegalType = i+1;
11295       // Or check whether a truncstore is legal.
11296       } else if (TLI.getTypeAction(Context, StoreTy) ==
11297                  TargetLowering::TypePromoteInteger) {
11298         EVT LegalizedStoredValueTy =
11299           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11300         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11301             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11302                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11303             IsFast) {
11304           LastLegalType = i + 1;
11305         }
11306       }
11307
11308       // We only use vectors if the constant is known to be zero or the target
11309       // allows it and the function is not marked with the noimplicitfloat
11310       // attribute.
11311       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11312                                                         FirstStoreAS)) &&
11313           !NoVectors) {
11314         // Find a legal type for the vector store.
11315         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11316         if (TLI.isTypeLegal(Ty) &&
11317             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11318                                    FirstStoreAlign, &IsFast) && IsFast)
11319           LastLegalVectorType = i + 1;
11320       }
11321     }
11322
11323     // Check if we found a legal integer type to store.
11324     if (LastLegalType == 0 && LastLegalVectorType == 0)
11325       return false;
11326
11327     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11328     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11329
11330     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11331                                            true, UseVector);
11332   }
11333
11334   // When extracting multiple vector elements, try to store them
11335   // in one vector store rather than a sequence of scalar stores.
11336   if (IsExtractVecSrc) {
11337     unsigned NumStoresToMerge = 0;
11338     bool IsVec = MemVT.isVector();
11339     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11340       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11341       unsigned StoreValOpcode = St->getValue().getOpcode();
11342       // This restriction could be loosened.
11343       // Bail out if any stored values are not elements extracted from a vector.
11344       // It should be possible to handle mixed sources, but load sources need
11345       // more careful handling (see the block of code below that handles
11346       // consecutive loads).
11347       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11348           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11349         return false;
11350
11351       // Find a legal type for the vector store.
11352       unsigned Elts = i + 1;
11353       if (IsVec) {
11354         // When merging vector stores, get the total number of elements.
11355         Elts *= MemVT.getVectorNumElements();
11356       }
11357       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11358       bool IsFast;
11359       if (TLI.isTypeLegal(Ty) &&
11360           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11361                                  FirstStoreAlign, &IsFast) && IsFast)
11362         NumStoresToMerge = i + 1;
11363     }
11364
11365     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11366                                            false, true);
11367   }
11368
11369   // Below we handle the case of multiple consecutive stores that
11370   // come from multiple consecutive loads. We merge them into a single
11371   // wide load and a single wide store.
11372
11373   // Look for load nodes which are used by the stored values.
11374   SmallVector<MemOpLink, 8> LoadNodes;
11375
11376   // Find acceptable loads. Loads need to have the same chain (token factor),
11377   // must not be zext, volatile, indexed, and they must be consecutive.
11378   BaseIndexOffset LdBasePtr;
11379   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11380     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11381     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11382     if (!Ld) break;
11383
11384     // Loads must only have one use.
11385     if (!Ld->hasNUsesOfValue(1, 0))
11386       break;
11387
11388     // The memory operands must not be volatile.
11389     if (Ld->isVolatile() || Ld->isIndexed())
11390       break;
11391
11392     // We do not accept ext loads.
11393     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11394       break;
11395
11396     // The stored memory type must be the same.
11397     if (Ld->getMemoryVT() != MemVT)
11398       break;
11399
11400     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11401     // If this is not the first ptr that we check.
11402     if (LdBasePtr.Base.getNode()) {
11403       // The base ptr must be the same.
11404       if (!LdPtr.equalBaseIndex(LdBasePtr))
11405         break;
11406     } else {
11407       // Check that all other base pointers are the same as this one.
11408       LdBasePtr = LdPtr;
11409     }
11410
11411     // We found a potential memory operand to merge.
11412     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11413   }
11414
11415   if (LoadNodes.size() < 2)
11416     return false;
11417
11418   // If we have load/store pair instructions and we only have two values,
11419   // don't bother.
11420   unsigned RequiredAlignment;
11421   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11422       St->getAlignment() >= RequiredAlignment)
11423     return false;
11424
11425   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11426   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11427   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11428
11429   // Scan the memory operations on the chain and find the first non-consecutive
11430   // load memory address. These variables hold the index in the store node
11431   // array.
11432   unsigned LastConsecutiveLoad = 0;
11433   // This variable refers to the size and not index in the array.
11434   unsigned LastLegalVectorType = 0;
11435   unsigned LastLegalIntegerType = 0;
11436   StartAddress = LoadNodes[0].OffsetFromBase;
11437   SDValue FirstChain = FirstLoad->getChain();
11438   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11439     // All loads much share the same chain.
11440     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11441       break;
11442
11443     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11444     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11445       break;
11446     LastConsecutiveLoad = i;
11447     // Find a legal type for the vector store.
11448     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11449     bool IsFastSt, IsFastLd;
11450     if (TLI.isTypeLegal(StoreTy) &&
11451         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11452                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11453         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11454                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11455       LastLegalVectorType = i + 1;
11456     }
11457
11458     // Find a legal type for the integer store.
11459     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11460     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11461     if (TLI.isTypeLegal(StoreTy) &&
11462         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11463                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11464         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11465                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11466       LastLegalIntegerType = i + 1;
11467     // Or check whether a truncstore and extload is legal.
11468     else if (TLI.getTypeAction(Context, StoreTy) ==
11469              TargetLowering::TypePromoteInteger) {
11470       EVT LegalizedStoredValueTy =
11471         TLI.getTypeToTransformTo(Context, StoreTy);
11472       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11473           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11474           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11475           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11476           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11477                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11478           IsFastSt &&
11479           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11480                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11481           IsFastLd)
11482         LastLegalIntegerType = i+1;
11483     }
11484   }
11485
11486   // Only use vector types if the vector type is larger than the integer type.
11487   // If they are the same, use integers.
11488   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11489   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11490
11491   // We add +1 here because the LastXXX variables refer to location while
11492   // the NumElem refers to array/index size.
11493   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11494   NumElem = std::min(LastLegalType, NumElem);
11495
11496   if (NumElem < 2)
11497     return false;
11498
11499   // Collect the chains from all merged stores.
11500   SmallVector<SDValue, 8> MergeStoreChains;
11501   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11502
11503   // The latest Node in the DAG.
11504   unsigned LatestNodeUsed = 0;
11505   for (unsigned i=1; i<NumElem; ++i) {
11506     // Find a chain for the new wide-store operand. Notice that some
11507     // of the store nodes that we found may not be selected for inclusion
11508     // in the wide store. The chain we use needs to be the chain of the
11509     // latest store node which is *used* and replaced by the wide store.
11510     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11511       LatestNodeUsed = i;
11512
11513     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11514   }
11515
11516   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11517
11518   // Find if it is better to use vectors or integers to load and store
11519   // to memory.
11520   EVT JointMemOpVT;
11521   if (UseVectorTy) {
11522     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11523   } else {
11524     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11525     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11526   }
11527
11528   SDLoc LoadDL(LoadNodes[0].MemNode);
11529   SDLoc StoreDL(StoreNodes[0].MemNode);
11530
11531   // The merged loads are required to have the same chain, so using the first's
11532   // chain is acceptable.
11533   SDValue NewLoad = DAG.getLoad(
11534       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11535       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11536
11537   SDValue NewStoreChain =
11538     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11539
11540   SDValue NewStore = DAG.getStore(
11541     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11542       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11543
11544   // Replace one of the loads with the new load.
11545   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11546   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11547                                 SDValue(NewLoad.getNode(), 1));
11548
11549   // Remove the rest of the load chains.
11550   for (unsigned i = 1; i < NumElem ; ++i) {
11551     // Replace all chain users of the old load nodes with the chain of the new
11552     // load node.
11553     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11554     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11555   }
11556
11557   // Replace the last store with the new store.
11558   CombineTo(LatestOp, NewStore);
11559   // Erase all other stores.
11560   for (unsigned i = 0; i < NumElem ; ++i) {
11561     // Remove all Store nodes.
11562     if (StoreNodes[i].MemNode == LatestOp)
11563       continue;
11564     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11565     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11566     deleteAndRecombine(St);
11567   }
11568
11569   return true;
11570 }
11571
11572 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11573   SDLoc SL(ST);
11574   SDValue ReplStore;
11575
11576   // Replace the chain to avoid dependency.
11577   if (ST->isTruncatingStore()) {
11578     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11579                                   ST->getBasePtr(), ST->getMemoryVT(),
11580                                   ST->getMemOperand());
11581   } else {
11582     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11583                              ST->getMemOperand());
11584   }
11585
11586   // Create token to keep both nodes around.
11587   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11588                               MVT::Other, ST->getChain(), ReplStore);
11589
11590   // Make sure the new and old chains are cleaned up.
11591   AddToWorklist(Token.getNode());
11592
11593   // Don't add users to work list.
11594   return CombineTo(ST, Token, false);
11595 }
11596
11597 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11598   SDValue Value = ST->getValue();
11599   if (Value.getOpcode() == ISD::TargetConstantFP)
11600     return SDValue();
11601
11602   SDLoc DL(ST);
11603
11604   SDValue Chain = ST->getChain();
11605   SDValue Ptr = ST->getBasePtr();
11606
11607   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11608
11609   // NOTE: If the original store is volatile, this transform must not increase
11610   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11611   // processor operation but an i64 (which is not legal) requires two.  So the
11612   // transform should not be done in this case.
11613
11614   SDValue Tmp;
11615   switch (CFP->getSimpleValueType(0).SimpleTy) {
11616   default:
11617     llvm_unreachable("Unknown FP type");
11618   case MVT::f16:    // We don't do this for these yet.
11619   case MVT::f80:
11620   case MVT::f128:
11621   case MVT::ppcf128:
11622     return SDValue();
11623   case MVT::f32:
11624     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11625         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11626       ;
11627       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11628                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11629                             MVT::i32);
11630       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11631     }
11632
11633     return SDValue();
11634   case MVT::f64:
11635     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11636          !ST->isVolatile()) ||
11637         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11638       ;
11639       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11640                             getZExtValue(), SDLoc(CFP), MVT::i64);
11641       return DAG.getStore(Chain, DL, Tmp,
11642                           Ptr, ST->getMemOperand());
11643     }
11644
11645     if (!ST->isVolatile() &&
11646         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11647       // Many FP stores are not made apparent until after legalize, e.g. for
11648       // argument passing.  Since this is so common, custom legalize the
11649       // 64-bit integer store into two 32-bit stores.
11650       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11651       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11652       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11653       if (DAG.getDataLayout().isBigEndian())
11654         std::swap(Lo, Hi);
11655
11656       unsigned Alignment = ST->getAlignment();
11657       bool isVolatile = ST->isVolatile();
11658       bool isNonTemporal = ST->isNonTemporal();
11659       AAMDNodes AAInfo = ST->getAAInfo();
11660
11661       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11662                                  Ptr, ST->getPointerInfo(),
11663                                  isVolatile, isNonTemporal,
11664                                  ST->getAlignment(), AAInfo);
11665       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11666                         DAG.getConstant(4, DL, Ptr.getValueType()));
11667       Alignment = MinAlign(Alignment, 4U);
11668       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11669                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11670                                  isVolatile, isNonTemporal,
11671                                  Alignment, AAInfo);
11672       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11673                          St0, St1);
11674     }
11675
11676     return SDValue();
11677   }
11678 }
11679
11680 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11681   StoreSDNode *ST  = cast<StoreSDNode>(N);
11682   SDValue Chain = ST->getChain();
11683   SDValue Value = ST->getValue();
11684   SDValue Ptr   = ST->getBasePtr();
11685
11686   // If this is a store of a bit convert, store the input value if the
11687   // resultant store does not need a higher alignment than the original.
11688   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11689       ST->isUnindexed()) {
11690     unsigned OrigAlign = ST->getAlignment();
11691     EVT SVT = Value.getOperand(0).getValueType();
11692     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11693         SVT.getTypeForEVT(*DAG.getContext()));
11694     if (Align <= OrigAlign &&
11695         ((!LegalOperations && !ST->isVolatile()) ||
11696          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11697       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11698                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11699                           ST->isNonTemporal(), OrigAlign,
11700                           ST->getAAInfo());
11701   }
11702
11703   // Turn 'store undef, Ptr' -> nothing.
11704   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11705     return Chain;
11706
11707   // Try to infer better alignment information than the store already has.
11708   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11709     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11710       if (Align > ST->getAlignment()) {
11711         SDValue NewStore =
11712                DAG.getTruncStore(Chain, SDLoc(N), Value,
11713                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11714                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11715                                  ST->getAAInfo());
11716         if (NewStore.getNode() != N)
11717           return CombineTo(ST, NewStore, true);
11718       }
11719     }
11720   }
11721
11722   // Try transforming a pair floating point load / store ops to integer
11723   // load / store ops.
11724   if (SDValue NewST = TransformFPLoadStorePair(N))
11725     return NewST;
11726
11727   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11728                                                   : DAG.getSubtarget().useAA();
11729 #ifndef NDEBUG
11730   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11731       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11732     UseAA = false;
11733 #endif
11734   if (UseAA && ST->isUnindexed()) {
11735     // FIXME: We should do this even without AA enabled. AA will just allow
11736     // FindBetterChain to work in more situations. The problem with this is that
11737     // any combine that expects memory operations to be on consecutive chains
11738     // first needs to be updated to look for users of the same chain.
11739
11740     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11741     // adjacent stores.
11742     if (findBetterNeighborChains(ST)) {
11743       // replaceStoreChain uses CombineTo, which handled all of the worklist
11744       // manipulation. Return the original node to not do anything else.
11745       return SDValue(ST, 0);
11746     }
11747   }
11748
11749   // Try transforming N to an indexed store.
11750   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11751     return SDValue(N, 0);
11752
11753   // FIXME: is there such a thing as a truncating indexed store?
11754   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11755       Value.getValueType().isInteger()) {
11756     // See if we can simplify the input to this truncstore with knowledge that
11757     // only the low bits are being used.  For example:
11758     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11759     SDValue Shorter =
11760       GetDemandedBits(Value,
11761                       APInt::getLowBitsSet(
11762                         Value.getValueType().getScalarType().getSizeInBits(),
11763                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11764     AddToWorklist(Value.getNode());
11765     if (Shorter.getNode())
11766       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11767                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11768
11769     // Otherwise, see if we can simplify the operation with
11770     // SimplifyDemandedBits, which only works if the value has a single use.
11771     if (SimplifyDemandedBits(Value,
11772                         APInt::getLowBitsSet(
11773                           Value.getValueType().getScalarType().getSizeInBits(),
11774                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11775       return SDValue(N, 0);
11776   }
11777
11778   // If this is a load followed by a store to the same location, then the store
11779   // is dead/noop.
11780   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11781     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11782         ST->isUnindexed() && !ST->isVolatile() &&
11783         // There can't be any side effects between the load and store, such as
11784         // a call or store.
11785         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11786       // The store is dead, remove it.
11787       return Chain;
11788     }
11789   }
11790
11791   // If this is a store followed by a store with the same value to the same
11792   // location, then the store is dead/noop.
11793   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11794     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11795         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11796         ST1->isUnindexed() && !ST1->isVolatile()) {
11797       // The store is dead, remove it.
11798       return Chain;
11799     }
11800   }
11801
11802   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11803   // truncating store.  We can do this even if this is already a truncstore.
11804   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11805       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11806       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11807                             ST->getMemoryVT())) {
11808     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11809                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11810   }
11811
11812   // Only perform this optimization before the types are legal, because we
11813   // don't want to perform this optimization on every DAGCombine invocation.
11814   if (!LegalTypes) {
11815     bool EverChanged = false;
11816
11817     do {
11818       // There can be multiple store sequences on the same chain.
11819       // Keep trying to merge store sequences until we are unable to do so
11820       // or until we merge the last store on the chain.
11821       bool Changed = MergeConsecutiveStores(ST);
11822       EverChanged |= Changed;
11823       if (!Changed) break;
11824     } while (ST->getOpcode() != ISD::DELETED_NODE);
11825
11826     if (EverChanged)
11827       return SDValue(N, 0);
11828   }
11829
11830   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11831   //
11832   // Make sure to do this only after attempting to merge stores in order to
11833   //  avoid changing the types of some subset of stores due to visit order,
11834   //  preventing their merging.
11835   if (isa<ConstantFPSDNode>(Value)) {
11836     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11837       return NewSt;
11838   }
11839
11840   return ReduceLoadOpStoreWidth(N);
11841 }
11842
11843 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11844   SDValue InVec = N->getOperand(0);
11845   SDValue InVal = N->getOperand(1);
11846   SDValue EltNo = N->getOperand(2);
11847   SDLoc dl(N);
11848
11849   // If the inserted element is an UNDEF, just use the input vector.
11850   if (InVal.getOpcode() == ISD::UNDEF)
11851     return InVec;
11852
11853   EVT VT = InVec.getValueType();
11854
11855   // If we can't generate a legal BUILD_VECTOR, exit
11856   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11857     return SDValue();
11858
11859   // Check that we know which element is being inserted
11860   if (!isa<ConstantSDNode>(EltNo))
11861     return SDValue();
11862   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11863
11864   // Canonicalize insert_vector_elt dag nodes.
11865   // Example:
11866   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11867   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11868   //
11869   // Do this only if the child insert_vector node has one use; also
11870   // do this only if indices are both constants and Idx1 < Idx0.
11871   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11872       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11873     unsigned OtherElt =
11874       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11875     if (Elt < OtherElt) {
11876       // Swap nodes.
11877       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11878                                   InVec.getOperand(0), InVal, EltNo);
11879       AddToWorklist(NewOp.getNode());
11880       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11881                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11882     }
11883   }
11884
11885   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11886   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11887   // vector elements.
11888   SmallVector<SDValue, 8> Ops;
11889   // Do not combine these two vectors if the output vector will not replace
11890   // the input vector.
11891   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11892     Ops.append(InVec.getNode()->op_begin(),
11893                InVec.getNode()->op_end());
11894   } else if (InVec.getOpcode() == ISD::UNDEF) {
11895     unsigned NElts = VT.getVectorNumElements();
11896     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11897   } else {
11898     return SDValue();
11899   }
11900
11901   // Insert the element
11902   if (Elt < Ops.size()) {
11903     // All the operands of BUILD_VECTOR must have the same type;
11904     // we enforce that here.
11905     EVT OpVT = Ops[0].getValueType();
11906     if (InVal.getValueType() != OpVT)
11907       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11908                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11909                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11910     Ops[Elt] = InVal;
11911   }
11912
11913   // Return the new vector
11914   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11915 }
11916
11917 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11918     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11919   EVT ResultVT = EVE->getValueType(0);
11920   EVT VecEltVT = InVecVT.getVectorElementType();
11921   unsigned Align = OriginalLoad->getAlignment();
11922   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11923       VecEltVT.getTypeForEVT(*DAG.getContext()));
11924
11925   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11926     return SDValue();
11927
11928   Align = NewAlign;
11929
11930   SDValue NewPtr = OriginalLoad->getBasePtr();
11931   SDValue Offset;
11932   EVT PtrType = NewPtr.getValueType();
11933   MachinePointerInfo MPI;
11934   SDLoc DL(EVE);
11935   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11936     int Elt = ConstEltNo->getZExtValue();
11937     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11938     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11939     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11940   } else {
11941     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11942     Offset = DAG.getNode(
11943         ISD::MUL, DL, PtrType, Offset,
11944         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11945     MPI = OriginalLoad->getPointerInfo();
11946   }
11947   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11948
11949   // The replacement we need to do here is a little tricky: we need to
11950   // replace an extractelement of a load with a load.
11951   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11952   // Note that this replacement assumes that the extractvalue is the only
11953   // use of the load; that's okay because we don't want to perform this
11954   // transformation in other cases anyway.
11955   SDValue Load;
11956   SDValue Chain;
11957   if (ResultVT.bitsGT(VecEltVT)) {
11958     // If the result type of vextract is wider than the load, then issue an
11959     // extending load instead.
11960     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11961                                                   VecEltVT)
11962                                    ? ISD::ZEXTLOAD
11963                                    : ISD::EXTLOAD;
11964     Load = DAG.getExtLoad(
11965         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11966         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11967         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11968     Chain = Load.getValue(1);
11969   } else {
11970     Load = DAG.getLoad(
11971         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11972         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11973         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11974     Chain = Load.getValue(1);
11975     if (ResultVT.bitsLT(VecEltVT))
11976       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11977     else
11978       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11979   }
11980   WorklistRemover DeadNodes(*this);
11981   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11982   SDValue To[] = { Load, Chain };
11983   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11984   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11985   // worklist explicitly as well.
11986   AddToWorklist(Load.getNode());
11987   AddUsersToWorklist(Load.getNode()); // Add users too
11988   // Make sure to revisit this node to clean it up; it will usually be dead.
11989   AddToWorklist(EVE);
11990   ++OpsNarrowed;
11991   return SDValue(EVE, 0);
11992 }
11993
11994 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11995   // (vextract (scalar_to_vector val, 0) -> val
11996   SDValue InVec = N->getOperand(0);
11997   EVT VT = InVec.getValueType();
11998   EVT NVT = N->getValueType(0);
11999
12000   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12001     // Check if the result type doesn't match the inserted element type. A
12002     // SCALAR_TO_VECTOR may truncate the inserted element and the
12003     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12004     SDValue InOp = InVec.getOperand(0);
12005     if (InOp.getValueType() != NVT) {
12006       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12007       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12008     }
12009     return InOp;
12010   }
12011
12012   SDValue EltNo = N->getOperand(1);
12013   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12014
12015   // extract_vector_elt (build_vector x, y), 1 -> y
12016   if (ConstEltNo &&
12017       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12018       TLI.isTypeLegal(VT) &&
12019       (InVec.hasOneUse() ||
12020        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12021     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12022     EVT InEltVT = Elt.getValueType();
12023
12024     // Sometimes build_vector's scalar input types do not match result type.
12025     if (NVT == InEltVT)
12026       return Elt;
12027
12028     // TODO: It may be useful to truncate if free if the build_vector implicitly
12029     // converts.
12030   }
12031
12032   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12033   // We only perform this optimization before the op legalization phase because
12034   // we may introduce new vector instructions which are not backed by TD
12035   // patterns. For example on AVX, extracting elements from a wide vector
12036   // without using extract_subvector. However, if we can find an underlying
12037   // scalar value, then we can always use that.
12038   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12039     int NumElem = VT.getVectorNumElements();
12040     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12041     // Find the new index to extract from.
12042     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12043
12044     // Extracting an undef index is undef.
12045     if (OrigElt == -1)
12046       return DAG.getUNDEF(NVT);
12047
12048     // Select the right vector half to extract from.
12049     SDValue SVInVec;
12050     if (OrigElt < NumElem) {
12051       SVInVec = InVec->getOperand(0);
12052     } else {
12053       SVInVec = InVec->getOperand(1);
12054       OrigElt -= NumElem;
12055     }
12056
12057     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12058       SDValue InOp = SVInVec.getOperand(OrigElt);
12059       if (InOp.getValueType() != NVT) {
12060         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12061         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12062       }
12063
12064       return InOp;
12065     }
12066
12067     // FIXME: We should handle recursing on other vector shuffles and
12068     // scalar_to_vector here as well.
12069
12070     if (!LegalOperations) {
12071       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12072       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12073                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12074     }
12075   }
12076
12077   bool BCNumEltsChanged = false;
12078   EVT ExtVT = VT.getVectorElementType();
12079   EVT LVT = ExtVT;
12080
12081   // If the result of load has to be truncated, then it's not necessarily
12082   // profitable.
12083   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12084     return SDValue();
12085
12086   if (InVec.getOpcode() == ISD::BITCAST) {
12087     // Don't duplicate a load with other uses.
12088     if (!InVec.hasOneUse())
12089       return SDValue();
12090
12091     EVT BCVT = InVec.getOperand(0).getValueType();
12092     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12093       return SDValue();
12094     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12095       BCNumEltsChanged = true;
12096     InVec = InVec.getOperand(0);
12097     ExtVT = BCVT.getVectorElementType();
12098   }
12099
12100   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12101   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12102       ISD::isNormalLoad(InVec.getNode()) &&
12103       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12104     SDValue Index = N->getOperand(1);
12105     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12106       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12107                                                            OrigLoad);
12108   }
12109
12110   // Perform only after legalization to ensure build_vector / vector_shuffle
12111   // optimizations have already been done.
12112   if (!LegalOperations) return SDValue();
12113
12114   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12115   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12116   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12117
12118   if (ConstEltNo) {
12119     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12120
12121     LoadSDNode *LN0 = nullptr;
12122     const ShuffleVectorSDNode *SVN = nullptr;
12123     if (ISD::isNormalLoad(InVec.getNode())) {
12124       LN0 = cast<LoadSDNode>(InVec);
12125     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12126                InVec.getOperand(0).getValueType() == ExtVT &&
12127                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12128       // Don't duplicate a load with other uses.
12129       if (!InVec.hasOneUse())
12130         return SDValue();
12131
12132       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12133     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12134       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12135       // =>
12136       // (load $addr+1*size)
12137
12138       // Don't duplicate a load with other uses.
12139       if (!InVec.hasOneUse())
12140         return SDValue();
12141
12142       // If the bit convert changed the number of elements, it is unsafe
12143       // to examine the mask.
12144       if (BCNumEltsChanged)
12145         return SDValue();
12146
12147       // Select the input vector, guarding against out of range extract vector.
12148       unsigned NumElems = VT.getVectorNumElements();
12149       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12150       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12151
12152       if (InVec.getOpcode() == ISD::BITCAST) {
12153         // Don't duplicate a load with other uses.
12154         if (!InVec.hasOneUse())
12155           return SDValue();
12156
12157         InVec = InVec.getOperand(0);
12158       }
12159       if (ISD::isNormalLoad(InVec.getNode())) {
12160         LN0 = cast<LoadSDNode>(InVec);
12161         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12162         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12163       }
12164     }
12165
12166     // Make sure we found a non-volatile load and the extractelement is
12167     // the only use.
12168     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12169       return SDValue();
12170
12171     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12172     if (Elt == -1)
12173       return DAG.getUNDEF(LVT);
12174
12175     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12176   }
12177
12178   return SDValue();
12179 }
12180
12181 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12182 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12183   // We perform this optimization post type-legalization because
12184   // the type-legalizer often scalarizes integer-promoted vectors.
12185   // Performing this optimization before may create bit-casts which
12186   // will be type-legalized to complex code sequences.
12187   // We perform this optimization only before the operation legalizer because we
12188   // may introduce illegal operations.
12189   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12190     return SDValue();
12191
12192   unsigned NumInScalars = N->getNumOperands();
12193   SDLoc dl(N);
12194   EVT VT = N->getValueType(0);
12195
12196   // Check to see if this is a BUILD_VECTOR of a bunch of values
12197   // which come from any_extend or zero_extend nodes. If so, we can create
12198   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12199   // optimizations. We do not handle sign-extend because we can't fill the sign
12200   // using shuffles.
12201   EVT SourceType = MVT::Other;
12202   bool AllAnyExt = true;
12203
12204   for (unsigned i = 0; i != NumInScalars; ++i) {
12205     SDValue In = N->getOperand(i);
12206     // Ignore undef inputs.
12207     if (In.getOpcode() == ISD::UNDEF) continue;
12208
12209     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12210     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12211
12212     // Abort if the element is not an extension.
12213     if (!ZeroExt && !AnyExt) {
12214       SourceType = MVT::Other;
12215       break;
12216     }
12217
12218     // The input is a ZeroExt or AnyExt. Check the original type.
12219     EVT InTy = In.getOperand(0).getValueType();
12220
12221     // Check that all of the widened source types are the same.
12222     if (SourceType == MVT::Other)
12223       // First time.
12224       SourceType = InTy;
12225     else if (InTy != SourceType) {
12226       // Multiple income types. Abort.
12227       SourceType = MVT::Other;
12228       break;
12229     }
12230
12231     // Check if all of the extends are ANY_EXTENDs.
12232     AllAnyExt &= AnyExt;
12233   }
12234
12235   // In order to have valid types, all of the inputs must be extended from the
12236   // same source type and all of the inputs must be any or zero extend.
12237   // Scalar sizes must be a power of two.
12238   EVT OutScalarTy = VT.getScalarType();
12239   bool ValidTypes = SourceType != MVT::Other &&
12240                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12241                  isPowerOf2_32(SourceType.getSizeInBits());
12242
12243   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12244   // turn into a single shuffle instruction.
12245   if (!ValidTypes)
12246     return SDValue();
12247
12248   bool isLE = DAG.getDataLayout().isLittleEndian();
12249   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12250   assert(ElemRatio > 1 && "Invalid element size ratio");
12251   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12252                                DAG.getConstant(0, SDLoc(N), SourceType);
12253
12254   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12255   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12256
12257   // Populate the new build_vector
12258   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12259     SDValue Cast = N->getOperand(i);
12260     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12261             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12262             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12263     SDValue In;
12264     if (Cast.getOpcode() == ISD::UNDEF)
12265       In = DAG.getUNDEF(SourceType);
12266     else
12267       In = Cast->getOperand(0);
12268     unsigned Index = isLE ? (i * ElemRatio) :
12269                             (i * ElemRatio + (ElemRatio - 1));
12270
12271     assert(Index < Ops.size() && "Invalid index");
12272     Ops[Index] = In;
12273   }
12274
12275   // The type of the new BUILD_VECTOR node.
12276   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12277   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12278          "Invalid vector size");
12279   // Check if the new vector type is legal.
12280   if (!isTypeLegal(VecVT)) return SDValue();
12281
12282   // Make the new BUILD_VECTOR.
12283   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12284
12285   // The new BUILD_VECTOR node has the potential to be further optimized.
12286   AddToWorklist(BV.getNode());
12287   // Bitcast to the desired type.
12288   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12289 }
12290
12291 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12292   EVT VT = N->getValueType(0);
12293
12294   unsigned NumInScalars = N->getNumOperands();
12295   SDLoc dl(N);
12296
12297   EVT SrcVT = MVT::Other;
12298   unsigned Opcode = ISD::DELETED_NODE;
12299   unsigned NumDefs = 0;
12300
12301   for (unsigned i = 0; i != NumInScalars; ++i) {
12302     SDValue In = N->getOperand(i);
12303     unsigned Opc = In.getOpcode();
12304
12305     if (Opc == ISD::UNDEF)
12306       continue;
12307
12308     // If all scalar values are floats and converted from integers.
12309     if (Opcode == ISD::DELETED_NODE &&
12310         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12311       Opcode = Opc;
12312     }
12313
12314     if (Opc != Opcode)
12315       return SDValue();
12316
12317     EVT InVT = In.getOperand(0).getValueType();
12318
12319     // If all scalar values are typed differently, bail out. It's chosen to
12320     // simplify BUILD_VECTOR of integer types.
12321     if (SrcVT == MVT::Other)
12322       SrcVT = InVT;
12323     if (SrcVT != InVT)
12324       return SDValue();
12325     NumDefs++;
12326   }
12327
12328   // If the vector has just one element defined, it's not worth to fold it into
12329   // a vectorized one.
12330   if (NumDefs < 2)
12331     return SDValue();
12332
12333   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12334          && "Should only handle conversion from integer to float.");
12335   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12336
12337   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12338
12339   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12340     return SDValue();
12341
12342   // Just because the floating-point vector type is legal does not necessarily
12343   // mean that the corresponding integer vector type is.
12344   if (!isTypeLegal(NVT))
12345     return SDValue();
12346
12347   SmallVector<SDValue, 8> Opnds;
12348   for (unsigned i = 0; i != NumInScalars; ++i) {
12349     SDValue In = N->getOperand(i);
12350
12351     if (In.getOpcode() == ISD::UNDEF)
12352       Opnds.push_back(DAG.getUNDEF(SrcVT));
12353     else
12354       Opnds.push_back(In.getOperand(0));
12355   }
12356   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12357   AddToWorklist(BV.getNode());
12358
12359   return DAG.getNode(Opcode, dl, VT, BV);
12360 }
12361
12362 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12363   unsigned NumInScalars = N->getNumOperands();
12364   SDLoc dl(N);
12365   EVT VT = N->getValueType(0);
12366
12367   // A vector built entirely of undefs is undef.
12368   if (ISD::allOperandsUndef(N))
12369     return DAG.getUNDEF(VT);
12370
12371   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12372     return V;
12373
12374   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12375     return V;
12376
12377   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12378   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12379   // at most two distinct vectors, turn this into a shuffle node.
12380
12381   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12382   if (!isTypeLegal(VT))
12383     return SDValue();
12384
12385   // May only combine to shuffle after legalize if shuffle is legal.
12386   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12387     return SDValue();
12388
12389   SDValue VecIn1, VecIn2;
12390   bool UsesZeroVector = false;
12391   for (unsigned i = 0; i != NumInScalars; ++i) {
12392     SDValue Op = N->getOperand(i);
12393     // Ignore undef inputs.
12394     if (Op.getOpcode() == ISD::UNDEF) continue;
12395
12396     // See if we can combine this build_vector into a blend with a zero vector.
12397     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12398       UsesZeroVector = true;
12399       continue;
12400     }
12401
12402     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12403     // constant index, bail out.
12404     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12405         !isa<ConstantSDNode>(Op.getOperand(1))) {
12406       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12407       break;
12408     }
12409
12410     // We allow up to two distinct input vectors.
12411     SDValue ExtractedFromVec = Op.getOperand(0);
12412     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12413       continue;
12414
12415     if (!VecIn1.getNode()) {
12416       VecIn1 = ExtractedFromVec;
12417     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12418       VecIn2 = ExtractedFromVec;
12419     } else {
12420       // Too many inputs.
12421       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12422       break;
12423     }
12424   }
12425
12426   // If everything is good, we can make a shuffle operation.
12427   if (VecIn1.getNode()) {
12428     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12429     SmallVector<int, 8> Mask;
12430     for (unsigned i = 0; i != NumInScalars; ++i) {
12431       unsigned Opcode = N->getOperand(i).getOpcode();
12432       if (Opcode == ISD::UNDEF) {
12433         Mask.push_back(-1);
12434         continue;
12435       }
12436
12437       // Operands can also be zero.
12438       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12439         assert(UsesZeroVector &&
12440                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12441                "Unexpected node found!");
12442         Mask.push_back(NumInScalars+i);
12443         continue;
12444       }
12445
12446       // If extracting from the first vector, just use the index directly.
12447       SDValue Extract = N->getOperand(i);
12448       SDValue ExtVal = Extract.getOperand(1);
12449       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12450       if (Extract.getOperand(0) == VecIn1) {
12451         Mask.push_back(ExtIndex);
12452         continue;
12453       }
12454
12455       // Otherwise, use InIdx + InputVecSize
12456       Mask.push_back(InNumElements + ExtIndex);
12457     }
12458
12459     // Avoid introducing illegal shuffles with zero.
12460     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12461       return SDValue();
12462
12463     // We can't generate a shuffle node with mismatched input and output types.
12464     // Attempt to transform a single input vector to the correct type.
12465     if ((VT != VecIn1.getValueType())) {
12466       // If the input vector type has a different base type to the output
12467       // vector type, bail out.
12468       EVT VTElemType = VT.getVectorElementType();
12469       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12470           (VecIn2.getNode() &&
12471            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12472         return SDValue();
12473
12474       // If the input vector is too small, widen it.
12475       // We only support widening of vectors which are half the size of the
12476       // output registers. For example XMM->YMM widening on X86 with AVX.
12477       EVT VecInT = VecIn1.getValueType();
12478       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12479         // If we only have one small input, widen it by adding undef values.
12480         if (!VecIn2.getNode())
12481           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12482                                DAG.getUNDEF(VecIn1.getValueType()));
12483         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12484           // If we have two small inputs of the same type, try to concat them.
12485           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12486           VecIn2 = SDValue(nullptr, 0);
12487         } else
12488           return SDValue();
12489       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12490         // If the input vector is too large, try to split it.
12491         // We don't support having two input vectors that are too large.
12492         // If the zero vector was used, we can not split the vector,
12493         // since we'd need 3 inputs.
12494         if (UsesZeroVector || VecIn2.getNode())
12495           return SDValue();
12496
12497         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12498           return SDValue();
12499
12500         // Try to replace VecIn1 with two extract_subvectors
12501         // No need to update the masks, they should still be correct.
12502         VecIn2 = DAG.getNode(
12503             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12504             DAG.getConstant(VT.getVectorNumElements(), dl,
12505                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12506         VecIn1 = DAG.getNode(
12507             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12508             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12509       } else
12510         return SDValue();
12511     }
12512
12513     if (UsesZeroVector)
12514       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12515                                 DAG.getConstantFP(0.0, dl, VT);
12516     else
12517       // If VecIn2 is unused then change it to undef.
12518       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12519
12520     // Check that we were able to transform all incoming values to the same
12521     // type.
12522     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12523         VecIn1.getValueType() != VT)
12524           return SDValue();
12525
12526     // Return the new VECTOR_SHUFFLE node.
12527     SDValue Ops[2];
12528     Ops[0] = VecIn1;
12529     Ops[1] = VecIn2;
12530     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12531   }
12532
12533   return SDValue();
12534 }
12535
12536 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12538   EVT OpVT = N->getOperand(0).getValueType();
12539
12540   // If the operands are legal vectors, leave them alone.
12541   if (TLI.isTypeLegal(OpVT))
12542     return SDValue();
12543
12544   SDLoc DL(N);
12545   EVT VT = N->getValueType(0);
12546   SmallVector<SDValue, 8> Ops;
12547
12548   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12549   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12550
12551   // Keep track of what we encounter.
12552   bool AnyInteger = false;
12553   bool AnyFP = false;
12554   for (const SDValue &Op : N->ops()) {
12555     if (ISD::BITCAST == Op.getOpcode() &&
12556         !Op.getOperand(0).getValueType().isVector())
12557       Ops.push_back(Op.getOperand(0));
12558     else if (ISD::UNDEF == Op.getOpcode())
12559       Ops.push_back(ScalarUndef);
12560     else
12561       return SDValue();
12562
12563     // Note whether we encounter an integer or floating point scalar.
12564     // If it's neither, bail out, it could be something weird like x86mmx.
12565     EVT LastOpVT = Ops.back().getValueType();
12566     if (LastOpVT.isFloatingPoint())
12567       AnyFP = true;
12568     else if (LastOpVT.isInteger())
12569       AnyInteger = true;
12570     else
12571       return SDValue();
12572   }
12573
12574   // If any of the operands is a floating point scalar bitcast to a vector,
12575   // use floating point types throughout, and bitcast everything.
12576   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12577   if (AnyFP) {
12578     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12579     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12580     if (AnyInteger) {
12581       for (SDValue &Op : Ops) {
12582         if (Op.getValueType() == SVT)
12583           continue;
12584         if (Op.getOpcode() == ISD::UNDEF)
12585           Op = ScalarUndef;
12586         else
12587           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12588       }
12589     }
12590   }
12591
12592   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12593                                VT.getSizeInBits() / SVT.getSizeInBits());
12594   return DAG.getNode(ISD::BITCAST, DL, VT,
12595                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12596 }
12597
12598 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12599 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12600 // most two distinct vectors the same size as the result, attempt to turn this
12601 // into a legal shuffle.
12602 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12603   EVT VT = N->getValueType(0);
12604   EVT OpVT = N->getOperand(0).getValueType();
12605   int NumElts = VT.getVectorNumElements();
12606   int NumOpElts = OpVT.getVectorNumElements();
12607
12608   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12609   SmallVector<int, 8> Mask;
12610
12611   for (SDValue Op : N->ops()) {
12612     // Peek through any bitcast.
12613     while (Op.getOpcode() == ISD::BITCAST)
12614       Op = Op.getOperand(0);
12615
12616     // UNDEF nodes convert to UNDEF shuffle mask values.
12617     if (Op.getOpcode() == ISD::UNDEF) {
12618       Mask.append((unsigned)NumOpElts, -1);
12619       continue;
12620     }
12621
12622     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12623       return SDValue();
12624
12625     // What vector are we extracting the subvector from and at what index?
12626     SDValue ExtVec = Op.getOperand(0);
12627
12628     // We want the EVT of the original extraction to correctly scale the
12629     // extraction index.
12630     EVT ExtVT = ExtVec.getValueType();
12631
12632     // Peek through any bitcast.
12633     while (ExtVec.getOpcode() == ISD::BITCAST)
12634       ExtVec = ExtVec.getOperand(0);
12635
12636     // UNDEF nodes convert to UNDEF shuffle mask values.
12637     if (ExtVec.getOpcode() == ISD::UNDEF) {
12638       Mask.append((unsigned)NumOpElts, -1);
12639       continue;
12640     }
12641
12642     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12643       return SDValue();
12644     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12645
12646     // Ensure that we are extracting a subvector from a vector the same
12647     // size as the result.
12648     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12649       return SDValue();
12650
12651     // Scale the subvector index to account for any bitcast.
12652     int NumExtElts = ExtVT.getVectorNumElements();
12653     if (0 == (NumExtElts % NumElts))
12654       ExtIdx /= (NumExtElts / NumElts);
12655     else if (0 == (NumElts % NumExtElts))
12656       ExtIdx *= (NumElts / NumExtElts);
12657     else
12658       return SDValue();
12659
12660     // At most we can reference 2 inputs in the final shuffle.
12661     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12662       SV0 = ExtVec;
12663       for (int i = 0; i != NumOpElts; ++i)
12664         Mask.push_back(i + ExtIdx);
12665     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12666       SV1 = ExtVec;
12667       for (int i = 0; i != NumOpElts; ++i)
12668         Mask.push_back(i + ExtIdx + NumElts);
12669     } else {
12670       return SDValue();
12671     }
12672   }
12673
12674   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12675     return SDValue();
12676
12677   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12678                               DAG.getBitcast(VT, SV1), Mask);
12679 }
12680
12681 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12682   // If we only have one input vector, we don't need to do any concatenation.
12683   if (N->getNumOperands() == 1)
12684     return N->getOperand(0);
12685
12686   // Check if all of the operands are undefs.
12687   EVT VT = N->getValueType(0);
12688   if (ISD::allOperandsUndef(N))
12689     return DAG.getUNDEF(VT);
12690
12691   // Optimize concat_vectors where all but the first of the vectors are undef.
12692   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12693         return Op.getOpcode() == ISD::UNDEF;
12694       })) {
12695     SDValue In = N->getOperand(0);
12696     assert(In.getValueType().isVector() && "Must concat vectors");
12697
12698     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12699     if (In->getOpcode() == ISD::BITCAST &&
12700         !In->getOperand(0)->getValueType(0).isVector()) {
12701       SDValue Scalar = In->getOperand(0);
12702
12703       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12704       // look through the trunc so we can still do the transform:
12705       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12706       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12707           !TLI.isTypeLegal(Scalar.getValueType()) &&
12708           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12709         Scalar = Scalar->getOperand(0);
12710
12711       EVT SclTy = Scalar->getValueType(0);
12712
12713       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12714         return SDValue();
12715
12716       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12717                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12718       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12719         return SDValue();
12720
12721       SDLoc dl = SDLoc(N);
12722       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12723       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12724     }
12725   }
12726
12727   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12728   // We have already tested above for an UNDEF only concatenation.
12729   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12730   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12731   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12732     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12733   };
12734   bool AllBuildVectorsOrUndefs =
12735       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12736   if (AllBuildVectorsOrUndefs) {
12737     SmallVector<SDValue, 8> Opnds;
12738     EVT SVT = VT.getScalarType();
12739
12740     EVT MinVT = SVT;
12741     if (!SVT.isFloatingPoint()) {
12742       // If BUILD_VECTOR are from built from integer, they may have different
12743       // operand types. Get the smallest type and truncate all operands to it.
12744       bool FoundMinVT = false;
12745       for (const SDValue &Op : N->ops())
12746         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12747           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12748           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12749           FoundMinVT = true;
12750         }
12751       assert(FoundMinVT && "Concat vector type mismatch");
12752     }
12753
12754     for (const SDValue &Op : N->ops()) {
12755       EVT OpVT = Op.getValueType();
12756       unsigned NumElts = OpVT.getVectorNumElements();
12757
12758       if (ISD::UNDEF == Op.getOpcode())
12759         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12760
12761       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12762         if (SVT.isFloatingPoint()) {
12763           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12764           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12765         } else {
12766           for (unsigned i = 0; i != NumElts; ++i)
12767             Opnds.push_back(
12768                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12769         }
12770       }
12771     }
12772
12773     assert(VT.getVectorNumElements() == Opnds.size() &&
12774            "Concat vector type mismatch");
12775     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12776   }
12777
12778   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12779   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12780     return V;
12781
12782   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12783   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12784     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12785       return V;
12786
12787   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12788   // nodes often generate nop CONCAT_VECTOR nodes.
12789   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12790   // place the incoming vectors at the exact same location.
12791   SDValue SingleSource = SDValue();
12792   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12793
12794   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12795     SDValue Op = N->getOperand(i);
12796
12797     if (Op.getOpcode() == ISD::UNDEF)
12798       continue;
12799
12800     // Check if this is the identity extract:
12801     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12802       return SDValue();
12803
12804     // Find the single incoming vector for the extract_subvector.
12805     if (SingleSource.getNode()) {
12806       if (Op.getOperand(0) != SingleSource)
12807         return SDValue();
12808     } else {
12809       SingleSource = Op.getOperand(0);
12810
12811       // Check the source type is the same as the type of the result.
12812       // If not, this concat may extend the vector, so we can not
12813       // optimize it away.
12814       if (SingleSource.getValueType() != N->getValueType(0))
12815         return SDValue();
12816     }
12817
12818     unsigned IdentityIndex = i * PartNumElem;
12819     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12820     // The extract index must be constant.
12821     if (!CS)
12822       return SDValue();
12823
12824     // Check that we are reading from the identity index.
12825     if (CS->getZExtValue() != IdentityIndex)
12826       return SDValue();
12827   }
12828
12829   if (SingleSource.getNode())
12830     return SingleSource;
12831
12832   return SDValue();
12833 }
12834
12835 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12836   EVT NVT = N->getValueType(0);
12837   SDValue V = N->getOperand(0);
12838
12839   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12840     // Combine:
12841     //    (extract_subvec (concat V1, V2, ...), i)
12842     // Into:
12843     //    Vi if possible
12844     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12845     // type.
12846     if (V->getOperand(0).getValueType() != NVT)
12847       return SDValue();
12848     unsigned Idx = N->getConstantOperandVal(1);
12849     unsigned NumElems = NVT.getVectorNumElements();
12850     assert((Idx % NumElems) == 0 &&
12851            "IDX in concat is not a multiple of the result vector length.");
12852     return V->getOperand(Idx / NumElems);
12853   }
12854
12855   // Skip bitcasting
12856   if (V->getOpcode() == ISD::BITCAST)
12857     V = V.getOperand(0);
12858
12859   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12860     SDLoc dl(N);
12861     // Handle only simple case where vector being inserted and vector
12862     // being extracted are of same type, and are half size of larger vectors.
12863     EVT BigVT = V->getOperand(0).getValueType();
12864     EVT SmallVT = V->getOperand(1).getValueType();
12865     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12866       return SDValue();
12867
12868     // Only handle cases where both indexes are constants with the same type.
12869     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12870     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12871
12872     if (InsIdx && ExtIdx &&
12873         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12874         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12875       // Combine:
12876       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12877       // Into:
12878       //    indices are equal or bit offsets are equal => V1
12879       //    otherwise => (extract_subvec V1, ExtIdx)
12880       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12881           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12882         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12883       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12884                          DAG.getNode(ISD::BITCAST, dl,
12885                                      N->getOperand(0).getValueType(),
12886                                      V->getOperand(0)), N->getOperand(1));
12887     }
12888   }
12889
12890   return SDValue();
12891 }
12892
12893 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12894                                                  SDValue V, SelectionDAG &DAG) {
12895   SDLoc DL(V);
12896   EVT VT = V.getValueType();
12897
12898   switch (V.getOpcode()) {
12899   default:
12900     return V;
12901
12902   case ISD::CONCAT_VECTORS: {
12903     EVT OpVT = V->getOperand(0).getValueType();
12904     int OpSize = OpVT.getVectorNumElements();
12905     SmallBitVector OpUsedElements(OpSize, false);
12906     bool FoundSimplification = false;
12907     SmallVector<SDValue, 4> NewOps;
12908     NewOps.reserve(V->getNumOperands());
12909     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12910       SDValue Op = V->getOperand(i);
12911       bool OpUsed = false;
12912       for (int j = 0; j < OpSize; ++j)
12913         if (UsedElements[i * OpSize + j]) {
12914           OpUsedElements[j] = true;
12915           OpUsed = true;
12916         }
12917       NewOps.push_back(
12918           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12919                  : DAG.getUNDEF(OpVT));
12920       FoundSimplification |= Op == NewOps.back();
12921       OpUsedElements.reset();
12922     }
12923     if (FoundSimplification)
12924       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12925     return V;
12926   }
12927
12928   case ISD::INSERT_SUBVECTOR: {
12929     SDValue BaseV = V->getOperand(0);
12930     SDValue SubV = V->getOperand(1);
12931     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12932     if (!IdxN)
12933       return V;
12934
12935     int SubSize = SubV.getValueType().getVectorNumElements();
12936     int Idx = IdxN->getZExtValue();
12937     bool SubVectorUsed = false;
12938     SmallBitVector SubUsedElements(SubSize, false);
12939     for (int i = 0; i < SubSize; ++i)
12940       if (UsedElements[i + Idx]) {
12941         SubVectorUsed = true;
12942         SubUsedElements[i] = true;
12943         UsedElements[i + Idx] = false;
12944       }
12945
12946     // Now recurse on both the base and sub vectors.
12947     SDValue SimplifiedSubV =
12948         SubVectorUsed
12949             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12950             : DAG.getUNDEF(SubV.getValueType());
12951     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12952     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12953       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12954                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12955     return V;
12956   }
12957   }
12958 }
12959
12960 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12961                                        SDValue N1, SelectionDAG &DAG) {
12962   EVT VT = SVN->getValueType(0);
12963   int NumElts = VT.getVectorNumElements();
12964   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12965   for (int M : SVN->getMask())
12966     if (M >= 0 && M < NumElts)
12967       N0UsedElements[M] = true;
12968     else if (M >= NumElts)
12969       N1UsedElements[M - NumElts] = true;
12970
12971   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12972   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12973   if (S0 == N0 && S1 == N1)
12974     return SDValue();
12975
12976   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12977 }
12978
12979 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12980 // or turn a shuffle of a single concat into simpler shuffle then concat.
12981 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12982   EVT VT = N->getValueType(0);
12983   unsigned NumElts = VT.getVectorNumElements();
12984
12985   SDValue N0 = N->getOperand(0);
12986   SDValue N1 = N->getOperand(1);
12987   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12988
12989   SmallVector<SDValue, 4> Ops;
12990   EVT ConcatVT = N0.getOperand(0).getValueType();
12991   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12992   unsigned NumConcats = NumElts / NumElemsPerConcat;
12993
12994   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12995   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12996   // half vector elements.
12997   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12998       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12999                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13000     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13001                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13002     N1 = DAG.getUNDEF(ConcatVT);
13003     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13004   }
13005
13006   // Look at every vector that's inserted. We're looking for exact
13007   // subvector-sized copies from a concatenated vector
13008   for (unsigned I = 0; I != NumConcats; ++I) {
13009     // Make sure we're dealing with a copy.
13010     unsigned Begin = I * NumElemsPerConcat;
13011     bool AllUndef = true, NoUndef = true;
13012     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13013       if (SVN->getMaskElt(J) >= 0)
13014         AllUndef = false;
13015       else
13016         NoUndef = false;
13017     }
13018
13019     if (NoUndef) {
13020       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13021         return SDValue();
13022
13023       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13024         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13025           return SDValue();
13026
13027       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13028       if (FirstElt < N0.getNumOperands())
13029         Ops.push_back(N0.getOperand(FirstElt));
13030       else
13031         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13032
13033     } else if (AllUndef) {
13034       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13035     } else { // Mixed with general masks and undefs, can't do optimization.
13036       return SDValue();
13037     }
13038   }
13039
13040   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13041 }
13042
13043 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13044   EVT VT = N->getValueType(0);
13045   unsigned NumElts = VT.getVectorNumElements();
13046
13047   SDValue N0 = N->getOperand(0);
13048   SDValue N1 = N->getOperand(1);
13049
13050   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13051
13052   // Canonicalize shuffle undef, undef -> undef
13053   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13054     return DAG.getUNDEF(VT);
13055
13056   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13057
13058   // Canonicalize shuffle v, v -> v, undef
13059   if (N0 == N1) {
13060     SmallVector<int, 8> NewMask;
13061     for (unsigned i = 0; i != NumElts; ++i) {
13062       int Idx = SVN->getMaskElt(i);
13063       if (Idx >= (int)NumElts) Idx -= NumElts;
13064       NewMask.push_back(Idx);
13065     }
13066     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13067                                 &NewMask[0]);
13068   }
13069
13070   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13071   if (N0.getOpcode() == ISD::UNDEF) {
13072     SmallVector<int, 8> NewMask;
13073     for (unsigned i = 0; i != NumElts; ++i) {
13074       int Idx = SVN->getMaskElt(i);
13075       if (Idx >= 0) {
13076         if (Idx >= (int)NumElts)
13077           Idx -= NumElts;
13078         else
13079           Idx = -1; // remove reference to lhs
13080       }
13081       NewMask.push_back(Idx);
13082     }
13083     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13084                                 &NewMask[0]);
13085   }
13086
13087   // Remove references to rhs if it is undef
13088   if (N1.getOpcode() == ISD::UNDEF) {
13089     bool Changed = false;
13090     SmallVector<int, 8> NewMask;
13091     for (unsigned i = 0; i != NumElts; ++i) {
13092       int Idx = SVN->getMaskElt(i);
13093       if (Idx >= (int)NumElts) {
13094         Idx = -1;
13095         Changed = true;
13096       }
13097       NewMask.push_back(Idx);
13098     }
13099     if (Changed)
13100       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13101   }
13102
13103   // If it is a splat, check if the argument vector is another splat or a
13104   // build_vector.
13105   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13106     SDNode *V = N0.getNode();
13107
13108     // If this is a bit convert that changes the element type of the vector but
13109     // not the number of vector elements, look through it.  Be careful not to
13110     // look though conversions that change things like v4f32 to v2f64.
13111     if (V->getOpcode() == ISD::BITCAST) {
13112       SDValue ConvInput = V->getOperand(0);
13113       if (ConvInput.getValueType().isVector() &&
13114           ConvInput.getValueType().getVectorNumElements() == NumElts)
13115         V = ConvInput.getNode();
13116     }
13117
13118     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13119       assert(V->getNumOperands() == NumElts &&
13120              "BUILD_VECTOR has wrong number of operands");
13121       SDValue Base;
13122       bool AllSame = true;
13123       for (unsigned i = 0; i != NumElts; ++i) {
13124         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13125           Base = V->getOperand(i);
13126           break;
13127         }
13128       }
13129       // Splat of <u, u, u, u>, return <u, u, u, u>
13130       if (!Base.getNode())
13131         return N0;
13132       for (unsigned i = 0; i != NumElts; ++i) {
13133         if (V->getOperand(i) != Base) {
13134           AllSame = false;
13135           break;
13136         }
13137       }
13138       // Splat of <x, x, x, x>, return <x, x, x, x>
13139       if (AllSame)
13140         return N0;
13141
13142       // Canonicalize any other splat as a build_vector.
13143       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13144       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13145       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13146                                   V->getValueType(0), Ops);
13147
13148       // We may have jumped through bitcasts, so the type of the
13149       // BUILD_VECTOR may not match the type of the shuffle.
13150       if (V->getValueType(0) != VT)
13151         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13152       return NewBV;
13153     }
13154   }
13155
13156   // There are various patterns used to build up a vector from smaller vectors,
13157   // subvectors, or elements. Scan chains of these and replace unused insertions
13158   // or components with undef.
13159   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13160     return S;
13161
13162   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13163       Level < AfterLegalizeVectorOps &&
13164       (N1.getOpcode() == ISD::UNDEF ||
13165       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13166        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13167     SDValue V = partitionShuffleOfConcats(N, DAG);
13168
13169     if (V.getNode())
13170       return V;
13171   }
13172
13173   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13174   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13175   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13176     SmallVector<SDValue, 8> Ops;
13177     for (int M : SVN->getMask()) {
13178       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13179       if (M >= 0) {
13180         int Idx = M % NumElts;
13181         SDValue &S = (M < (int)NumElts ? N0 : N1);
13182         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13183           Op = S.getOperand(Idx);
13184         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13185           if (Idx == 0)
13186             Op = S.getOperand(0);
13187         } else {
13188           // Operand can't be combined - bail out.
13189           break;
13190         }
13191       }
13192       Ops.push_back(Op);
13193     }
13194     if (Ops.size() == VT.getVectorNumElements()) {
13195       // BUILD_VECTOR requires all inputs to be of the same type, find the
13196       // maximum type and extend them all.
13197       EVT SVT = VT.getScalarType();
13198       if (SVT.isInteger())
13199         for (SDValue &Op : Ops)
13200           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13201       if (SVT != VT.getScalarType())
13202         for (SDValue &Op : Ops)
13203           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13204                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13205                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13206       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13207     }
13208   }
13209
13210   // If this shuffle only has a single input that is a bitcasted shuffle,
13211   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13212   // back to their original types.
13213   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13214       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13215       TLI.isTypeLegal(VT)) {
13216
13217     // Peek through the bitcast only if there is one user.
13218     SDValue BC0 = N0;
13219     while (BC0.getOpcode() == ISD::BITCAST) {
13220       if (!BC0.hasOneUse())
13221         break;
13222       BC0 = BC0.getOperand(0);
13223     }
13224
13225     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13226       if (Scale == 1)
13227         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13228
13229       SmallVector<int, 8> NewMask;
13230       for (int M : Mask)
13231         for (int s = 0; s != Scale; ++s)
13232           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13233       return NewMask;
13234     };
13235
13236     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13237       EVT SVT = VT.getScalarType();
13238       EVT InnerVT = BC0->getValueType(0);
13239       EVT InnerSVT = InnerVT.getScalarType();
13240
13241       // Determine which shuffle works with the smaller scalar type.
13242       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13243       EVT ScaleSVT = ScaleVT.getScalarType();
13244
13245       if (TLI.isTypeLegal(ScaleVT) &&
13246           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13247           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13248
13249         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13250         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13251
13252         // Scale the shuffle masks to the smaller scalar type.
13253         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13254         SmallVector<int, 8> InnerMask =
13255             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13256         SmallVector<int, 8> OuterMask =
13257             ScaleShuffleMask(SVN->getMask(), OuterScale);
13258
13259         // Merge the shuffle masks.
13260         SmallVector<int, 8> NewMask;
13261         for (int M : OuterMask)
13262           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13263
13264         // Test for shuffle mask legality over both commutations.
13265         SDValue SV0 = BC0->getOperand(0);
13266         SDValue SV1 = BC0->getOperand(1);
13267         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13268         if (!LegalMask) {
13269           std::swap(SV0, SV1);
13270           ShuffleVectorSDNode::commuteMask(NewMask);
13271           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13272         }
13273
13274         if (LegalMask) {
13275           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13276           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13277           return DAG.getNode(
13278               ISD::BITCAST, SDLoc(N), VT,
13279               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13280         }
13281       }
13282     }
13283   }
13284
13285   // Canonicalize shuffles according to rules:
13286   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13287   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13288   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13289   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13290       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13291       TLI.isTypeLegal(VT)) {
13292     // The incoming shuffle must be of the same type as the result of the
13293     // current shuffle.
13294     assert(N1->getOperand(0).getValueType() == VT &&
13295            "Shuffle types don't match");
13296
13297     SDValue SV0 = N1->getOperand(0);
13298     SDValue SV1 = N1->getOperand(1);
13299     bool HasSameOp0 = N0 == SV0;
13300     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13301     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13302       // Commute the operands of this shuffle so that next rule
13303       // will trigger.
13304       return DAG.getCommutedVectorShuffle(*SVN);
13305   }
13306
13307   // Try to fold according to rules:
13308   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13309   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13310   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13311   // Don't try to fold shuffles with illegal type.
13312   // Only fold if this shuffle is the only user of the other shuffle.
13313   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13314       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13315     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13316
13317     // The incoming shuffle must be of the same type as the result of the
13318     // current shuffle.
13319     assert(OtherSV->getOperand(0).getValueType() == VT &&
13320            "Shuffle types don't match");
13321
13322     SDValue SV0, SV1;
13323     SmallVector<int, 4> Mask;
13324     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13325     // operand, and SV1 as the second operand.
13326     for (unsigned i = 0; i != NumElts; ++i) {
13327       int Idx = SVN->getMaskElt(i);
13328       if (Idx < 0) {
13329         // Propagate Undef.
13330         Mask.push_back(Idx);
13331         continue;
13332       }
13333
13334       SDValue CurrentVec;
13335       if (Idx < (int)NumElts) {
13336         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13337         // shuffle mask to identify which vector is actually referenced.
13338         Idx = OtherSV->getMaskElt(Idx);
13339         if (Idx < 0) {
13340           // Propagate Undef.
13341           Mask.push_back(Idx);
13342           continue;
13343         }
13344
13345         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13346                                            : OtherSV->getOperand(1);
13347       } else {
13348         // This shuffle index references an element within N1.
13349         CurrentVec = N1;
13350       }
13351
13352       // Simple case where 'CurrentVec' is UNDEF.
13353       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13354         Mask.push_back(-1);
13355         continue;
13356       }
13357
13358       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13359       // will be the first or second operand of the combined shuffle.
13360       Idx = Idx % NumElts;
13361       if (!SV0.getNode() || SV0 == CurrentVec) {
13362         // Ok. CurrentVec is the left hand side.
13363         // Update the mask accordingly.
13364         SV0 = CurrentVec;
13365         Mask.push_back(Idx);
13366         continue;
13367       }
13368
13369       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13370       if (SV1.getNode() && SV1 != CurrentVec)
13371         return SDValue();
13372
13373       // Ok. CurrentVec is the right hand side.
13374       // Update the mask accordingly.
13375       SV1 = CurrentVec;
13376       Mask.push_back(Idx + NumElts);
13377     }
13378
13379     // Check if all indices in Mask are Undef. In case, propagate Undef.
13380     bool isUndefMask = true;
13381     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13382       isUndefMask &= Mask[i] < 0;
13383
13384     if (isUndefMask)
13385       return DAG.getUNDEF(VT);
13386
13387     if (!SV0.getNode())
13388       SV0 = DAG.getUNDEF(VT);
13389     if (!SV1.getNode())
13390       SV1 = DAG.getUNDEF(VT);
13391
13392     // Avoid introducing shuffles with illegal mask.
13393     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13394       ShuffleVectorSDNode::commuteMask(Mask);
13395
13396       if (!TLI.isShuffleMaskLegal(Mask, VT))
13397         return SDValue();
13398
13399       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13400       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13401       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13402       std::swap(SV0, SV1);
13403     }
13404
13405     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13406     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13407     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13408     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13409   }
13410
13411   return SDValue();
13412 }
13413
13414 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13415   SDValue InVal = N->getOperand(0);
13416   EVT VT = N->getValueType(0);
13417
13418   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13419   // with a VECTOR_SHUFFLE.
13420   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13421     SDValue InVec = InVal->getOperand(0);
13422     SDValue EltNo = InVal->getOperand(1);
13423
13424     // FIXME: We could support implicit truncation if the shuffle can be
13425     // scaled to a smaller vector scalar type.
13426     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13427     if (C0 && VT == InVec.getValueType() &&
13428         VT.getScalarType() == InVal.getValueType()) {
13429       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13430       int Elt = C0->getZExtValue();
13431       NewMask[0] = Elt;
13432
13433       if (TLI.isShuffleMaskLegal(NewMask, VT))
13434         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13435                                     NewMask);
13436     }
13437   }
13438
13439   return SDValue();
13440 }
13441
13442 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13443   SDValue N0 = N->getOperand(0);
13444   SDValue N2 = N->getOperand(2);
13445
13446   // If the input vector is a concatenation, and the insert replaces
13447   // one of the halves, we can optimize into a single concat_vectors.
13448   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13449       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13450     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13451     EVT VT = N->getValueType(0);
13452
13453     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13454     // (concat_vectors Z, Y)
13455     if (InsIdx == 0)
13456       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13457                          N->getOperand(1), N0.getOperand(1));
13458
13459     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13460     // (concat_vectors X, Z)
13461     if (InsIdx == VT.getVectorNumElements()/2)
13462       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13463                          N0.getOperand(0), N->getOperand(1));
13464   }
13465
13466   return SDValue();
13467 }
13468
13469 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13470   SDValue N0 = N->getOperand(0);
13471
13472   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13473   if (N0->getOpcode() == ISD::FP16_TO_FP)
13474     return N0->getOperand(0);
13475
13476   return SDValue();
13477 }
13478
13479 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13480   SDValue N0 = N->getOperand(0);
13481
13482   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13483   if (N0->getOpcode() == ISD::AND) {
13484     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13485     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13486       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13487                          N0.getOperand(0));
13488     }
13489   }
13490
13491   return SDValue();
13492 }
13493
13494 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13495 /// with the destination vector and a zero vector.
13496 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13497 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13498 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13499   EVT VT = N->getValueType(0);
13500   SDValue LHS = N->getOperand(0);
13501   SDValue RHS = N->getOperand(1);
13502   SDLoc dl(N);
13503
13504   // Make sure we're not running after operation legalization where it
13505   // may have custom lowered the vector shuffles.
13506   if (LegalOperations)
13507     return SDValue();
13508
13509   if (N->getOpcode() != ISD::AND)
13510     return SDValue();
13511
13512   if (RHS.getOpcode() == ISD::BITCAST)
13513     RHS = RHS.getOperand(0);
13514
13515   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13516     return SDValue();
13517
13518   EVT RVT = RHS.getValueType();
13519   unsigned NumElts = RHS.getNumOperands();
13520
13521   // Attempt to create a valid clear mask, splitting the mask into
13522   // sub elements and checking to see if each is
13523   // all zeros or all ones - suitable for shuffle masking.
13524   auto BuildClearMask = [&](int Split) {
13525     int NumSubElts = NumElts * Split;
13526     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13527
13528     SmallVector<int, 8> Indices;
13529     for (int i = 0; i != NumSubElts; ++i) {
13530       int EltIdx = i / Split;
13531       int SubIdx = i % Split;
13532       SDValue Elt = RHS.getOperand(EltIdx);
13533       if (Elt.getOpcode() == ISD::UNDEF) {
13534         Indices.push_back(-1);
13535         continue;
13536       }
13537
13538       APInt Bits;
13539       if (isa<ConstantSDNode>(Elt))
13540         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13541       else if (isa<ConstantFPSDNode>(Elt))
13542         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13543       else
13544         return SDValue();
13545
13546       // Extract the sub element from the constant bit mask.
13547       if (DAG.getDataLayout().isBigEndian()) {
13548         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13549       } else {
13550         Bits = Bits.lshr(SubIdx * NumSubBits);
13551       }
13552
13553       if (Split > 1)
13554         Bits = Bits.trunc(NumSubBits);
13555
13556       if (Bits.isAllOnesValue())
13557         Indices.push_back(i);
13558       else if (Bits == 0)
13559         Indices.push_back(i + NumSubElts);
13560       else
13561         return SDValue();
13562     }
13563
13564     // Let's see if the target supports this vector_shuffle.
13565     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13566     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13567     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13568       return SDValue();
13569
13570     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13571     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13572                                                    DAG.getBitcast(ClearVT, LHS),
13573                                                    Zero, &Indices[0]));
13574   };
13575
13576   // Determine maximum split level (byte level masking).
13577   int MaxSplit = 1;
13578   if (RVT.getScalarSizeInBits() % 8 == 0)
13579     MaxSplit = RVT.getScalarSizeInBits() / 8;
13580
13581   for (int Split = 1; Split <= MaxSplit; ++Split)
13582     if (RVT.getScalarSizeInBits() % Split == 0)
13583       if (SDValue S = BuildClearMask(Split))
13584         return S;
13585
13586   return SDValue();
13587 }
13588
13589 /// Visit a binary vector operation, like ADD.
13590 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13591   assert(N->getValueType(0).isVector() &&
13592          "SimplifyVBinOp only works on vectors!");
13593
13594   SDValue LHS = N->getOperand(0);
13595   SDValue RHS = N->getOperand(1);
13596   SDValue Ops[] = {LHS, RHS};
13597
13598   // See if we can constant fold the vector operation.
13599   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13600           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13601     return Fold;
13602
13603   // Try to convert a constant mask AND into a shuffle clear mask.
13604   if (SDValue Shuffle = XformToShuffleWithZero(N))
13605     return Shuffle;
13606
13607   // Type legalization might introduce new shuffles in the DAG.
13608   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13609   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13610   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13611       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13612       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13613       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13614     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13615     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13616
13617     if (SVN0->getMask().equals(SVN1->getMask())) {
13618       EVT VT = N->getValueType(0);
13619       SDValue UndefVector = LHS.getOperand(1);
13620       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13621                                      LHS.getOperand(0), RHS.getOperand(0),
13622                                      N->getFlags());
13623       AddUsersToWorklist(N);
13624       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13625                                   &SVN0->getMask()[0]);
13626     }
13627   }
13628
13629   return SDValue();
13630 }
13631
13632 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13633                                     SDValue N1, SDValue N2){
13634   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13635
13636   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13637                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13638
13639   // If we got a simplified select_cc node back from SimplifySelectCC, then
13640   // break it down into a new SETCC node, and a new SELECT node, and then return
13641   // the SELECT node, since we were called with a SELECT node.
13642   if (SCC.getNode()) {
13643     // Check to see if we got a select_cc back (to turn into setcc/select).
13644     // Otherwise, just return whatever node we got back, like fabs.
13645     if (SCC.getOpcode() == ISD::SELECT_CC) {
13646       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13647                                   N0.getValueType(),
13648                                   SCC.getOperand(0), SCC.getOperand(1),
13649                                   SCC.getOperand(4));
13650       AddToWorklist(SETCC.getNode());
13651       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13652                            SCC.getOperand(2), SCC.getOperand(3));
13653     }
13654
13655     return SCC;
13656   }
13657   return SDValue();
13658 }
13659
13660 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13661 /// being selected between, see if we can simplify the select.  Callers of this
13662 /// should assume that TheSelect is deleted if this returns true.  As such, they
13663 /// should return the appropriate thing (e.g. the node) back to the top-level of
13664 /// the DAG combiner loop to avoid it being looked at.
13665 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13666                                     SDValue RHS) {
13667
13668   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13669   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13670   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13671     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13672       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13673       SDValue Sqrt = RHS;
13674       ISD::CondCode CC;
13675       SDValue CmpLHS;
13676       const ConstantFPSDNode *NegZero = nullptr;
13677
13678       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13679         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13680         CmpLHS = TheSelect->getOperand(0);
13681         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13682       } else {
13683         // SELECT or VSELECT
13684         SDValue Cmp = TheSelect->getOperand(0);
13685         if (Cmp.getOpcode() == ISD::SETCC) {
13686           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13687           CmpLHS = Cmp.getOperand(0);
13688           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13689         }
13690       }
13691       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13692           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13693           CC == ISD::SETULT || CC == ISD::SETLT)) {
13694         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13695         CombineTo(TheSelect, Sqrt);
13696         return true;
13697       }
13698     }
13699   }
13700   // Cannot simplify select with vector condition
13701   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13702
13703   // If this is a select from two identical things, try to pull the operation
13704   // through the select.
13705   if (LHS.getOpcode() != RHS.getOpcode() ||
13706       !LHS.hasOneUse() || !RHS.hasOneUse())
13707     return false;
13708
13709   // If this is a load and the token chain is identical, replace the select
13710   // of two loads with a load through a select of the address to load from.
13711   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13712   // constants have been dropped into the constant pool.
13713   if (LHS.getOpcode() == ISD::LOAD) {
13714     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13715     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13716
13717     // Token chains must be identical.
13718     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13719         // Do not let this transformation reduce the number of volatile loads.
13720         LLD->isVolatile() || RLD->isVolatile() ||
13721         // FIXME: If either is a pre/post inc/dec load,
13722         // we'd need to split out the address adjustment.
13723         LLD->isIndexed() || RLD->isIndexed() ||
13724         // If this is an EXTLOAD, the VT's must match.
13725         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13726         // If this is an EXTLOAD, the kind of extension must match.
13727         (LLD->getExtensionType() != RLD->getExtensionType() &&
13728          // The only exception is if one of the extensions is anyext.
13729          LLD->getExtensionType() != ISD::EXTLOAD &&
13730          RLD->getExtensionType() != ISD::EXTLOAD) ||
13731         // FIXME: this discards src value information.  This is
13732         // over-conservative. It would be beneficial to be able to remember
13733         // both potential memory locations.  Since we are discarding
13734         // src value info, don't do the transformation if the memory
13735         // locations are not in the default address space.
13736         LLD->getPointerInfo().getAddrSpace() != 0 ||
13737         RLD->getPointerInfo().getAddrSpace() != 0 ||
13738         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13739                                       LLD->getBasePtr().getValueType()))
13740       return false;
13741
13742     // Check that the select condition doesn't reach either load.  If so,
13743     // folding this will induce a cycle into the DAG.  If not, this is safe to
13744     // xform, so create a select of the addresses.
13745     SDValue Addr;
13746     if (TheSelect->getOpcode() == ISD::SELECT) {
13747       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13748       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13749           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13750         return false;
13751       // The loads must not depend on one another.
13752       if (LLD->isPredecessorOf(RLD) ||
13753           RLD->isPredecessorOf(LLD))
13754         return false;
13755       Addr = DAG.getSelect(SDLoc(TheSelect),
13756                            LLD->getBasePtr().getValueType(),
13757                            TheSelect->getOperand(0), LLD->getBasePtr(),
13758                            RLD->getBasePtr());
13759     } else {  // Otherwise SELECT_CC
13760       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13761       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13762
13763       if ((LLD->hasAnyUseOfValue(1) &&
13764            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13765           (RLD->hasAnyUseOfValue(1) &&
13766            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13767         return false;
13768
13769       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13770                          LLD->getBasePtr().getValueType(),
13771                          TheSelect->getOperand(0),
13772                          TheSelect->getOperand(1),
13773                          LLD->getBasePtr(), RLD->getBasePtr(),
13774                          TheSelect->getOperand(4));
13775     }
13776
13777     SDValue Load;
13778     // It is safe to replace the two loads if they have different alignments,
13779     // but the new load must be the minimum (most restrictive) alignment of the
13780     // inputs.
13781     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13782     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13783     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13784       Load = DAG.getLoad(TheSelect->getValueType(0),
13785                          SDLoc(TheSelect),
13786                          // FIXME: Discards pointer and AA info.
13787                          LLD->getChain(), Addr, MachinePointerInfo(),
13788                          LLD->isVolatile(), LLD->isNonTemporal(),
13789                          isInvariant, Alignment);
13790     } else {
13791       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13792                             RLD->getExtensionType() : LLD->getExtensionType(),
13793                             SDLoc(TheSelect),
13794                             TheSelect->getValueType(0),
13795                             // FIXME: Discards pointer and AA info.
13796                             LLD->getChain(), Addr, MachinePointerInfo(),
13797                             LLD->getMemoryVT(), LLD->isVolatile(),
13798                             LLD->isNonTemporal(), isInvariant, Alignment);
13799     }
13800
13801     // Users of the select now use the result of the load.
13802     CombineTo(TheSelect, Load);
13803
13804     // Users of the old loads now use the new load's chain.  We know the
13805     // old-load value is dead now.
13806     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13807     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13808     return true;
13809   }
13810
13811   return false;
13812 }
13813
13814 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13815 /// where 'cond' is the comparison specified by CC.
13816 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13817                                       SDValue N2, SDValue N3,
13818                                       ISD::CondCode CC, bool NotExtCompare) {
13819   // (x ? y : y) -> y.
13820   if (N2 == N3) return N2;
13821
13822   EVT VT = N2.getValueType();
13823   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13824   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13825
13826   // Determine if the condition we're dealing with is constant
13827   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13828                               N0, N1, CC, DL, false);
13829   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13830
13831   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13832     // fold select_cc true, x, y -> x
13833     // fold select_cc false, x, y -> y
13834     return !SCCC->isNullValue() ? N2 : N3;
13835   }
13836
13837   // Check to see if we can simplify the select into an fabs node
13838   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13839     // Allow either -0.0 or 0.0
13840     if (CFP->isZero()) {
13841       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13842       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13843           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13844           N2 == N3.getOperand(0))
13845         return DAG.getNode(ISD::FABS, DL, VT, N0);
13846
13847       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13848       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13849           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13850           N2.getOperand(0) == N3)
13851         return DAG.getNode(ISD::FABS, DL, VT, N3);
13852     }
13853   }
13854
13855   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13856   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13857   // in it.  This is a win when the constant is not otherwise available because
13858   // it replaces two constant pool loads with one.  We only do this if the FP
13859   // type is known to be legal, because if it isn't, then we are before legalize
13860   // types an we want the other legalization to happen first (e.g. to avoid
13861   // messing with soft float) and if the ConstantFP is not legal, because if
13862   // it is legal, we may not need to store the FP constant in a constant pool.
13863   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13864     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13865       if (TLI.isTypeLegal(N2.getValueType()) &&
13866           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13867                TargetLowering::Legal &&
13868            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13869            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13870           // If both constants have multiple uses, then we won't need to do an
13871           // extra load, they are likely around in registers for other users.
13872           (TV->hasOneUse() || FV->hasOneUse())) {
13873         Constant *Elts[] = {
13874           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13875           const_cast<ConstantFP*>(TV->getConstantFPValue())
13876         };
13877         Type *FPTy = Elts[0]->getType();
13878         const DataLayout &TD = DAG.getDataLayout();
13879
13880         // Create a ConstantArray of the two constants.
13881         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13882         SDValue CPIdx =
13883             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13884                                 TD.getPrefTypeAlignment(FPTy));
13885         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13886
13887         // Get the offsets to the 0 and 1 element of the array so that we can
13888         // select between them.
13889         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13890         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13891         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13892
13893         SDValue Cond = DAG.getSetCC(DL,
13894                                     getSetCCResultType(N0.getValueType()),
13895                                     N0, N1, CC);
13896         AddToWorklist(Cond.getNode());
13897         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13898                                           Cond, One, Zero);
13899         AddToWorklist(CstOffset.getNode());
13900         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13901                             CstOffset);
13902         AddToWorklist(CPIdx.getNode());
13903         return DAG.getLoad(
13904             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13905             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13906             false, false, false, Alignment);
13907       }
13908     }
13909
13910   // Check to see if we can perform the "gzip trick", transforming
13911   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13912   if (isNullConstant(N3) && CC == ISD::SETLT &&
13913       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13914        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13915     EVT XType = N0.getValueType();
13916     EVT AType = N2.getValueType();
13917     if (XType.bitsGE(AType)) {
13918       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13919       // single-bit constant.
13920       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13921         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13922         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13923         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13924                                        getShiftAmountTy(N0.getValueType()));
13925         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13926                                     XType, N0, ShCt);
13927         AddToWorklist(Shift.getNode());
13928
13929         if (XType.bitsGT(AType)) {
13930           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13931           AddToWorklist(Shift.getNode());
13932         }
13933
13934         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13935       }
13936
13937       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13938                                   XType, N0,
13939                                   DAG.getConstant(XType.getSizeInBits() - 1,
13940                                                   SDLoc(N0),
13941                                          getShiftAmountTy(N0.getValueType())));
13942       AddToWorklist(Shift.getNode());
13943
13944       if (XType.bitsGT(AType)) {
13945         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13946         AddToWorklist(Shift.getNode());
13947       }
13948
13949       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13950     }
13951   }
13952
13953   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13954   // where y is has a single bit set.
13955   // A plaintext description would be, we can turn the SELECT_CC into an AND
13956   // when the condition can be materialized as an all-ones register.  Any
13957   // single bit-test can be materialized as an all-ones register with
13958   // shift-left and shift-right-arith.
13959   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13960       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13961     SDValue AndLHS = N0->getOperand(0);
13962     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13963     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13964       // Shift the tested bit over the sign bit.
13965       APInt AndMask = ConstAndRHS->getAPIntValue();
13966       SDValue ShlAmt =
13967         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13968                         getShiftAmountTy(AndLHS.getValueType()));
13969       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13970
13971       // Now arithmetic right shift it all the way over, so the result is either
13972       // all-ones, or zero.
13973       SDValue ShrAmt =
13974         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13975                         getShiftAmountTy(Shl.getValueType()));
13976       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13977
13978       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13979     }
13980   }
13981
13982   // fold select C, 16, 0 -> shl C, 4
13983   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13984       TLI.getBooleanContents(N0.getValueType()) ==
13985           TargetLowering::ZeroOrOneBooleanContent) {
13986
13987     // If the caller doesn't want us to simplify this into a zext of a compare,
13988     // don't do it.
13989     if (NotExtCompare && N2C->isOne())
13990       return SDValue();
13991
13992     // Get a SetCC of the condition
13993     // NOTE: Don't create a SETCC if it's not legal on this target.
13994     if (!LegalOperations ||
13995         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13996       SDValue Temp, SCC;
13997       // cast from setcc result type to select result type
13998       if (LegalTypes) {
13999         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14000                             N0, N1, CC);
14001         if (N2.getValueType().bitsLT(SCC.getValueType()))
14002           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14003                                         N2.getValueType());
14004         else
14005           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14006                              N2.getValueType(), SCC);
14007       } else {
14008         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14009         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14010                            N2.getValueType(), SCC);
14011       }
14012
14013       AddToWorklist(SCC.getNode());
14014       AddToWorklist(Temp.getNode());
14015
14016       if (N2C->isOne())
14017         return Temp;
14018
14019       // shl setcc result by log2 n2c
14020       return DAG.getNode(
14021           ISD::SHL, DL, N2.getValueType(), Temp,
14022           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14023                           getShiftAmountTy(Temp.getValueType())));
14024     }
14025   }
14026
14027   // Check to see if this is an integer abs.
14028   // select_cc setg[te] X,  0,  X, -X ->
14029   // select_cc setgt    X, -1,  X, -X ->
14030   // select_cc setl[te] X,  0, -X,  X ->
14031   // select_cc setlt    X,  1, -X,  X ->
14032   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14033   if (N1C) {
14034     ConstantSDNode *SubC = nullptr;
14035     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14036          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14037         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14038       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14039     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14040               (N1C->isOne() && CC == ISD::SETLT)) &&
14041              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14042       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14043
14044     EVT XType = N0.getValueType();
14045     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14046       SDLoc DL(N0);
14047       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14048                                   N0,
14049                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14050                                          getShiftAmountTy(N0.getValueType())));
14051       SDValue Add = DAG.getNode(ISD::ADD, DL,
14052                                 XType, N0, Shift);
14053       AddToWorklist(Shift.getNode());
14054       AddToWorklist(Add.getNode());
14055       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14056     }
14057   }
14058
14059   return SDValue();
14060 }
14061
14062 /// This is a stub for TargetLowering::SimplifySetCC.
14063 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14064                                    SDValue N1, ISD::CondCode Cond,
14065                                    SDLoc DL, bool foldBooleans) {
14066   TargetLowering::DAGCombinerInfo
14067     DagCombineInfo(DAG, Level, false, this);
14068   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14069 }
14070
14071 /// Given an ISD::SDIV node expressing a divide by constant, return
14072 /// a DAG expression to select that will generate the same value by multiplying
14073 /// by a magic number.
14074 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14075 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14076   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14077   if (!C)
14078     return SDValue();
14079
14080   // Avoid division by zero.
14081   if (C->isNullValue())
14082     return SDValue();
14083
14084   std::vector<SDNode*> Built;
14085   SDValue S =
14086       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14087
14088   for (SDNode *N : Built)
14089     AddToWorklist(N);
14090   return S;
14091 }
14092
14093 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14094 /// DAG expression that will generate the same value by right shifting.
14095 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14096   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14097   if (!C)
14098     return SDValue();
14099
14100   // Avoid division by zero.
14101   if (C->isNullValue())
14102     return SDValue();
14103
14104   std::vector<SDNode *> Built;
14105   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14106
14107   for (SDNode *N : Built)
14108     AddToWorklist(N);
14109   return S;
14110 }
14111
14112 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14113 /// expression that will generate the same value by multiplying by a magic
14114 /// number.
14115 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14116 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14117   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14118   if (!C)
14119     return SDValue();
14120
14121   // Avoid division by zero.
14122   if (C->isNullValue())
14123     return SDValue();
14124
14125   std::vector<SDNode*> Built;
14126   SDValue S =
14127       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14128
14129   for (SDNode *N : Built)
14130     AddToWorklist(N);
14131   return S;
14132 }
14133
14134 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14135   if (Level >= AfterLegalizeDAG)
14136     return SDValue();
14137
14138   // Expose the DAG combiner to the target combiner implementations.
14139   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14140
14141   unsigned Iterations = 0;
14142   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14143     if (Iterations) {
14144       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14145       // For the reciprocal, we need to find the zero of the function:
14146       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14147       //     =>
14148       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14149       //     does not require additional intermediate precision]
14150       EVT VT = Op.getValueType();
14151       SDLoc DL(Op);
14152       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14153
14154       AddToWorklist(Est.getNode());
14155
14156       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14157       for (unsigned i = 0; i < Iterations; ++i) {
14158         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14159         AddToWorklist(NewEst.getNode());
14160
14161         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14162         AddToWorklist(NewEst.getNode());
14163
14164         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14165         AddToWorklist(NewEst.getNode());
14166
14167         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14168         AddToWorklist(Est.getNode());
14169       }
14170     }
14171     return Est;
14172   }
14173
14174   return SDValue();
14175 }
14176
14177 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14178 /// For the reciprocal sqrt, we need to find the zero of the function:
14179 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14180 ///     =>
14181 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14182 /// As a result, we precompute A/2 prior to the iteration loop.
14183 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14184                                           unsigned Iterations,
14185                                           SDNodeFlags *Flags) {
14186   EVT VT = Arg.getValueType();
14187   SDLoc DL(Arg);
14188   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14189
14190   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14191   // this entire sequence requires only one FP constant.
14192   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14193   AddToWorklist(HalfArg.getNode());
14194
14195   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14196   AddToWorklist(HalfArg.getNode());
14197
14198   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14199   for (unsigned i = 0; i < Iterations; ++i) {
14200     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14201     AddToWorklist(NewEst.getNode());
14202
14203     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14204     AddToWorklist(NewEst.getNode());
14205
14206     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14207     AddToWorklist(NewEst.getNode());
14208
14209     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14210     AddToWorklist(Est.getNode());
14211   }
14212   return Est;
14213 }
14214
14215 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14216 /// For the reciprocal sqrt, we need to find the zero of the function:
14217 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14218 ///     =>
14219 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14220 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14221                                           unsigned Iterations,
14222                                           SDNodeFlags *Flags) {
14223   EVT VT = Arg.getValueType();
14224   SDLoc DL(Arg);
14225   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14226   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14227
14228   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14229   for (unsigned i = 0; i < Iterations; ++i) {
14230     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14231     AddToWorklist(HalfEst.getNode());
14232
14233     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14234     AddToWorklist(Est.getNode());
14235
14236     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14237     AddToWorklist(Est.getNode());
14238
14239     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14240     AddToWorklist(Est.getNode());
14241
14242     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14243     AddToWorklist(Est.getNode());
14244   }
14245   return Est;
14246 }
14247
14248 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14249   if (Level >= AfterLegalizeDAG)
14250     return SDValue();
14251
14252   // Expose the DAG combiner to the target combiner implementations.
14253   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14254   unsigned Iterations = 0;
14255   bool UseOneConstNR = false;
14256   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14257     AddToWorklist(Est.getNode());
14258     if (Iterations) {
14259       Est = UseOneConstNR ?
14260         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14261         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14262     }
14263     return Est;
14264   }
14265
14266   return SDValue();
14267 }
14268
14269 /// Return true if base is a frame index, which is known not to alias with
14270 /// anything but itself.  Provides base object and offset as results.
14271 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14272                            const GlobalValue *&GV, const void *&CV) {
14273   // Assume it is a primitive operation.
14274   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14275
14276   // If it's an adding a simple constant then integrate the offset.
14277   if (Base.getOpcode() == ISD::ADD) {
14278     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14279       Base = Base.getOperand(0);
14280       Offset += C->getZExtValue();
14281     }
14282   }
14283
14284   // Return the underlying GlobalValue, and update the Offset.  Return false
14285   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14286   // by multiple nodes with different offsets.
14287   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14288     GV = G->getGlobal();
14289     Offset += G->getOffset();
14290     return false;
14291   }
14292
14293   // Return the underlying Constant value, and update the Offset.  Return false
14294   // for ConstantSDNodes since the same constant pool entry may be represented
14295   // by multiple nodes with different offsets.
14296   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14297     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14298                                          : (const void *)C->getConstVal();
14299     Offset += C->getOffset();
14300     return false;
14301   }
14302   // If it's any of the following then it can't alias with anything but itself.
14303   return isa<FrameIndexSDNode>(Base);
14304 }
14305
14306 /// Return true if there is any possibility that the two addresses overlap.
14307 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14308   // If they are the same then they must be aliases.
14309   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14310
14311   // If they are both volatile then they cannot be reordered.
14312   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14313
14314   // If one operation reads from invariant memory, and the other may store, they
14315   // cannot alias. These should really be checking the equivalent of mayWrite,
14316   // but it only matters for memory nodes other than load /store.
14317   if (Op0->isInvariant() && Op1->writeMem())
14318     return false;
14319
14320   if (Op1->isInvariant() && Op0->writeMem())
14321     return false;
14322
14323   // Gather base node and offset information.
14324   SDValue Base1, Base2;
14325   int64_t Offset1, Offset2;
14326   const GlobalValue *GV1, *GV2;
14327   const void *CV1, *CV2;
14328   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14329                                       Base1, Offset1, GV1, CV1);
14330   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14331                                       Base2, Offset2, GV2, CV2);
14332
14333   // If they have a same base address then check to see if they overlap.
14334   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14335     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14336              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14337
14338   // It is possible for different frame indices to alias each other, mostly
14339   // when tail call optimization reuses return address slots for arguments.
14340   // To catch this case, look up the actual index of frame indices to compute
14341   // the real alias relationship.
14342   if (isFrameIndex1 && isFrameIndex2) {
14343     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14344     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14345     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14346     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14347              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14348   }
14349
14350   // Otherwise, if we know what the bases are, and they aren't identical, then
14351   // we know they cannot alias.
14352   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14353     return false;
14354
14355   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14356   // compared to the size and offset of the access, we may be able to prove they
14357   // do not alias.  This check is conservative for now to catch cases created by
14358   // splitting vector types.
14359   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14360       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14361       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14362        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14363       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14364     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14365     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14366
14367     // There is no overlap between these relatively aligned accesses of similar
14368     // size, return no alias.
14369     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14370         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14371       return false;
14372   }
14373
14374   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14375                    ? CombinerGlobalAA
14376                    : DAG.getSubtarget().useAA();
14377 #ifndef NDEBUG
14378   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14379       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14380     UseAA = false;
14381 #endif
14382   if (UseAA &&
14383       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14384     // Use alias analysis information.
14385     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14386                                  Op1->getSrcValueOffset());
14387     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14388         Op0->getSrcValueOffset() - MinOffset;
14389     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14390         Op1->getSrcValueOffset() - MinOffset;
14391     AliasResult AAResult =
14392         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14393                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14394                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14395                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14396     if (AAResult == NoAlias)
14397       return false;
14398   }
14399
14400   // Otherwise we have to assume they alias.
14401   return true;
14402 }
14403
14404 /// Walk up chain skipping non-aliasing memory nodes,
14405 /// looking for aliasing nodes and adding them to the Aliases vector.
14406 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14407                                    SmallVectorImpl<SDValue> &Aliases) {
14408   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14409   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14410
14411   // Get alias information for node.
14412   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14413
14414   // Starting off.
14415   Chains.push_back(OriginalChain);
14416   unsigned Depth = 0;
14417
14418   // Look at each chain and determine if it is an alias.  If so, add it to the
14419   // aliases list.  If not, then continue up the chain looking for the next
14420   // candidate.
14421   while (!Chains.empty()) {
14422     SDValue Chain = Chains.pop_back_val();
14423
14424     // For TokenFactor nodes, look at each operand and only continue up the
14425     // chain until we reach the depth limit.
14426     //
14427     // FIXME: The depth check could be made to return the last non-aliasing
14428     // chain we found before we hit a tokenfactor rather than the original
14429     // chain.
14430     if (Depth > 6) {
14431       Aliases.clear();
14432       Aliases.push_back(OriginalChain);
14433       return;
14434     }
14435
14436     // Don't bother if we've been before.
14437     if (!Visited.insert(Chain.getNode()).second)
14438       continue;
14439
14440     switch (Chain.getOpcode()) {
14441     case ISD::EntryToken:
14442       // Entry token is ideal chain operand, but handled in FindBetterChain.
14443       break;
14444
14445     case ISD::LOAD:
14446     case ISD::STORE: {
14447       // Get alias information for Chain.
14448       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14449           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14450
14451       // If chain is alias then stop here.
14452       if (!(IsLoad && IsOpLoad) &&
14453           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14454         Aliases.push_back(Chain);
14455       } else {
14456         // Look further up the chain.
14457         Chains.push_back(Chain.getOperand(0));
14458         ++Depth;
14459       }
14460       break;
14461     }
14462
14463     case ISD::TokenFactor:
14464       // We have to check each of the operands of the token factor for "small"
14465       // token factors, so we queue them up.  Adding the operands to the queue
14466       // (stack) in reverse order maintains the original order and increases the
14467       // likelihood that getNode will find a matching token factor (CSE.)
14468       if (Chain.getNumOperands() > 16) {
14469         Aliases.push_back(Chain);
14470         break;
14471       }
14472       for (unsigned n = Chain.getNumOperands(); n;)
14473         Chains.push_back(Chain.getOperand(--n));
14474       ++Depth;
14475       break;
14476
14477     default:
14478       // For all other instructions we will just have to take what we can get.
14479       Aliases.push_back(Chain);
14480       break;
14481     }
14482   }
14483
14484   // We need to be careful here to also search for aliases through the
14485   // value operand of a store, etc. Consider the following situation:
14486   //   Token1 = ...
14487   //   L1 = load Token1, %52
14488   //   S1 = store Token1, L1, %51
14489   //   L2 = load Token1, %52+8
14490   //   S2 = store Token1, L2, %51+8
14491   //   Token2 = Token(S1, S2)
14492   //   L3 = load Token2, %53
14493   //   S3 = store Token2, L3, %52
14494   //   L4 = load Token2, %53+8
14495   //   S4 = store Token2, L4, %52+8
14496   // If we search for aliases of S3 (which loads address %52), and we look
14497   // only through the chain, then we'll miss the trivial dependence on L1
14498   // (which also loads from %52). We then might change all loads and
14499   // stores to use Token1 as their chain operand, which could result in
14500   // copying %53 into %52 before copying %52 into %51 (which should
14501   // happen first).
14502   //
14503   // The problem is, however, that searching for such data dependencies
14504   // can become expensive, and the cost is not directly related to the
14505   // chain depth. Instead, we'll rule out such configurations here by
14506   // insisting that we've visited all chain users (except for users
14507   // of the original chain, which is not necessary). When doing this,
14508   // we need to look through nodes we don't care about (otherwise, things
14509   // like register copies will interfere with trivial cases).
14510
14511   SmallVector<const SDNode *, 16> Worklist;
14512   for (const SDNode *N : Visited)
14513     if (N != OriginalChain.getNode())
14514       Worklist.push_back(N);
14515
14516   while (!Worklist.empty()) {
14517     const SDNode *M = Worklist.pop_back_val();
14518
14519     // We have already visited M, and want to make sure we've visited any uses
14520     // of M that we care about. For uses that we've not visisted, and don't
14521     // care about, queue them to the worklist.
14522
14523     for (SDNode::use_iterator UI = M->use_begin(),
14524          UIE = M->use_end(); UI != UIE; ++UI)
14525       if (UI.getUse().getValueType() == MVT::Other &&
14526           Visited.insert(*UI).second) {
14527         if (isa<MemSDNode>(*UI)) {
14528           // We've not visited this use, and we care about it (it could have an
14529           // ordering dependency with the original node).
14530           Aliases.clear();
14531           Aliases.push_back(OriginalChain);
14532           return;
14533         }
14534
14535         // We've not visited this use, but we don't care about it. Mark it as
14536         // visited and enqueue it to the worklist.
14537         Worklist.push_back(*UI);
14538       }
14539   }
14540 }
14541
14542 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14543 /// (aliasing node.)
14544 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14545   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14546
14547   // Accumulate all the aliases to this node.
14548   GatherAllAliases(N, OldChain, Aliases);
14549
14550   // If no operands then chain to entry token.
14551   if (Aliases.size() == 0)
14552     return DAG.getEntryNode();
14553
14554   // If a single operand then chain to it.  We don't need to revisit it.
14555   if (Aliases.size() == 1)
14556     return Aliases[0];
14557
14558   // Construct a custom tailored token factor.
14559   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14560 }
14561
14562 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14563   // This holds the base pointer, index, and the offset in bytes from the base
14564   // pointer.
14565   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14566
14567   // We must have a base and an offset.
14568   if (!BasePtr.Base.getNode())
14569     return false;
14570
14571   // Do not handle stores to undef base pointers.
14572   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14573     return false;
14574
14575   SmallVector<StoreSDNode *, 8> ChainedStores;
14576   ChainedStores.push_back(St);
14577
14578   // Walk up the chain and look for nodes with offsets from the same
14579   // base pointer. Stop when reaching an instruction with a different kind
14580   // or instruction which has a different base pointer.
14581   StoreSDNode *Index = St;
14582   while (Index) {
14583     // If the chain has more than one use, then we can't reorder the mem ops.
14584     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14585       break;
14586
14587     if (Index->isVolatile() || Index->isIndexed())
14588       break;
14589
14590     // Find the base pointer and offset for this memory node.
14591     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14592
14593     // Check that the base pointer is the same as the original one.
14594     if (!Ptr.equalBaseIndex(BasePtr))
14595       break;
14596
14597     // Find the next memory operand in the chain. If the next operand in the
14598     // chain is a store then move up and continue the scan with the next
14599     // memory operand. If the next operand is a load save it and use alias
14600     // information to check if it interferes with anything.
14601     SDNode *NextInChain = Index->getChain().getNode();
14602     while (true) {
14603       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14604         // We found a store node. Use it for the next iteration.
14605         ChainedStores.push_back(STn);
14606         Index = STn;
14607         break;
14608       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14609         NextInChain = Ldn->getChain().getNode();
14610         continue;
14611       } else {
14612         Index = nullptr;
14613         break;
14614       }
14615     }
14616   }
14617
14618   bool MadeChange = false;
14619   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14620
14621   for (StoreSDNode *ChainedStore : ChainedStores) {
14622     SDValue Chain = ChainedStore->getChain();
14623     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14624
14625     if (Chain != BetterChain) {
14626       MadeChange = true;
14627       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14628     }
14629   }
14630
14631   // Do all replacements after finding the replacements to make to avoid making
14632   // the chains more complicated by introducing new TokenFactors.
14633   for (auto Replacement : BetterChains)
14634     replaceStoreChain(Replacement.first, Replacement.second);
14635
14636   return MadeChange;
14637 }
14638
14639 /// This is the entry point for the file.
14640 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14641                            CodeGenOpt::Level OptLevel) {
14642   /// This is the main entry point to this class.
14643   DAGCombiner(*this, AA, OptLevel).Run(Level);
14644 }