Use the 'arcp' fast-math-flag when combining repeated FP divisors
[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 the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2333   // Otherwise, we break the simplification logic in visitREM().
2334   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2335     if (SDValue DivRem = useDivRem(N))
2336         return DivRem;
2337
2338   // undef / X -> 0
2339   if (N0.getOpcode() == ISD::UNDEF)
2340     return DAG.getConstant(0, DL, VT);
2341   // X / undef -> undef
2342   if (N1.getOpcode() == ISD::UNDEF)
2343     return N1;
2344
2345   return SDValue();
2346 }
2347
2348 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2349   SDValue N0 = N->getOperand(0);
2350   SDValue N1 = N->getOperand(1);
2351   EVT VT = N->getValueType(0);
2352
2353   // fold vector ops
2354   if (VT.isVector())
2355     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2356       return FoldedVOp;
2357
2358   SDLoc DL(N);
2359
2360   // fold (udiv c1, c2) -> c1/c2
2361   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2362   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2363   if (N0C && N1C)
2364     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2365                                                     N0C, N1C))
2366       return Folded;
2367   // fold (udiv x, (1 << c)) -> x >>u c
2368   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2369     return DAG.getNode(ISD::SRL, DL, VT, N0,
2370                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2371                                        getShiftAmountTy(N0.getValueType())));
2372
2373   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2374   if (N1.getOpcode() == ISD::SHL) {
2375     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2376       if (SHC->getAPIntValue().isPowerOf2()) {
2377         EVT ADDVT = N1.getOperand(1).getValueType();
2378         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2379                                   N1.getOperand(1),
2380                                   DAG.getConstant(SHC->getAPIntValue()
2381                                                                   .logBase2(),
2382                                                   DL, ADDVT));
2383         AddToWorklist(Add.getNode());
2384         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2385       }
2386     }
2387   }
2388
2389   // fold (udiv x, c) -> alternate
2390   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2391   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2392     if (SDValue Op = BuildUDIV(N))
2393       return Op;
2394
2395   // sdiv, srem -> sdivrem
2396   // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true.
2397   // Otherwise, we break the simplification logic in visitREM().
2398   if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
2399     if (SDValue DivRem = useDivRem(N))
2400         return DivRem;
2401
2402   // undef / X -> 0
2403   if (N0.getOpcode() == ISD::UNDEF)
2404     return DAG.getConstant(0, DL, VT);
2405   // X / undef -> undef
2406   if (N1.getOpcode() == ISD::UNDEF)
2407     return N1;
2408
2409   return SDValue();
2410 }
2411
2412 // handles ISD::SREM and ISD::UREM
2413 SDValue DAGCombiner::visitREM(SDNode *N) {
2414   unsigned Opcode = N->getOpcode();
2415   SDValue N0 = N->getOperand(0);
2416   SDValue N1 = N->getOperand(1);
2417   EVT VT = N->getValueType(0);
2418   bool isSigned = (Opcode == ISD::SREM);
2419   SDLoc DL(N);
2420
2421   // fold (rem c1, c2) -> c1%c2
2422   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2423   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2424   if (N0C && N1C)
2425     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2426       return Folded;
2427
2428   if (isSigned) {
2429     // If we know the sign bits of both operands are zero, strength reduce to a
2430     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2431     if (!VT.isVector()) {
2432       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2433         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2434     }
2435   } else {
2436     // fold (urem x, pow2) -> (and x, pow2-1)
2437     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2438         N1C->getAPIntValue().isPowerOf2()) {
2439       return DAG.getNode(ISD::AND, DL, VT, N0,
2440                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2441     }
2442     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2443     if (N1.getOpcode() == ISD::SHL) {
2444       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2445         if (SHC->getAPIntValue().isPowerOf2()) {
2446           SDValue Add =
2447             DAG.getNode(ISD::ADD, DL, VT, N1,
2448                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2449                                  VT));
2450           AddToWorklist(Add.getNode());
2451           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2452         }
2453       }
2454     }
2455   }
2456
2457   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2458
2459   // If X/C can be simplified by the division-by-constant logic, lower
2460   // X%C to the equivalent of X-X/C*C.
2461   // To avoid mangling nodes, this simplification requires that the combine()
2462   // call for the speculative DIV must not cause a DIVREM conversion.  We guard
2463   // against this by skipping the simplification if isIntDivCheap().  When
2464   // div is not cheap, combine will not return a DIVREM.  Regardless,
2465   // checking cheapness here makes sense since the simplification results in
2466   // fatter code.
2467   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
2468     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2469     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2470     AddToWorklist(Div.getNode());
2471     SDValue OptimizedDiv = combine(Div.getNode());
2472     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2473       assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
2474              (OptimizedDiv.getOpcode() != ISD::SDIVREM));
2475       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2476       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2477       AddToWorklist(Mul.getNode());
2478       return Sub;
2479     }
2480   }
2481
2482   // sdiv, srem -> sdivrem
2483   if (SDValue DivRem = useDivRem(N))
2484     return DivRem.getValue(1);
2485
2486   // undef % X -> 0
2487   if (N0.getOpcode() == ISD::UNDEF)
2488     return DAG.getConstant(0, DL, VT);
2489   // X % undef -> undef
2490   if (N1.getOpcode() == ISD::UNDEF)
2491     return N1;
2492
2493   return SDValue();
2494 }
2495
2496 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2497   SDValue N0 = N->getOperand(0);
2498   SDValue N1 = N->getOperand(1);
2499   EVT VT = N->getValueType(0);
2500   SDLoc DL(N);
2501
2502   // fold (mulhs x, 0) -> 0
2503   if (isNullConstant(N1))
2504     return N1;
2505   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2506   if (isOneConstant(N1)) {
2507     SDLoc DL(N);
2508     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2509                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2510                                        DL,
2511                                        getShiftAmountTy(N0.getValueType())));
2512   }
2513   // fold (mulhs x, undef) -> 0
2514   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2515     return DAG.getConstant(0, SDLoc(N), VT);
2516
2517   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2518   // plus a shift.
2519   if (VT.isSimple() && !VT.isVector()) {
2520     MVT Simple = VT.getSimpleVT();
2521     unsigned SimpleSize = Simple.getSizeInBits();
2522     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2523     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2524       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2525       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2526       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2527       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2528             DAG.getConstant(SimpleSize, DL,
2529                             getShiftAmountTy(N1.getValueType())));
2530       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2531     }
2532   }
2533
2534   return SDValue();
2535 }
2536
2537 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2538   SDValue N0 = N->getOperand(0);
2539   SDValue N1 = N->getOperand(1);
2540   EVT VT = N->getValueType(0);
2541   SDLoc DL(N);
2542
2543   // fold (mulhu x, 0) -> 0
2544   if (isNullConstant(N1))
2545     return N1;
2546   // fold (mulhu x, 1) -> 0
2547   if (isOneConstant(N1))
2548     return DAG.getConstant(0, DL, N0.getValueType());
2549   // fold (mulhu x, undef) -> 0
2550   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2551     return DAG.getConstant(0, DL, VT);
2552
2553   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2554   // plus a shift.
2555   if (VT.isSimple() && !VT.isVector()) {
2556     MVT Simple = VT.getSimpleVT();
2557     unsigned SimpleSize = Simple.getSizeInBits();
2558     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2559     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2560       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2561       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2562       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2563       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2564             DAG.getConstant(SimpleSize, DL,
2565                             getShiftAmountTy(N1.getValueType())));
2566       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2567     }
2568   }
2569
2570   return SDValue();
2571 }
2572
2573 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2574 /// give the opcodes for the two computations that are being performed. Return
2575 /// true if a simplification was made.
2576 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2577                                                 unsigned HiOp) {
2578   // If the high half is not needed, just compute the low half.
2579   bool HiExists = N->hasAnyUseOfValue(1);
2580   if (!HiExists &&
2581       (!LegalOperations ||
2582        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2583     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2584     return CombineTo(N, Res, Res);
2585   }
2586
2587   // If the low half is not needed, just compute the high half.
2588   bool LoExists = N->hasAnyUseOfValue(0);
2589   if (!LoExists &&
2590       (!LegalOperations ||
2591        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2592     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2593     return CombineTo(N, Res, Res);
2594   }
2595
2596   // If both halves are used, return as it is.
2597   if (LoExists && HiExists)
2598     return SDValue();
2599
2600   // If the two computed results can be simplified separately, separate them.
2601   if (LoExists) {
2602     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2603     AddToWorklist(Lo.getNode());
2604     SDValue LoOpt = combine(Lo.getNode());
2605     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2606         (!LegalOperations ||
2607          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2608       return CombineTo(N, LoOpt, LoOpt);
2609   }
2610
2611   if (HiExists) {
2612     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2613     AddToWorklist(Hi.getNode());
2614     SDValue HiOpt = combine(Hi.getNode());
2615     if (HiOpt.getNode() && HiOpt != Hi &&
2616         (!LegalOperations ||
2617          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2618       return CombineTo(N, HiOpt, HiOpt);
2619   }
2620
2621   return SDValue();
2622 }
2623
2624 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2625   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2626     return Res;
2627
2628   EVT VT = N->getValueType(0);
2629   SDLoc DL(N);
2630
2631   // If the type is twice as wide is legal, transform the mulhu to a wider
2632   // multiply plus a shift.
2633   if (VT.isSimple() && !VT.isVector()) {
2634     MVT Simple = VT.getSimpleVT();
2635     unsigned SimpleSize = Simple.getSizeInBits();
2636     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2637     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2638       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2639       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2640       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2641       // Compute the high part as N1.
2642       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2643             DAG.getConstant(SimpleSize, DL,
2644                             getShiftAmountTy(Lo.getValueType())));
2645       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2646       // Compute the low part as N0.
2647       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2648       return CombineTo(N, Lo, Hi);
2649     }
2650   }
2651
2652   return SDValue();
2653 }
2654
2655 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2656   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2657     return Res;
2658
2659   EVT VT = N->getValueType(0);
2660   SDLoc DL(N);
2661
2662   // If the type is twice as wide is legal, transform the mulhu to a wider
2663   // multiply plus a shift.
2664   if (VT.isSimple() && !VT.isVector()) {
2665     MVT Simple = VT.getSimpleVT();
2666     unsigned SimpleSize = Simple.getSizeInBits();
2667     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2668     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2669       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2670       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2671       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2672       // Compute the high part as N1.
2673       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2674             DAG.getConstant(SimpleSize, DL,
2675                             getShiftAmountTy(Lo.getValueType())));
2676       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2677       // Compute the low part as N0.
2678       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2679       return CombineTo(N, Lo, Hi);
2680     }
2681   }
2682
2683   return SDValue();
2684 }
2685
2686 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2687   // (smulo x, 2) -> (saddo x, x)
2688   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2689     if (C2->getAPIntValue() == 2)
2690       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2691                          N->getOperand(0), N->getOperand(0));
2692
2693   return SDValue();
2694 }
2695
2696 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2697   // (umulo x, 2) -> (uaddo x, x)
2698   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2699     if (C2->getAPIntValue() == 2)
2700       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2701                          N->getOperand(0), N->getOperand(0));
2702
2703   return SDValue();
2704 }
2705
2706 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2707   SDValue N0 = N->getOperand(0);
2708   SDValue N1 = N->getOperand(1);
2709   EVT VT = N0.getValueType();
2710
2711   // fold vector ops
2712   if (VT.isVector())
2713     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2714       return FoldedVOp;
2715
2716   // fold (add c1, c2) -> c1+c2
2717   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2718   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2719   if (N0C && N1C)
2720     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2721
2722   // canonicalize constant to RHS
2723   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2724      !isConstantIntBuildVectorOrConstantInt(N1))
2725     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2726
2727   return SDValue();
2728 }
2729
2730 /// If this is a binary operator with two operands of the same opcode, try to
2731 /// simplify it.
2732 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2733   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2734   EVT VT = N0.getValueType();
2735   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2736
2737   // Bail early if none of these transforms apply.
2738   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2739
2740   // For each of OP in AND/OR/XOR:
2741   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2742   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2743   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2744   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2745   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2746   //
2747   // do not sink logical op inside of a vector extend, since it may combine
2748   // into a vsetcc.
2749   EVT Op0VT = N0.getOperand(0).getValueType();
2750   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2751        N0.getOpcode() == ISD::SIGN_EXTEND ||
2752        N0.getOpcode() == ISD::BSWAP ||
2753        // Avoid infinite looping with PromoteIntBinOp.
2754        (N0.getOpcode() == ISD::ANY_EXTEND &&
2755         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2756        (N0.getOpcode() == ISD::TRUNCATE &&
2757         (!TLI.isZExtFree(VT, Op0VT) ||
2758          !TLI.isTruncateFree(Op0VT, VT)) &&
2759         TLI.isTypeLegal(Op0VT))) &&
2760       !VT.isVector() &&
2761       Op0VT == N1.getOperand(0).getValueType() &&
2762       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2763     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2764                                  N0.getOperand(0).getValueType(),
2765                                  N0.getOperand(0), N1.getOperand(0));
2766     AddToWorklist(ORNode.getNode());
2767     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2768   }
2769
2770   // For each of OP in SHL/SRL/SRA/AND...
2771   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2772   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2773   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2774   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2775        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2776       N0.getOperand(1) == N1.getOperand(1)) {
2777     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2778                                  N0.getOperand(0).getValueType(),
2779                                  N0.getOperand(0), N1.getOperand(0));
2780     AddToWorklist(ORNode.getNode());
2781     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2782                        ORNode, N0.getOperand(1));
2783   }
2784
2785   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2786   // Only perform this optimization after type legalization and before
2787   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2788   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2789   // we don't want to undo this promotion.
2790   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2791   // on scalars.
2792   if ((N0.getOpcode() == ISD::BITCAST ||
2793        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2794       Level == AfterLegalizeTypes) {
2795     SDValue In0 = N0.getOperand(0);
2796     SDValue In1 = N1.getOperand(0);
2797     EVT In0Ty = In0.getValueType();
2798     EVT In1Ty = In1.getValueType();
2799     SDLoc DL(N);
2800     // If both incoming values are integers, and the original types are the
2801     // same.
2802     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2803       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2804       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2805       AddToWorklist(Op.getNode());
2806       return BC;
2807     }
2808   }
2809
2810   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2811   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2812   // If both shuffles use the same mask, and both shuffle within a single
2813   // vector, then it is worthwhile to move the swizzle after the operation.
2814   // The type-legalizer generates this pattern when loading illegal
2815   // vector types from memory. In many cases this allows additional shuffle
2816   // optimizations.
2817   // There are other cases where moving the shuffle after the xor/and/or
2818   // is profitable even if shuffles don't perform a swizzle.
2819   // If both shuffles use the same mask, and both shuffles have the same first
2820   // or second operand, then it might still be profitable to move the shuffle
2821   // after the xor/and/or operation.
2822   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2823     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2824     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2825
2826     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2827            "Inputs to shuffles are not the same type");
2828
2829     // Check that both shuffles use the same mask. The masks are known to be of
2830     // the same length because the result vector type is the same.
2831     // Check also that shuffles have only one use to avoid introducing extra
2832     // instructions.
2833     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2834         SVN0->getMask().equals(SVN1->getMask())) {
2835       SDValue ShOp = N0->getOperand(1);
2836
2837       // Don't try to fold this node if it requires introducing a
2838       // build vector of all zeros that might be illegal at this stage.
2839       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2840         if (!LegalTypes)
2841           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2842         else
2843           ShOp = SDValue();
2844       }
2845
2846       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2847       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2848       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2849       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2850         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2851                                       N0->getOperand(0), N1->getOperand(0));
2852         AddToWorklist(NewNode.getNode());
2853         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2854                                     &SVN0->getMask()[0]);
2855       }
2856
2857       // Don't try to fold this node if it requires introducing a
2858       // build vector of all zeros that might be illegal at this stage.
2859       ShOp = N0->getOperand(0);
2860       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2861         if (!LegalTypes)
2862           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2863         else
2864           ShOp = SDValue();
2865       }
2866
2867       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2868       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2869       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2870       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2871         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2872                                       N0->getOperand(1), N1->getOperand(1));
2873         AddToWorklist(NewNode.getNode());
2874         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2875                                     &SVN0->getMask()[0]);
2876       }
2877     }
2878   }
2879
2880   return SDValue();
2881 }
2882
2883 /// This contains all DAGCombine rules which reduce two values combined by
2884 /// an And operation to a single value. This makes them reusable in the context
2885 /// of visitSELECT(). Rules involving constants are not included as
2886 /// visitSELECT() already handles those cases.
2887 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2888                                   SDNode *LocReference) {
2889   EVT VT = N1.getValueType();
2890
2891   // fold (and x, undef) -> 0
2892   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2893     return DAG.getConstant(0, SDLoc(LocReference), VT);
2894   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2895   SDValue LL, LR, RL, RR, CC0, CC1;
2896   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2897     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2898     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2899
2900     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2901         LL.getValueType().isInteger()) {
2902       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2903       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2904         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2905                                      LR.getValueType(), LL, RL);
2906         AddToWorklist(ORNode.getNode());
2907         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2908       }
2909       if (isAllOnesConstant(LR)) {
2910         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2911         if (Op1 == ISD::SETEQ) {
2912           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2913                                         LR.getValueType(), LL, RL);
2914           AddToWorklist(ANDNode.getNode());
2915           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2916         }
2917         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2918         if (Op1 == ISD::SETGT) {
2919           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2920                                        LR.getValueType(), LL, RL);
2921           AddToWorklist(ORNode.getNode());
2922           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2923         }
2924       }
2925     }
2926     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2927     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2928         Op0 == Op1 && LL.getValueType().isInteger() &&
2929       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2930                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2931       SDLoc DL(N0);
2932       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2933                                     LL, DAG.getConstant(1, DL,
2934                                                         LL.getValueType()));
2935       AddToWorklist(ADDNode.getNode());
2936       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2937                           DAG.getConstant(2, DL, LL.getValueType()),
2938                           ISD::SETUGE);
2939     }
2940     // canonicalize equivalent to ll == rl
2941     if (LL == RR && LR == RL) {
2942       Op1 = ISD::getSetCCSwappedOperands(Op1);
2943       std::swap(RL, RR);
2944     }
2945     if (LL == RL && LR == RR) {
2946       bool isInteger = LL.getValueType().isInteger();
2947       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2948       if (Result != ISD::SETCC_INVALID &&
2949           (!LegalOperations ||
2950            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2951             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2952         EVT CCVT = getSetCCResultType(LL.getValueType());
2953         if (N0.getValueType() == CCVT ||
2954             (!LegalOperations && N0.getValueType() == MVT::i1))
2955           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2956                               LL, LR, Result);
2957       }
2958     }
2959   }
2960
2961   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2962       VT.getSizeInBits() <= 64) {
2963     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2964       APInt ADDC = ADDI->getAPIntValue();
2965       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2966         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2967         // immediate for an add, but it is legal if its top c2 bits are set,
2968         // transform the ADD so the immediate doesn't need to be materialized
2969         // in a register.
2970         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2971           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2972                                              SRLI->getZExtValue());
2973           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2974             ADDC |= Mask;
2975             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2976               SDLoc DL(N0);
2977               SDValue NewAdd =
2978                 DAG.getNode(ISD::ADD, DL, VT,
2979                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2980               CombineTo(N0.getNode(), NewAdd);
2981               // Return N so it doesn't get rechecked!
2982               return SDValue(LocReference, 0);
2983             }
2984           }
2985         }
2986       }
2987     }
2988   }
2989
2990   return SDValue();
2991 }
2992
2993 SDValue DAGCombiner::visitAND(SDNode *N) {
2994   SDValue N0 = N->getOperand(0);
2995   SDValue N1 = N->getOperand(1);
2996   EVT VT = N1.getValueType();
2997
2998   // fold vector ops
2999   if (VT.isVector()) {
3000     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3001       return FoldedVOp;
3002
3003     // fold (and x, 0) -> 0, vector edition
3004     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3005       // do not return N0, because undef node may exist in N0
3006       return DAG.getConstant(
3007           APInt::getNullValue(
3008               N0.getValueType().getScalarType().getSizeInBits()),
3009           SDLoc(N), N0.getValueType());
3010     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3011       // do not return N1, because undef node may exist in N1
3012       return DAG.getConstant(
3013           APInt::getNullValue(
3014               N1.getValueType().getScalarType().getSizeInBits()),
3015           SDLoc(N), N1.getValueType());
3016
3017     // fold (and x, -1) -> x, vector edition
3018     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3019       return N1;
3020     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3021       return N0;
3022   }
3023
3024   // fold (and c1, c2) -> c1&c2
3025   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3026   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3027   if (N0C && N1C && !N1C->isOpaque())
3028     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3029   // canonicalize constant to RHS
3030   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3031      !isConstantIntBuildVectorOrConstantInt(N1))
3032     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3033   // fold (and x, -1) -> x
3034   if (isAllOnesConstant(N1))
3035     return N0;
3036   // if (and x, c) is known to be zero, return 0
3037   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3038   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3039                                    APInt::getAllOnesValue(BitWidth)))
3040     return DAG.getConstant(0, SDLoc(N), VT);
3041   // reassociate and
3042   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3043     return RAND;
3044   // fold (and (or x, C), D) -> D if (C & D) == D
3045   if (N1C && N0.getOpcode() == ISD::OR)
3046     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3047       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3048         return N1;
3049   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3050   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3051     SDValue N0Op0 = N0.getOperand(0);
3052     APInt Mask = ~N1C->getAPIntValue();
3053     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3054     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3055       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3056                                  N0.getValueType(), N0Op0);
3057
3058       // Replace uses of the AND with uses of the Zero extend node.
3059       CombineTo(N, Zext);
3060
3061       // We actually want to replace all uses of the any_extend with the
3062       // zero_extend, to avoid duplicating things.  This will later cause this
3063       // AND to be folded.
3064       CombineTo(N0.getNode(), Zext);
3065       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3066     }
3067   }
3068   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3069   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3070   // already be zero by virtue of the width of the base type of the load.
3071   //
3072   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3073   // more cases.
3074   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3075        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3076       N0.getOpcode() == ISD::LOAD) {
3077     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3078                                          N0 : N0.getOperand(0) );
3079
3080     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3081     // This can be a pure constant or a vector splat, in which case we treat the
3082     // vector as a scalar and use the splat value.
3083     APInt Constant = APInt::getNullValue(1);
3084     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3085       Constant = C->getAPIntValue();
3086     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3087       APInt SplatValue, SplatUndef;
3088       unsigned SplatBitSize;
3089       bool HasAnyUndefs;
3090       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3091                                              SplatBitSize, HasAnyUndefs);
3092       if (IsSplat) {
3093         // Undef bits can contribute to a possible optimisation if set, so
3094         // set them.
3095         SplatValue |= SplatUndef;
3096
3097         // The splat value may be something like "0x00FFFFFF", which means 0 for
3098         // the first vector value and FF for the rest, repeating. We need a mask
3099         // that will apply equally to all members of the vector, so AND all the
3100         // lanes of the constant together.
3101         EVT VT = Vector->getValueType(0);
3102         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3103
3104         // If the splat value has been compressed to a bitlength lower
3105         // than the size of the vector lane, we need to re-expand it to
3106         // the lane size.
3107         if (BitWidth > SplatBitSize)
3108           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3109                SplatBitSize < BitWidth;
3110                SplatBitSize = SplatBitSize * 2)
3111             SplatValue |= SplatValue.shl(SplatBitSize);
3112
3113         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3114         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3115         if (SplatBitSize % BitWidth == 0) {
3116           Constant = APInt::getAllOnesValue(BitWidth);
3117           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3118             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3119         }
3120       }
3121     }
3122
3123     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3124     // actually legal and isn't going to get expanded, else this is a false
3125     // optimisation.
3126     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3127                                                     Load->getValueType(0),
3128                                                     Load->getMemoryVT());
3129
3130     // Resize the constant to the same size as the original memory access before
3131     // extension. If it is still the AllOnesValue then this AND is completely
3132     // unneeded.
3133     Constant =
3134       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3135
3136     bool B;
3137     switch (Load->getExtensionType()) {
3138     default: B = false; break;
3139     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3140     case ISD::ZEXTLOAD:
3141     case ISD::NON_EXTLOAD: B = true; break;
3142     }
3143
3144     if (B && Constant.isAllOnesValue()) {
3145       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3146       // preserve semantics once we get rid of the AND.
3147       SDValue NewLoad(Load, 0);
3148       if (Load->getExtensionType() == ISD::EXTLOAD) {
3149         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3150                               Load->getValueType(0), SDLoc(Load),
3151                               Load->getChain(), Load->getBasePtr(),
3152                               Load->getOffset(), Load->getMemoryVT(),
3153                               Load->getMemOperand());
3154         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3155         if (Load->getNumValues() == 3) {
3156           // PRE/POST_INC loads have 3 values.
3157           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3158                            NewLoad.getValue(2) };
3159           CombineTo(Load, To, 3, true);
3160         } else {
3161           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3162         }
3163       }
3164
3165       // Fold the AND away, taking care not to fold to the old load node if we
3166       // replaced it.
3167       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3168
3169       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3170     }
3171   }
3172
3173   // fold (and (load x), 255) -> (zextload x, i8)
3174   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3175   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3176   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3177               (N0.getOpcode() == ISD::ANY_EXTEND &&
3178                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3179     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3180     LoadSDNode *LN0 = HasAnyExt
3181       ? cast<LoadSDNode>(N0.getOperand(0))
3182       : cast<LoadSDNode>(N0);
3183     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3184         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3185       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3186       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3187         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3188         EVT LoadedVT = LN0->getMemoryVT();
3189         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3190
3191         if (ExtVT == LoadedVT &&
3192             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3193                                                     ExtVT))) {
3194
3195           SDValue NewLoad =
3196             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3197                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3198                            LN0->getMemOperand());
3199           AddToWorklist(N);
3200           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3201           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3202         }
3203
3204         // Do not change the width of a volatile load.
3205         // Do not generate loads of non-round integer types since these can
3206         // be expensive (and would be wrong if the type is not byte sized).
3207         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3208             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3209                                                     ExtVT))) {
3210           EVT PtrType = LN0->getOperand(1).getValueType();
3211
3212           unsigned Alignment = LN0->getAlignment();
3213           SDValue NewPtr = LN0->getBasePtr();
3214
3215           // For big endian targets, we need to add an offset to the pointer
3216           // to load the correct bytes.  For little endian systems, we merely
3217           // need to read fewer bytes from the same pointer.
3218           if (DAG.getDataLayout().isBigEndian()) {
3219             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3220             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3221             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3222             SDLoc DL(LN0);
3223             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3224                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3225             Alignment = MinAlign(Alignment, PtrOff);
3226           }
3227
3228           AddToWorklist(NewPtr.getNode());
3229
3230           SDValue Load =
3231             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3232                            LN0->getChain(), NewPtr,
3233                            LN0->getPointerInfo(),
3234                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3235                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3236           AddToWorklist(N);
3237           CombineTo(LN0, Load, Load.getValue(1));
3238           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3239         }
3240       }
3241     }
3242   }
3243
3244   if (SDValue Combined = visitANDLike(N0, N1, N))
3245     return Combined;
3246
3247   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3248   if (N0.getOpcode() == N1.getOpcode())
3249     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3250       return Tmp;
3251
3252   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3253   // fold (and (sra)) -> (and (srl)) when possible.
3254   if (!VT.isVector() &&
3255       SimplifyDemandedBits(SDValue(N, 0)))
3256     return SDValue(N, 0);
3257
3258   // fold (zext_inreg (extload x)) -> (zextload x)
3259   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3260     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3261     EVT MemVT = LN0->getMemoryVT();
3262     // If we zero all the possible extended bits, then we can turn this into
3263     // a zextload if we are running before legalize or the operation is legal.
3264     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3265     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3266                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3267         ((!LegalOperations && !LN0->isVolatile()) ||
3268          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3269       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3270                                        LN0->getChain(), LN0->getBasePtr(),
3271                                        MemVT, LN0->getMemOperand());
3272       AddToWorklist(N);
3273       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3274       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3275     }
3276   }
3277   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3278   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3279       N0.hasOneUse()) {
3280     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3281     EVT MemVT = LN0->getMemoryVT();
3282     // If we zero all the possible extended bits, then we can turn this into
3283     // a zextload if we are running before legalize or the operation is legal.
3284     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3285     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3286                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3287         ((!LegalOperations && !LN0->isVolatile()) ||
3288          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3289       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3290                                        LN0->getChain(), LN0->getBasePtr(),
3291                                        MemVT, LN0->getMemOperand());
3292       AddToWorklist(N);
3293       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3294       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3295     }
3296   }
3297   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3298   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3299     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3300                                        N0.getOperand(1), false);
3301     if (BSwap.getNode())
3302       return BSwap;
3303   }
3304
3305   return SDValue();
3306 }
3307
3308 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3309 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3310                                         bool DemandHighBits) {
3311   if (!LegalOperations)
3312     return SDValue();
3313
3314   EVT VT = N->getValueType(0);
3315   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3316     return SDValue();
3317   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3318     return SDValue();
3319
3320   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3321   bool LookPassAnd0 = false;
3322   bool LookPassAnd1 = false;
3323   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3324       std::swap(N0, N1);
3325   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3326       std::swap(N0, N1);
3327   if (N0.getOpcode() == ISD::AND) {
3328     if (!N0.getNode()->hasOneUse())
3329       return SDValue();
3330     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3331     if (!N01C || N01C->getZExtValue() != 0xFF00)
3332       return SDValue();
3333     N0 = N0.getOperand(0);
3334     LookPassAnd0 = true;
3335   }
3336
3337   if (N1.getOpcode() == ISD::AND) {
3338     if (!N1.getNode()->hasOneUse())
3339       return SDValue();
3340     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3341     if (!N11C || N11C->getZExtValue() != 0xFF)
3342       return SDValue();
3343     N1 = N1.getOperand(0);
3344     LookPassAnd1 = true;
3345   }
3346
3347   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3348     std::swap(N0, N1);
3349   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3350     return SDValue();
3351   if (!N0.getNode()->hasOneUse() ||
3352       !N1.getNode()->hasOneUse())
3353     return SDValue();
3354
3355   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3356   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3357   if (!N01C || !N11C)
3358     return SDValue();
3359   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3360     return SDValue();
3361
3362   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3363   SDValue N00 = N0->getOperand(0);
3364   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3365     if (!N00.getNode()->hasOneUse())
3366       return SDValue();
3367     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3368     if (!N001C || N001C->getZExtValue() != 0xFF)
3369       return SDValue();
3370     N00 = N00.getOperand(0);
3371     LookPassAnd0 = true;
3372   }
3373
3374   SDValue N10 = N1->getOperand(0);
3375   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3376     if (!N10.getNode()->hasOneUse())
3377       return SDValue();
3378     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3379     if (!N101C || N101C->getZExtValue() != 0xFF00)
3380       return SDValue();
3381     N10 = N10.getOperand(0);
3382     LookPassAnd1 = true;
3383   }
3384
3385   if (N00 != N10)
3386     return SDValue();
3387
3388   // Make sure everything beyond the low halfword gets set to zero since the SRL
3389   // 16 will clear the top bits.
3390   unsigned OpSizeInBits = VT.getSizeInBits();
3391   if (DemandHighBits && OpSizeInBits > 16) {
3392     // If the left-shift isn't masked out then the only way this is a bswap is
3393     // if all bits beyond the low 8 are 0. In that case the entire pattern
3394     // reduces to a left shift anyway: leave it for other parts of the combiner.
3395     if (!LookPassAnd0)
3396       return SDValue();
3397
3398     // However, if the right shift isn't masked out then it might be because
3399     // it's not needed. See if we can spot that too.
3400     if (!LookPassAnd1 &&
3401         !DAG.MaskedValueIsZero(
3402             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3403       return SDValue();
3404   }
3405
3406   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3407   if (OpSizeInBits > 16) {
3408     SDLoc DL(N);
3409     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3410                       DAG.getConstant(OpSizeInBits - 16, DL,
3411                                       getShiftAmountTy(VT)));
3412   }
3413   return Res;
3414 }
3415
3416 /// Return true if the specified node is an element that makes up a 32-bit
3417 /// packed halfword byteswap.
3418 /// ((x & 0x000000ff) << 8) |
3419 /// ((x & 0x0000ff00) >> 8) |
3420 /// ((x & 0x00ff0000) << 8) |
3421 /// ((x & 0xff000000) >> 8)
3422 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3423   if (!N.getNode()->hasOneUse())
3424     return false;
3425
3426   unsigned Opc = N.getOpcode();
3427   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3428     return false;
3429
3430   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3431   if (!N1C)
3432     return false;
3433
3434   unsigned Num;
3435   switch (N1C->getZExtValue()) {
3436   default:
3437     return false;
3438   case 0xFF:       Num = 0; break;
3439   case 0xFF00:     Num = 1; break;
3440   case 0xFF0000:   Num = 2; break;
3441   case 0xFF000000: Num = 3; break;
3442   }
3443
3444   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3445   SDValue N0 = N.getOperand(0);
3446   if (Opc == ISD::AND) {
3447     if (Num == 0 || Num == 2) {
3448       // (x >> 8) & 0xff
3449       // (x >> 8) & 0xff0000
3450       if (N0.getOpcode() != ISD::SRL)
3451         return false;
3452       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3453       if (!C || C->getZExtValue() != 8)
3454         return false;
3455     } else {
3456       // (x << 8) & 0xff00
3457       // (x << 8) & 0xff000000
3458       if (N0.getOpcode() != ISD::SHL)
3459         return false;
3460       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3461       if (!C || C->getZExtValue() != 8)
3462         return false;
3463     }
3464   } else if (Opc == ISD::SHL) {
3465     // (x & 0xff) << 8
3466     // (x & 0xff0000) << 8
3467     if (Num != 0 && Num != 2)
3468       return false;
3469     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3470     if (!C || C->getZExtValue() != 8)
3471       return false;
3472   } else { // Opc == ISD::SRL
3473     // (x & 0xff00) >> 8
3474     // (x & 0xff000000) >> 8
3475     if (Num != 1 && Num != 3)
3476       return false;
3477     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3478     if (!C || C->getZExtValue() != 8)
3479       return false;
3480   }
3481
3482   if (Parts[Num])
3483     return false;
3484
3485   Parts[Num] = N0.getOperand(0).getNode();
3486   return true;
3487 }
3488
3489 /// Match a 32-bit packed halfword bswap. That is
3490 /// ((x & 0x000000ff) << 8) |
3491 /// ((x & 0x0000ff00) >> 8) |
3492 /// ((x & 0x00ff0000) << 8) |
3493 /// ((x & 0xff000000) >> 8)
3494 /// => (rotl (bswap x), 16)
3495 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3496   if (!LegalOperations)
3497     return SDValue();
3498
3499   EVT VT = N->getValueType(0);
3500   if (VT != MVT::i32)
3501     return SDValue();
3502   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3503     return SDValue();
3504
3505   // Look for either
3506   // (or (or (and), (and)), (or (and), (and)))
3507   // (or (or (or (and), (and)), (and)), (and))
3508   if (N0.getOpcode() != ISD::OR)
3509     return SDValue();
3510   SDValue N00 = N0.getOperand(0);
3511   SDValue N01 = N0.getOperand(1);
3512   SDNode *Parts[4] = {};
3513
3514   if (N1.getOpcode() == ISD::OR &&
3515       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3516     // (or (or (and), (and)), (or (and), (and)))
3517     SDValue N000 = N00.getOperand(0);
3518     if (!isBSwapHWordElement(N000, Parts))
3519       return SDValue();
3520
3521     SDValue N001 = N00.getOperand(1);
3522     if (!isBSwapHWordElement(N001, Parts))
3523       return SDValue();
3524     SDValue N010 = N01.getOperand(0);
3525     if (!isBSwapHWordElement(N010, Parts))
3526       return SDValue();
3527     SDValue N011 = N01.getOperand(1);
3528     if (!isBSwapHWordElement(N011, Parts))
3529       return SDValue();
3530   } else {
3531     // (or (or (or (and), (and)), (and)), (and))
3532     if (!isBSwapHWordElement(N1, Parts))
3533       return SDValue();
3534     if (!isBSwapHWordElement(N01, Parts))
3535       return SDValue();
3536     if (N00.getOpcode() != ISD::OR)
3537       return SDValue();
3538     SDValue N000 = N00.getOperand(0);
3539     if (!isBSwapHWordElement(N000, Parts))
3540       return SDValue();
3541     SDValue N001 = N00.getOperand(1);
3542     if (!isBSwapHWordElement(N001, Parts))
3543       return SDValue();
3544   }
3545
3546   // Make sure the parts are all coming from the same node.
3547   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3548     return SDValue();
3549
3550   SDLoc DL(N);
3551   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3552                               SDValue(Parts[0], 0));
3553
3554   // Result of the bswap should be rotated by 16. If it's not legal, then
3555   // do  (x << 16) | (x >> 16).
3556   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3557   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3558     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3559   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3560     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3561   return DAG.getNode(ISD::OR, DL, VT,
3562                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3563                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3564 }
3565
3566 /// This contains all DAGCombine rules which reduce two values combined by
3567 /// an Or operation to a single value \see visitANDLike().
3568 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3569   EVT VT = N1.getValueType();
3570   // fold (or x, undef) -> -1
3571   if (!LegalOperations &&
3572       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3573     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3574     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3575                            SDLoc(LocReference), VT);
3576   }
3577   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3578   SDValue LL, LR, RL, RR, CC0, CC1;
3579   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3580     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3581     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3582
3583     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3584       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3585       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3586       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3587         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3588                                      LR.getValueType(), LL, RL);
3589         AddToWorklist(ORNode.getNode());
3590         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3591       }
3592       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3593       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3594       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3595         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3596                                       LR.getValueType(), LL, RL);
3597         AddToWorklist(ANDNode.getNode());
3598         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3599       }
3600     }
3601     // canonicalize equivalent to ll == rl
3602     if (LL == RR && LR == RL) {
3603       Op1 = ISD::getSetCCSwappedOperands(Op1);
3604       std::swap(RL, RR);
3605     }
3606     if (LL == RL && LR == RR) {
3607       bool isInteger = LL.getValueType().isInteger();
3608       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3609       if (Result != ISD::SETCC_INVALID &&
3610           (!LegalOperations ||
3611            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3612             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3613         EVT CCVT = getSetCCResultType(LL.getValueType());
3614         if (N0.getValueType() == CCVT ||
3615             (!LegalOperations && N0.getValueType() == MVT::i1))
3616           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3617                               LL, LR, Result);
3618       }
3619     }
3620   }
3621
3622   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3623   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3624       // Don't increase # computations.
3625       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3626     // We can only do this xform if we know that bits from X that are set in C2
3627     // but not in C1 are already zero.  Likewise for Y.
3628     if (const ConstantSDNode *N0O1C =
3629         getAsNonOpaqueConstant(N0.getOperand(1))) {
3630       if (const ConstantSDNode *N1O1C =
3631           getAsNonOpaqueConstant(N1.getOperand(1))) {
3632         // We can only do this xform if we know that bits from X that are set in
3633         // C2 but not in C1 are already zero.  Likewise for Y.
3634         const APInt &LHSMask = N0O1C->getAPIntValue();
3635         const APInt &RHSMask = N1O1C->getAPIntValue();
3636
3637         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3638             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3639           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3640                                   N0.getOperand(0), N1.getOperand(0));
3641           SDLoc DL(LocReference);
3642           return DAG.getNode(ISD::AND, DL, VT, X,
3643                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3644         }
3645       }
3646     }
3647   }
3648
3649   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3650   if (N0.getOpcode() == ISD::AND &&
3651       N1.getOpcode() == ISD::AND &&
3652       N0.getOperand(0) == N1.getOperand(0) &&
3653       // Don't increase # computations.
3654       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3655     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3656                             N0.getOperand(1), N1.getOperand(1));
3657     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3658   }
3659
3660   return SDValue();
3661 }
3662
3663 SDValue DAGCombiner::visitOR(SDNode *N) {
3664   SDValue N0 = N->getOperand(0);
3665   SDValue N1 = N->getOperand(1);
3666   EVT VT = N1.getValueType();
3667
3668   // fold vector ops
3669   if (VT.isVector()) {
3670     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3671       return FoldedVOp;
3672
3673     // fold (or x, 0) -> x, vector edition
3674     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3675       return N1;
3676     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3677       return N0;
3678
3679     // fold (or x, -1) -> -1, vector edition
3680     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3681       // do not return N0, because undef node may exist in N0
3682       return DAG.getConstant(
3683           APInt::getAllOnesValue(
3684               N0.getValueType().getScalarType().getSizeInBits()),
3685           SDLoc(N), N0.getValueType());
3686     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3687       // do not return N1, because undef node may exist in N1
3688       return DAG.getConstant(
3689           APInt::getAllOnesValue(
3690               N1.getValueType().getScalarType().getSizeInBits()),
3691           SDLoc(N), N1.getValueType());
3692
3693     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3694     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3695     // Do this only if the resulting shuffle is legal.
3696     if (isa<ShuffleVectorSDNode>(N0) &&
3697         isa<ShuffleVectorSDNode>(N1) &&
3698         // Avoid folding a node with illegal type.
3699         TLI.isTypeLegal(VT) &&
3700         N0->getOperand(1) == N1->getOperand(1) &&
3701         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3702       bool CanFold = true;
3703       unsigned NumElts = VT.getVectorNumElements();
3704       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3705       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3706       // We construct two shuffle masks:
3707       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3708       // and N1 as the second operand.
3709       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3710       // and N0 as the second operand.
3711       // We do this because OR is commutable and therefore there might be
3712       // two ways to fold this node into a shuffle.
3713       SmallVector<int,4> Mask1;
3714       SmallVector<int,4> Mask2;
3715
3716       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3717         int M0 = SV0->getMaskElt(i);
3718         int M1 = SV1->getMaskElt(i);
3719
3720         // Both shuffle indexes are undef. Propagate Undef.
3721         if (M0 < 0 && M1 < 0) {
3722           Mask1.push_back(M0);
3723           Mask2.push_back(M0);
3724           continue;
3725         }
3726
3727         if (M0 < 0 || M1 < 0 ||
3728             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3729             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3730           CanFold = false;
3731           break;
3732         }
3733
3734         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3735         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3736       }
3737
3738       if (CanFold) {
3739         // Fold this sequence only if the resulting shuffle is 'legal'.
3740         if (TLI.isShuffleMaskLegal(Mask1, VT))
3741           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3742                                       N1->getOperand(0), &Mask1[0]);
3743         if (TLI.isShuffleMaskLegal(Mask2, VT))
3744           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3745                                       N0->getOperand(0), &Mask2[0]);
3746       }
3747     }
3748   }
3749
3750   // fold (or c1, c2) -> c1|c2
3751   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3753   if (N0C && N1C && !N1C->isOpaque())
3754     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3755   // canonicalize constant to RHS
3756   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3757      !isConstantIntBuildVectorOrConstantInt(N1))
3758     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3759   // fold (or x, 0) -> x
3760   if (isNullConstant(N1))
3761     return N0;
3762   // fold (or x, -1) -> -1
3763   if (isAllOnesConstant(N1))
3764     return N1;
3765   // fold (or x, c) -> c iff (x & ~c) == 0
3766   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3767     return N1;
3768
3769   if (SDValue Combined = visitORLike(N0, N1, N))
3770     return Combined;
3771
3772   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3773   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3774     return BSwap;
3775   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3776     return BSwap;
3777
3778   // reassociate or
3779   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3780     return ROR;
3781   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3782   // iff (c1 & c2) == 0.
3783   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3784              isa<ConstantSDNode>(N0.getOperand(1))) {
3785     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3786     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3787       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3788                                                    N1C, C1))
3789         return DAG.getNode(
3790             ISD::AND, SDLoc(N), VT,
3791             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3792       return SDValue();
3793     }
3794   }
3795   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3796   if (N0.getOpcode() == N1.getOpcode())
3797     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3798       return Tmp;
3799
3800   // See if this is some rotate idiom.
3801   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3802     return SDValue(Rot, 0);
3803
3804   // Simplify the operands using demanded-bits information.
3805   if (!VT.isVector() &&
3806       SimplifyDemandedBits(SDValue(N, 0)))
3807     return SDValue(N, 0);
3808
3809   return SDValue();
3810 }
3811
3812 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3813 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3814   if (Op.getOpcode() == ISD::AND) {
3815     if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
3816       Mask = Op.getOperand(1);
3817       Op = Op.getOperand(0);
3818     } else {
3819       return false;
3820     }
3821   }
3822
3823   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3824     Shift = Op;
3825     return true;
3826   }
3827
3828   return false;
3829 }
3830
3831 // Return true if we can prove that, whenever Neg and Pos are both in the
3832 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos).  This means that
3833 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3834 //
3835 //     (or (shift1 X, Neg), (shift2 X, Pos))
3836 //
3837 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3838 // in direction shift1 by Neg.  The range [0, EltSize) means that we only need
3839 // to consider shift amounts with defined behavior.
3840 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
3841   // If EltSize is a power of 2 then:
3842   //
3843   //  (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
3844   //  (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
3845   //
3846   // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
3847   // for the stronger condition:
3848   //
3849   //     Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1)    [A]
3850   //
3851   // for all Neg and Pos.  Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
3852   // we can just replace Neg with Neg' for the rest of the function.
3853   //
3854   // In other cases we check for the even stronger condition:
3855   //
3856   //     Neg == EltSize - Pos                                    [B]
3857   //
3858   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3859   // behavior if Pos == 0 (and consequently Neg == EltSize).
3860   //
3861   // We could actually use [A] whenever EltSize is a power of 2, but the
3862   // only extra cases that it would match are those uninteresting ones
3863   // where Neg and Pos are never in range at the same time.  E.g. for
3864   // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3865   // as well as (sub 32, Pos), but:
3866   //
3867   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3868   //
3869   // always invokes undefined behavior for 32-bit X.
3870   //
3871   // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
3872   unsigned MaskLoBits = 0;
3873   if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
3874     if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
3875       if (NegC->getAPIntValue() == EltSize - 1) {
3876         Neg = Neg.getOperand(0);
3877         MaskLoBits = Log2_64(EltSize);
3878       }
3879     }
3880   }
3881
3882   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3883   if (Neg.getOpcode() != ISD::SUB)
3884     return 0;
3885   ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
3886   if (!NegC)
3887     return 0;
3888   SDValue NegOp1 = Neg.getOperand(1);
3889
3890   // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
3891   // Pos'.  The truncation is redundant for the purpose of the equality.
3892   if (MaskLoBits && Pos.getOpcode() == ISD::AND)
3893     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3894       if (PosC->getAPIntValue() == EltSize - 1)
3895         Pos = Pos.getOperand(0);
3896
3897   // The condition we need is now:
3898   //
3899   //     (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
3900   //
3901   // If NegOp1 == Pos then we need:
3902   //
3903   //              EltSize & Mask == NegC & Mask
3904   //
3905   // (because "x & Mask" is a truncation and distributes through subtraction).
3906   APInt Width;
3907   if (Pos == NegOp1)
3908     Width = NegC->getAPIntValue();
3909
3910   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3911   // Then the condition we want to prove becomes:
3912   //
3913   //     (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
3914   //
3915   // which, again because "x & Mask" is a truncation, becomes:
3916   //
3917   //                NegC & Mask == (EltSize - PosC) & Mask
3918   //             EltSize & Mask == (NegC + PosC) & Mask
3919   else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
3920     if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
3921       Width = PosC->getAPIntValue() + NegC->getAPIntValue();
3922     else
3923       return false;
3924   } else
3925     return false;
3926
3927   // Now we just need to check that EltSize & Mask == Width & Mask.
3928   if (MaskLoBits)
3929     // EltSize & Mask is 0 since Mask is EltSize - 1.
3930     return Width.getLoBits(MaskLoBits) == 0;
3931   return Width == EltSize;
3932 }
3933
3934 // A subroutine of MatchRotate used once we have found an OR of two opposite
3935 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3936 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3937 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3938 // Neg with outer conversions stripped away.
3939 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3940                                        SDValue Neg, SDValue InnerPos,
3941                                        SDValue InnerNeg, unsigned PosOpcode,
3942                                        unsigned NegOpcode, SDLoc DL) {
3943   // fold (or (shl x, (*ext y)),
3944   //          (srl x, (*ext (sub 32, y)))) ->
3945   //   (rotl x, y) or (rotr x, (sub 32, y))
3946   //
3947   // fold (or (shl x, (*ext (sub 32, y))),
3948   //          (srl x, (*ext y))) ->
3949   //   (rotr x, y) or (rotl x, (sub 32, y))
3950   EVT VT = Shifted.getValueType();
3951   if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
3952     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3953     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3954                        HasPos ? Pos : Neg).getNode();
3955   }
3956
3957   return nullptr;
3958 }
3959
3960 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3961 // idioms for rotate, and if the target supports rotation instructions, generate
3962 // a rot[lr].
3963 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3964   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3965   EVT VT = LHS.getValueType();
3966   if (!TLI.isTypeLegal(VT)) return nullptr;
3967
3968   // The target must have at least one rotate flavor.
3969   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3970   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3971   if (!HasROTL && !HasROTR) return nullptr;
3972
3973   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3974   SDValue LHSShift;   // The shift.
3975   SDValue LHSMask;    // AND value if any.
3976   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3977     return nullptr; // Not part of a rotate.
3978
3979   SDValue RHSShift;   // The shift.
3980   SDValue RHSMask;    // AND value if any.
3981   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3982     return nullptr; // Not part of a rotate.
3983
3984   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3985     return nullptr;   // Not shifting the same value.
3986
3987   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3988     return nullptr;   // Shifts must disagree.
3989
3990   // Canonicalize shl to left side in a shl/srl pair.
3991   if (RHSShift.getOpcode() == ISD::SHL) {
3992     std::swap(LHS, RHS);
3993     std::swap(LHSShift, RHSShift);
3994     std::swap(LHSMask, RHSMask);
3995   }
3996
3997   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3998   SDValue LHSShiftArg = LHSShift.getOperand(0);
3999   SDValue LHSShiftAmt = LHSShift.getOperand(1);
4000   SDValue RHSShiftArg = RHSShift.getOperand(0);
4001   SDValue RHSShiftAmt = RHSShift.getOperand(1);
4002
4003   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
4004   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
4005   if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
4006     uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
4007     uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
4008     if ((LShVal + RShVal) != EltSizeInBits)
4009       return nullptr;
4010
4011     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
4012                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
4013
4014     // If there is an AND of either shifted operand, apply it to the result.
4015     if (LHSMask.getNode() || RHSMask.getNode()) {
4016       APInt AllBits = APInt::getAllOnesValue(EltSizeInBits);
4017       SDValue Mask = DAG.getConstant(AllBits, DL, VT);
4018
4019       if (LHSMask.getNode()) {
4020         APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
4021         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4022                            DAG.getNode(ISD::OR, DL, VT, LHSMask,
4023                                        DAG.getConstant(RHSBits, DL, VT)));
4024       }
4025       if (RHSMask.getNode()) {
4026         APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
4027         Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
4028                            DAG.getNode(ISD::OR, DL, VT, RHSMask,
4029                                        DAG.getConstant(LHSBits, DL, VT)));
4030       }
4031
4032       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
4033     }
4034
4035     return Rot.getNode();
4036   }
4037
4038   // If there is a mask here, and we have a variable shift, we can't be sure
4039   // that we're masking out the right stuff.
4040   if (LHSMask.getNode() || RHSMask.getNode())
4041     return nullptr;
4042
4043   // If the shift amount is sign/zext/any-extended just peel it off.
4044   SDValue LExtOp0 = LHSShiftAmt;
4045   SDValue RExtOp0 = RHSShiftAmt;
4046   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4047        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4048        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4049        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4050       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4051        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4052        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4053        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4054     LExtOp0 = LHSShiftAmt.getOperand(0);
4055     RExtOp0 = RHSShiftAmt.getOperand(0);
4056   }
4057
4058   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4059                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4060   if (TryL)
4061     return TryL;
4062
4063   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4064                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4065   if (TryR)
4066     return TryR;
4067
4068   return nullptr;
4069 }
4070
4071 SDValue DAGCombiner::visitXOR(SDNode *N) {
4072   SDValue N0 = N->getOperand(0);
4073   SDValue N1 = N->getOperand(1);
4074   EVT VT = N0.getValueType();
4075
4076   // fold vector ops
4077   if (VT.isVector()) {
4078     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4079       return FoldedVOp;
4080
4081     // fold (xor x, 0) -> x, vector edition
4082     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4083       return N1;
4084     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4085       return N0;
4086   }
4087
4088   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4089   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4090     return DAG.getConstant(0, SDLoc(N), VT);
4091   // fold (xor x, undef) -> undef
4092   if (N0.getOpcode() == ISD::UNDEF)
4093     return N0;
4094   if (N1.getOpcode() == ISD::UNDEF)
4095     return N1;
4096   // fold (xor c1, c2) -> c1^c2
4097   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4098   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4099   if (N0C && N1C)
4100     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4101   // canonicalize constant to RHS
4102   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4103      !isConstantIntBuildVectorOrConstantInt(N1))
4104     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4105   // fold (xor x, 0) -> x
4106   if (isNullConstant(N1))
4107     return N0;
4108   // reassociate xor
4109   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4110     return RXOR;
4111
4112   // fold !(x cc y) -> (x !cc y)
4113   SDValue LHS, RHS, CC;
4114   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4115     bool isInt = LHS.getValueType().isInteger();
4116     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4117                                                isInt);
4118
4119     if (!LegalOperations ||
4120         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4121       switch (N0.getOpcode()) {
4122       default:
4123         llvm_unreachable("Unhandled SetCC Equivalent!");
4124       case ISD::SETCC:
4125         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4126       case ISD::SELECT_CC:
4127         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4128                                N0.getOperand(3), NotCC);
4129       }
4130     }
4131   }
4132
4133   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4134   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4135       N0.getNode()->hasOneUse() &&
4136       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4137     SDValue V = N0.getOperand(0);
4138     SDLoc DL(N0);
4139     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4140                     DAG.getConstant(1, DL, V.getValueType()));
4141     AddToWorklist(V.getNode());
4142     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4143   }
4144
4145   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4146   if (isOneConstant(N1) && VT == MVT::i1 &&
4147       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4148     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4149     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4150       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4151       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4152       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4153       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4154       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4155     }
4156   }
4157   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4158   if (isAllOnesConstant(N1) &&
4159       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4160     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4161     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4162       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4163       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4164       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4165       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4166       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4167     }
4168   }
4169   // fold (xor (and x, y), y) -> (and (not x), y)
4170   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4171       N0->getOperand(1) == N1) {
4172     SDValue X = N0->getOperand(0);
4173     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4174     AddToWorklist(NotX.getNode());
4175     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4176   }
4177   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4178   if (N1C && N0.getOpcode() == ISD::XOR) {
4179     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4180       SDLoc DL(N);
4181       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4182                          DAG.getConstant(N1C->getAPIntValue() ^
4183                                          N00C->getAPIntValue(), DL, VT));
4184     }
4185     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4186       SDLoc DL(N);
4187       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4188                          DAG.getConstant(N1C->getAPIntValue() ^
4189                                          N01C->getAPIntValue(), DL, VT));
4190     }
4191   }
4192   // fold (xor x, x) -> 0
4193   if (N0 == N1)
4194     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4195
4196   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4197   // Here is a concrete example of this equivalence:
4198   // i16   x ==  14
4199   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4200   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4201   //
4202   // =>
4203   //
4204   // i16     ~1      == 0b1111111111111110
4205   // i16 rol(~1, 14) == 0b1011111111111111
4206   //
4207   // Some additional tips to help conceptualize this transform:
4208   // - Try to see the operation as placing a single zero in a value of all ones.
4209   // - There exists no value for x which would allow the result to contain zero.
4210   // - Values of x larger than the bitwidth are undefined and do not require a
4211   //   consistent result.
4212   // - Pushing the zero left requires shifting one bits in from the right.
4213   // A rotate left of ~1 is a nice way of achieving the desired result.
4214   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4215       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4216     SDLoc DL(N);
4217     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4218                        N0.getOperand(1));
4219   }
4220
4221   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4222   if (N0.getOpcode() == N1.getOpcode())
4223     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4224       return Tmp;
4225
4226   // Simplify the expression using non-local knowledge.
4227   if (!VT.isVector() &&
4228       SimplifyDemandedBits(SDValue(N, 0)))
4229     return SDValue(N, 0);
4230
4231   return SDValue();
4232 }
4233
4234 /// Handle transforms common to the three shifts, when the shift amount is a
4235 /// constant.
4236 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4237   SDNode *LHS = N->getOperand(0).getNode();
4238   if (!LHS->hasOneUse()) return SDValue();
4239
4240   // We want to pull some binops through shifts, so that we have (and (shift))
4241   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4242   // thing happens with address calculations, so it's important to canonicalize
4243   // it.
4244   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4245
4246   switch (LHS->getOpcode()) {
4247   default: return SDValue();
4248   case ISD::OR:
4249   case ISD::XOR:
4250     HighBitSet = false; // We can only transform sra if the high bit is clear.
4251     break;
4252   case ISD::AND:
4253     HighBitSet = true;  // We can only transform sra if the high bit is set.
4254     break;
4255   case ISD::ADD:
4256     if (N->getOpcode() != ISD::SHL)
4257       return SDValue(); // only shl(add) not sr[al](add).
4258     HighBitSet = false; // We can only transform sra if the high bit is clear.
4259     break;
4260   }
4261
4262   // We require the RHS of the binop to be a constant and not opaque as well.
4263   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4264   if (!BinOpCst) return SDValue();
4265
4266   // FIXME: disable this unless the input to the binop is a shift by a constant.
4267   // If it is not a shift, it pessimizes some common cases like:
4268   //
4269   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4270   //    int bar(int *X, int i) { return X[i & 255]; }
4271   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4272   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4273        BinOpLHSVal->getOpcode() != ISD::SRA &&
4274        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4275       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4276     return SDValue();
4277
4278   EVT VT = N->getValueType(0);
4279
4280   // If this is a signed shift right, and the high bit is modified by the
4281   // logical operation, do not perform the transformation. The highBitSet
4282   // boolean indicates the value of the high bit of the constant which would
4283   // cause it to be modified for this operation.
4284   if (N->getOpcode() == ISD::SRA) {
4285     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4286     if (BinOpRHSSignSet != HighBitSet)
4287       return SDValue();
4288   }
4289
4290   if (!TLI.isDesirableToCommuteWithShift(LHS))
4291     return SDValue();
4292
4293   // Fold the constants, shifting the binop RHS by the shift amount.
4294   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4295                                N->getValueType(0),
4296                                LHS->getOperand(1), N->getOperand(1));
4297   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4298
4299   // Create the new shift.
4300   SDValue NewShift = DAG.getNode(N->getOpcode(),
4301                                  SDLoc(LHS->getOperand(0)),
4302                                  VT, LHS->getOperand(0), N->getOperand(1));
4303
4304   // Create the new binop.
4305   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4306 }
4307
4308 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4309   assert(N->getOpcode() == ISD::TRUNCATE);
4310   assert(N->getOperand(0).getOpcode() == ISD::AND);
4311
4312   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4313   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4314     SDValue N01 = N->getOperand(0).getOperand(1);
4315
4316     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4317       if (!N01C->isOpaque()) {
4318         EVT TruncVT = N->getValueType(0);
4319         SDValue N00 = N->getOperand(0).getOperand(0);
4320         APInt TruncC = N01C->getAPIntValue();
4321         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4322         SDLoc DL(N);
4323
4324         return DAG.getNode(ISD::AND, DL, TruncVT,
4325                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4326                            DAG.getConstant(TruncC, DL, TruncVT));
4327       }
4328     }
4329   }
4330
4331   return SDValue();
4332 }
4333
4334 SDValue DAGCombiner::visitRotate(SDNode *N) {
4335   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4336   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4337       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4338     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4339     if (NewOp1.getNode())
4340       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4341                          N->getOperand(0), NewOp1);
4342   }
4343   return SDValue();
4344 }
4345
4346 SDValue DAGCombiner::visitSHL(SDNode *N) {
4347   SDValue N0 = N->getOperand(0);
4348   SDValue N1 = N->getOperand(1);
4349   EVT VT = N0.getValueType();
4350   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4351
4352   // fold vector ops
4353   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4354   if (VT.isVector()) {
4355     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4356       return FoldedVOp;
4357
4358     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4359     // If setcc produces all-one true value then:
4360     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4361     if (N1CV && N1CV->isConstant()) {
4362       if (N0.getOpcode() == ISD::AND) {
4363         SDValue N00 = N0->getOperand(0);
4364         SDValue N01 = N0->getOperand(1);
4365         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4366
4367         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4368             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4369                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4370           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4371                                                      N01CV, N1CV))
4372             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4373         }
4374       } else {
4375         N1C = isConstOrConstSplat(N1);
4376       }
4377     }
4378   }
4379
4380   // fold (shl c1, c2) -> c1<<c2
4381   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4382   if (N0C && N1C && !N1C->isOpaque())
4383     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4384   // fold (shl 0, x) -> 0
4385   if (isNullConstant(N0))
4386     return N0;
4387   // fold (shl x, c >= size(x)) -> undef
4388   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4389     return DAG.getUNDEF(VT);
4390   // fold (shl x, 0) -> x
4391   if (N1C && N1C->isNullValue())
4392     return N0;
4393   // fold (shl undef, x) -> 0
4394   if (N0.getOpcode() == ISD::UNDEF)
4395     return DAG.getConstant(0, SDLoc(N), VT);
4396   // if (shl x, c) is known to be zero, return 0
4397   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4398                             APInt::getAllOnesValue(OpSizeInBits)))
4399     return DAG.getConstant(0, SDLoc(N), VT);
4400   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4401   if (N1.getOpcode() == ISD::TRUNCATE &&
4402       N1.getOperand(0).getOpcode() == ISD::AND) {
4403     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4404     if (NewOp1.getNode())
4405       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4406   }
4407
4408   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4409     return SDValue(N, 0);
4410
4411   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4412   if (N1C && N0.getOpcode() == ISD::SHL) {
4413     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4414       uint64_t c1 = N0C1->getZExtValue();
4415       uint64_t c2 = N1C->getZExtValue();
4416       SDLoc DL(N);
4417       if (c1 + c2 >= OpSizeInBits)
4418         return DAG.getConstant(0, DL, VT);
4419       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4420                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4421     }
4422   }
4423
4424   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4425   // For this to be valid, the second form must not preserve any of the bits
4426   // that are shifted out by the inner shift in the first form.  This means
4427   // the outer shift size must be >= the number of bits added by the ext.
4428   // As a corollary, we don't care what kind of ext it is.
4429   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4430               N0.getOpcode() == ISD::ANY_EXTEND ||
4431               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4432       N0.getOperand(0).getOpcode() == ISD::SHL) {
4433     SDValue N0Op0 = N0.getOperand(0);
4434     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4435       uint64_t c1 = N0Op0C1->getZExtValue();
4436       uint64_t c2 = N1C->getZExtValue();
4437       EVT InnerShiftVT = N0Op0.getValueType();
4438       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4439       if (c2 >= OpSizeInBits - InnerShiftSize) {
4440         SDLoc DL(N0);
4441         if (c1 + c2 >= OpSizeInBits)
4442           return DAG.getConstant(0, DL, VT);
4443         return DAG.getNode(ISD::SHL, DL, VT,
4444                            DAG.getNode(N0.getOpcode(), DL, VT,
4445                                        N0Op0->getOperand(0)),
4446                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4447       }
4448     }
4449   }
4450
4451   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4452   // Only fold this if the inner zext has no other uses to avoid increasing
4453   // the total number of instructions.
4454   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4455       N0.getOperand(0).getOpcode() == ISD::SRL) {
4456     SDValue N0Op0 = N0.getOperand(0);
4457     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4458       uint64_t c1 = N0Op0C1->getZExtValue();
4459       if (c1 < VT.getScalarSizeInBits()) {
4460         uint64_t c2 = N1C->getZExtValue();
4461         if (c1 == c2) {
4462           SDValue NewOp0 = N0.getOperand(0);
4463           EVT CountVT = NewOp0.getOperand(1).getValueType();
4464           SDLoc DL(N);
4465           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4466                                        NewOp0,
4467                                        DAG.getConstant(c2, DL, CountVT));
4468           AddToWorklist(NewSHL.getNode());
4469           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4470         }
4471       }
4472     }
4473   }
4474
4475   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4476   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4477   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4478       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4479     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4480       uint64_t C1 = N0C1->getZExtValue();
4481       uint64_t C2 = N1C->getZExtValue();
4482       SDLoc DL(N);
4483       if (C1 <= C2)
4484         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4485                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4486       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4487                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4488     }
4489   }
4490
4491   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4492   //                               (and (srl x, (sub c1, c2), MASK)
4493   // Only fold this if the inner shift has no other uses -- if it does, folding
4494   // this will increase the total number of instructions.
4495   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4496     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4497       uint64_t c1 = N0C1->getZExtValue();
4498       if (c1 < OpSizeInBits) {
4499         uint64_t c2 = N1C->getZExtValue();
4500         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4501         SDValue Shift;
4502         if (c2 > c1) {
4503           Mask = Mask.shl(c2 - c1);
4504           SDLoc DL(N);
4505           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4506                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4507         } else {
4508           Mask = Mask.lshr(c1 - c2);
4509           SDLoc DL(N);
4510           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4511                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4512         }
4513         SDLoc DL(N0);
4514         return DAG.getNode(ISD::AND, DL, VT, Shift,
4515                            DAG.getConstant(Mask, DL, VT));
4516       }
4517     }
4518   }
4519   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4520   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4521     unsigned BitSize = VT.getScalarSizeInBits();
4522     SDLoc DL(N);
4523     SDValue HiBitsMask =
4524       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4525                                             BitSize - N1C->getZExtValue()),
4526                       DL, VT);
4527     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4528                        HiBitsMask);
4529   }
4530
4531   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4532   // Variant of version done on multiply, except mul by a power of 2 is turned
4533   // into a shift.
4534   APInt Val;
4535   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4536       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4537        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4538     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4539     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4540     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4541   }
4542
4543   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4544   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4545     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4546       if (SDValue Folded =
4547               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4548         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4549     }
4550   }
4551
4552   if (N1C && !N1C->isOpaque())
4553     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4554       return NewSHL;
4555
4556   return SDValue();
4557 }
4558
4559 SDValue DAGCombiner::visitSRA(SDNode *N) {
4560   SDValue N0 = N->getOperand(0);
4561   SDValue N1 = N->getOperand(1);
4562   EVT VT = N0.getValueType();
4563   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4564
4565   // fold vector ops
4566   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4567   if (VT.isVector()) {
4568     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4569       return FoldedVOp;
4570
4571     N1C = isConstOrConstSplat(N1);
4572   }
4573
4574   // fold (sra c1, c2) -> (sra c1, c2)
4575   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4576   if (N0C && N1C && !N1C->isOpaque())
4577     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4578   // fold (sra 0, x) -> 0
4579   if (isNullConstant(N0))
4580     return N0;
4581   // fold (sra -1, x) -> -1
4582   if (isAllOnesConstant(N0))
4583     return N0;
4584   // fold (sra x, (setge c, size(x))) -> undef
4585   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4586     return DAG.getUNDEF(VT);
4587   // fold (sra x, 0) -> x
4588   if (N1C && N1C->isNullValue())
4589     return N0;
4590   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4591   // sext_inreg.
4592   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4593     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4594     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4595     if (VT.isVector())
4596       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4597                                ExtVT, VT.getVectorNumElements());
4598     if ((!LegalOperations ||
4599          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4600       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4601                          N0.getOperand(0), DAG.getValueType(ExtVT));
4602   }
4603
4604   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4605   if (N1C && N0.getOpcode() == ISD::SRA) {
4606     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4607       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4608       if (Sum >= OpSizeInBits)
4609         Sum = OpSizeInBits - 1;
4610       SDLoc DL(N);
4611       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4612                          DAG.getConstant(Sum, DL, N1.getValueType()));
4613     }
4614   }
4615
4616   // fold (sra (shl X, m), (sub result_size, n))
4617   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4618   // result_size - n != m.
4619   // If truncate is free for the target sext(shl) is likely to result in better
4620   // code.
4621   if (N0.getOpcode() == ISD::SHL && N1C) {
4622     // Get the two constanst of the shifts, CN0 = m, CN = n.
4623     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4624     if (N01C) {
4625       LLVMContext &Ctx = *DAG.getContext();
4626       // Determine what the truncate's result bitsize and type would be.
4627       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4628
4629       if (VT.isVector())
4630         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4631
4632       // Determine the residual right-shift amount.
4633       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4634
4635       // If the shift is not a no-op (in which case this should be just a sign
4636       // extend already), the truncated to type is legal, sign_extend is legal
4637       // on that type, and the truncate to that type is both legal and free,
4638       // perform the transform.
4639       if ((ShiftAmt > 0) &&
4640           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4641           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4642           TLI.isTruncateFree(VT, TruncVT)) {
4643
4644         SDLoc DL(N);
4645         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4646             getShiftAmountTy(N0.getOperand(0).getValueType()));
4647         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4648                                     N0.getOperand(0), Amt);
4649         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4650                                     Shift);
4651         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4652                            N->getValueType(0), Trunc);
4653       }
4654     }
4655   }
4656
4657   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4658   if (N1.getOpcode() == ISD::TRUNCATE &&
4659       N1.getOperand(0).getOpcode() == ISD::AND) {
4660     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4661     if (NewOp1.getNode())
4662       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4663   }
4664
4665   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4666   //      if c1 is equal to the number of bits the trunc removes
4667   if (N0.getOpcode() == ISD::TRUNCATE &&
4668       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4669        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4670       N0.getOperand(0).hasOneUse() &&
4671       N0.getOperand(0).getOperand(1).hasOneUse() &&
4672       N1C) {
4673     SDValue N0Op0 = N0.getOperand(0);
4674     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4675       unsigned LargeShiftVal = LargeShift->getZExtValue();
4676       EVT LargeVT = N0Op0.getValueType();
4677
4678       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4679         SDLoc DL(N);
4680         SDValue Amt =
4681           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4682                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4683         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4684                                   N0Op0.getOperand(0), Amt);
4685         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4686       }
4687     }
4688   }
4689
4690   // Simplify, based on bits shifted out of the LHS.
4691   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4692     return SDValue(N, 0);
4693
4694
4695   // If the sign bit is known to be zero, switch this to a SRL.
4696   if (DAG.SignBitIsZero(N0))
4697     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4698
4699   if (N1C && !N1C->isOpaque())
4700     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4701       return NewSRA;
4702
4703   return SDValue();
4704 }
4705
4706 SDValue DAGCombiner::visitSRL(SDNode *N) {
4707   SDValue N0 = N->getOperand(0);
4708   SDValue N1 = N->getOperand(1);
4709   EVT VT = N0.getValueType();
4710   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4711
4712   // fold vector ops
4713   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4714   if (VT.isVector()) {
4715     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4716       return FoldedVOp;
4717
4718     N1C = isConstOrConstSplat(N1);
4719   }
4720
4721   // fold (srl c1, c2) -> c1 >>u c2
4722   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4723   if (N0C && N1C && !N1C->isOpaque())
4724     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4725   // fold (srl 0, x) -> 0
4726   if (isNullConstant(N0))
4727     return N0;
4728   // fold (srl x, c >= size(x)) -> undef
4729   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4730     return DAG.getUNDEF(VT);
4731   // fold (srl x, 0) -> x
4732   if (N1C && N1C->isNullValue())
4733     return N0;
4734   // if (srl x, c) is known to be zero, return 0
4735   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4736                                    APInt::getAllOnesValue(OpSizeInBits)))
4737     return DAG.getConstant(0, SDLoc(N), VT);
4738
4739   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4740   if (N1C && N0.getOpcode() == ISD::SRL) {
4741     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4742       uint64_t c1 = N01C->getZExtValue();
4743       uint64_t c2 = N1C->getZExtValue();
4744       SDLoc DL(N);
4745       if (c1 + c2 >= OpSizeInBits)
4746         return DAG.getConstant(0, DL, VT);
4747       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4748                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4749     }
4750   }
4751
4752   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4753   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4754       N0.getOperand(0).getOpcode() == ISD::SRL &&
4755       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4756     uint64_t c1 =
4757       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4758     uint64_t c2 = N1C->getZExtValue();
4759     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4760     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4761     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4762     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4763     if (c1 + OpSizeInBits == InnerShiftSize) {
4764       SDLoc DL(N0);
4765       if (c1 + c2 >= InnerShiftSize)
4766         return DAG.getConstant(0, DL, VT);
4767       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4768                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4769                                      N0.getOperand(0)->getOperand(0),
4770                                      DAG.getConstant(c1 + c2, DL,
4771                                                      ShiftCountVT)));
4772     }
4773   }
4774
4775   // fold (srl (shl x, c), c) -> (and x, cst2)
4776   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4777     unsigned BitSize = N0.getScalarValueSizeInBits();
4778     if (BitSize <= 64) {
4779       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4780       SDLoc DL(N);
4781       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4782                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4783     }
4784   }
4785
4786   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4787   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4788     // Shifting in all undef bits?
4789     EVT SmallVT = N0.getOperand(0).getValueType();
4790     unsigned BitSize = SmallVT.getScalarSizeInBits();
4791     if (N1C->getZExtValue() >= BitSize)
4792       return DAG.getUNDEF(VT);
4793
4794     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4795       uint64_t ShiftAmt = N1C->getZExtValue();
4796       SDLoc DL0(N0);
4797       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4798                                        N0.getOperand(0),
4799                           DAG.getConstant(ShiftAmt, DL0,
4800                                           getShiftAmountTy(SmallVT)));
4801       AddToWorklist(SmallShift.getNode());
4802       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4803       SDLoc DL(N);
4804       return DAG.getNode(ISD::AND, DL, VT,
4805                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4806                          DAG.getConstant(Mask, DL, VT));
4807     }
4808   }
4809
4810   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4811   // bit, which is unmodified by sra.
4812   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4813     if (N0.getOpcode() == ISD::SRA)
4814       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4815   }
4816
4817   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4818   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4819       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4820     APInt KnownZero, KnownOne;
4821     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4822
4823     // If any of the input bits are KnownOne, then the input couldn't be all
4824     // zeros, thus the result of the srl will always be zero.
4825     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4826
4827     // If all of the bits input the to ctlz node are known to be zero, then
4828     // the result of the ctlz is "32" and the result of the shift is one.
4829     APInt UnknownBits = ~KnownZero;
4830     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4831
4832     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4833     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4834       // Okay, we know that only that the single bit specified by UnknownBits
4835       // could be set on input to the CTLZ node. If this bit is set, the SRL
4836       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4837       // to an SRL/XOR pair, which is likely to simplify more.
4838       unsigned ShAmt = UnknownBits.countTrailingZeros();
4839       SDValue Op = N0.getOperand(0);
4840
4841       if (ShAmt) {
4842         SDLoc DL(N0);
4843         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4844                   DAG.getConstant(ShAmt, DL,
4845                                   getShiftAmountTy(Op.getValueType())));
4846         AddToWorklist(Op.getNode());
4847       }
4848
4849       SDLoc DL(N);
4850       return DAG.getNode(ISD::XOR, DL, VT,
4851                          Op, DAG.getConstant(1, DL, VT));
4852     }
4853   }
4854
4855   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4856   if (N1.getOpcode() == ISD::TRUNCATE &&
4857       N1.getOperand(0).getOpcode() == ISD::AND) {
4858     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4859       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4860   }
4861
4862   // fold operands of srl based on knowledge that the low bits are not
4863   // demanded.
4864   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4865     return SDValue(N, 0);
4866
4867   if (N1C && !N1C->isOpaque())
4868     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4869       return NewSRL;
4870
4871   // Attempt to convert a srl of a load into a narrower zero-extending load.
4872   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4873     return NarrowLoad;
4874
4875   // Here is a common situation. We want to optimize:
4876   //
4877   //   %a = ...
4878   //   %b = and i32 %a, 2
4879   //   %c = srl i32 %b, 1
4880   //   brcond i32 %c ...
4881   //
4882   // into
4883   //
4884   //   %a = ...
4885   //   %b = and %a, 2
4886   //   %c = setcc eq %b, 0
4887   //   brcond %c ...
4888   //
4889   // However when after the source operand of SRL is optimized into AND, the SRL
4890   // itself may not be optimized further. Look for it and add the BRCOND into
4891   // the worklist.
4892   if (N->hasOneUse()) {
4893     SDNode *Use = *N->use_begin();
4894     if (Use->getOpcode() == ISD::BRCOND)
4895       AddToWorklist(Use);
4896     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4897       // Also look pass the truncate.
4898       Use = *Use->use_begin();
4899       if (Use->getOpcode() == ISD::BRCOND)
4900         AddToWorklist(Use);
4901     }
4902   }
4903
4904   return SDValue();
4905 }
4906
4907 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4908   SDValue N0 = N->getOperand(0);
4909   EVT VT = N->getValueType(0);
4910
4911   // fold (bswap c1) -> c2
4912   if (isConstantIntBuildVectorOrConstantInt(N0))
4913     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4914   // fold (bswap (bswap x)) -> x
4915   if (N0.getOpcode() == ISD::BSWAP)
4916     return N0->getOperand(0);
4917   return SDValue();
4918 }
4919
4920 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4921   SDValue N0 = N->getOperand(0);
4922   EVT VT = N->getValueType(0);
4923
4924   // fold (ctlz c1) -> c2
4925   if (isConstantIntBuildVectorOrConstantInt(N0))
4926     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4927   return SDValue();
4928 }
4929
4930 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4931   SDValue N0 = N->getOperand(0);
4932   EVT VT = N->getValueType(0);
4933
4934   // fold (ctlz_zero_undef c1) -> c2
4935   if (isConstantIntBuildVectorOrConstantInt(N0))
4936     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4937   return SDValue();
4938 }
4939
4940 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4941   SDValue N0 = N->getOperand(0);
4942   EVT VT = N->getValueType(0);
4943
4944   // fold (cttz c1) -> c2
4945   if (isConstantIntBuildVectorOrConstantInt(N0))
4946     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4947   return SDValue();
4948 }
4949
4950 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4951   SDValue N0 = N->getOperand(0);
4952   EVT VT = N->getValueType(0);
4953
4954   // fold (cttz_zero_undef c1) -> c2
4955   if (isConstantIntBuildVectorOrConstantInt(N0))
4956     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4957   return SDValue();
4958 }
4959
4960 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4961   SDValue N0 = N->getOperand(0);
4962   EVT VT = N->getValueType(0);
4963
4964   // fold (ctpop c1) -> c2
4965   if (isConstantIntBuildVectorOrConstantInt(N0))
4966     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4967   return SDValue();
4968 }
4969
4970
4971 /// \brief Generate Min/Max node
4972 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4973                                    SDValue True, SDValue False,
4974                                    ISD::CondCode CC, const TargetLowering &TLI,
4975                                    SelectionDAG &DAG) {
4976   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4977     return SDValue();
4978
4979   switch (CC) {
4980   case ISD::SETOLT:
4981   case ISD::SETOLE:
4982   case ISD::SETLT:
4983   case ISD::SETLE:
4984   case ISD::SETULT:
4985   case ISD::SETULE: {
4986     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4987     if (TLI.isOperationLegal(Opcode, VT))
4988       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4989     return SDValue();
4990   }
4991   case ISD::SETOGT:
4992   case ISD::SETOGE:
4993   case ISD::SETGT:
4994   case ISD::SETGE:
4995   case ISD::SETUGT:
4996   case ISD::SETUGE: {
4997     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4998     if (TLI.isOperationLegal(Opcode, VT))
4999       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
5000     return SDValue();
5001   }
5002   default:
5003     return SDValue();
5004   }
5005 }
5006
5007 SDValue DAGCombiner::visitSELECT(SDNode *N) {
5008   SDValue N0 = N->getOperand(0);
5009   SDValue N1 = N->getOperand(1);
5010   SDValue N2 = N->getOperand(2);
5011   EVT VT = N->getValueType(0);
5012   EVT VT0 = N0.getValueType();
5013
5014   // fold (select C, X, X) -> X
5015   if (N1 == N2)
5016     return N1;
5017   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
5018     // fold (select true, X, Y) -> X
5019     // fold (select false, X, Y) -> Y
5020     return !N0C->isNullValue() ? N1 : N2;
5021   }
5022   // fold (select C, 1, X) -> (or C, X)
5023   if (VT == MVT::i1 && isOneConstant(N1))
5024     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5025   // fold (select C, 0, 1) -> (xor C, 1)
5026   // We can't do this reliably if integer based booleans have different contents
5027   // to floating point based booleans. This is because we can't tell whether we
5028   // have an integer-based boolean or a floating-point-based boolean unless we
5029   // can find the SETCC that produced it and inspect its operands. This is
5030   // fairly easy if C is the SETCC node, but it can potentially be
5031   // undiscoverable (or not reasonably discoverable). For example, it could be
5032   // in another basic block or it could require searching a complicated
5033   // expression.
5034   if (VT.isInteger() &&
5035       (VT0 == MVT::i1 || (VT0.isInteger() &&
5036                           TLI.getBooleanContents(false, false) ==
5037                               TLI.getBooleanContents(false, true) &&
5038                           TLI.getBooleanContents(false, false) ==
5039                               TargetLowering::ZeroOrOneBooleanContent)) &&
5040       isNullConstant(N1) && isOneConstant(N2)) {
5041     SDValue XORNode;
5042     if (VT == VT0) {
5043       SDLoc DL(N);
5044       return DAG.getNode(ISD::XOR, DL, VT0,
5045                          N0, DAG.getConstant(1, DL, VT0));
5046     }
5047     SDLoc DL0(N0);
5048     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5049                           N0, DAG.getConstant(1, DL0, VT0));
5050     AddToWorklist(XORNode.getNode());
5051     if (VT.bitsGT(VT0))
5052       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5053     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5054   }
5055   // fold (select C, 0, X) -> (and (not C), X)
5056   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5057     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5058     AddToWorklist(NOTNode.getNode());
5059     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5060   }
5061   // fold (select C, X, 1) -> (or (not C), X)
5062   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5063     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5064     AddToWorklist(NOTNode.getNode());
5065     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5066   }
5067   // fold (select C, X, 0) -> (and C, X)
5068   if (VT == MVT::i1 && isNullConstant(N2))
5069     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5070   // fold (select X, X, Y) -> (or X, Y)
5071   // fold (select X, 1, Y) -> (or X, Y)
5072   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5073     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5074   // fold (select X, Y, X) -> (and X, Y)
5075   // fold (select X, Y, 0) -> (and X, Y)
5076   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5077     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5078
5079   // If we can fold this based on the true/false value, do so.
5080   if (SimplifySelectOps(N, N1, N2))
5081     return SDValue(N, 0);  // Don't revisit N.
5082
5083   if (VT0 == MVT::i1) {
5084     // The code in this block deals with the following 2 equivalences:
5085     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5086     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5087     // The target can specify its prefered form with the
5088     // shouldNormalizeToSelectSequence() callback. However we always transform
5089     // to the right anyway if we find the inner select exists in the DAG anyway
5090     // and we always transform to the left side if we know that we can further
5091     // optimize the combination of the conditions.
5092     bool normalizeToSequence
5093       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5094     // select (and Cond0, Cond1), X, Y
5095     //   -> select Cond0, (select Cond1, X, Y), Y
5096     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5097       SDValue Cond0 = N0->getOperand(0);
5098       SDValue Cond1 = N0->getOperand(1);
5099       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5100                                         N1.getValueType(), Cond1, N1, N2);
5101       if (normalizeToSequence || !InnerSelect.use_empty())
5102         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5103                            InnerSelect, N2);
5104     }
5105     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5106     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5107       SDValue Cond0 = N0->getOperand(0);
5108       SDValue Cond1 = N0->getOperand(1);
5109       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5110                                         N1.getValueType(), Cond1, N1, N2);
5111       if (normalizeToSequence || !InnerSelect.use_empty())
5112         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5113                            InnerSelect);
5114     }
5115
5116     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5117     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5118       SDValue N1_0 = N1->getOperand(0);
5119       SDValue N1_1 = N1->getOperand(1);
5120       SDValue N1_2 = N1->getOperand(2);
5121       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5122         // Create the actual and node if we can generate good code for it.
5123         if (!normalizeToSequence) {
5124           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5125                                     N0, N1_0);
5126           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5127                              N1_1, N2);
5128         }
5129         // Otherwise see if we can optimize the "and" to a better pattern.
5130         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5131           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5132                              N1_1, N2);
5133       }
5134     }
5135     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5136     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5137       SDValue N2_0 = N2->getOperand(0);
5138       SDValue N2_1 = N2->getOperand(1);
5139       SDValue N2_2 = N2->getOperand(2);
5140       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5141         // Create the actual or node if we can generate good code for it.
5142         if (!normalizeToSequence) {
5143           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5144                                    N0, N2_0);
5145           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5146                              N1, N2_2);
5147         }
5148         // Otherwise see if we can optimize to a better pattern.
5149         if (SDValue Combined = visitORLike(N0, N2_0, N))
5150           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5151                              N1, N2_2);
5152       }
5153     }
5154   }
5155
5156   // fold selects based on a setcc into other things, such as min/max/abs
5157   if (N0.getOpcode() == ISD::SETCC) {
5158     // select x, y (fcmp lt x, y) -> fminnum x, y
5159     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5160     //
5161     // This is OK if we don't care about what happens if either operand is a
5162     // NaN.
5163     //
5164
5165     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5166     // no signed zeros as well as no nans.
5167     const TargetOptions &Options = DAG.getTarget().Options;
5168     if (Options.UnsafeFPMath &&
5169         VT.isFloatingPoint() && N0.hasOneUse() &&
5170         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5171       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5172
5173       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5174                                                 N0.getOperand(1), N1, N2, CC,
5175                                                 TLI, DAG))
5176         return FMinMax;
5177     }
5178
5179     if ((!LegalOperations &&
5180          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5181         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5182       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5183                          N0.getOperand(0), N0.getOperand(1),
5184                          N1, N2, N0.getOperand(2));
5185     return SimplifySelect(SDLoc(N), N0, N1, N2);
5186   }
5187
5188   return SDValue();
5189 }
5190
5191 static
5192 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5193   SDLoc DL(N);
5194   EVT LoVT, HiVT;
5195   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5196
5197   // Split the inputs.
5198   SDValue Lo, Hi, LL, LH, RL, RH;
5199   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5200   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5201
5202   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5203   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5204
5205   return std::make_pair(Lo, Hi);
5206 }
5207
5208 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5209 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5210 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5211   SDLoc dl(N);
5212   SDValue Cond = N->getOperand(0);
5213   SDValue LHS = N->getOperand(1);
5214   SDValue RHS = N->getOperand(2);
5215   EVT VT = N->getValueType(0);
5216   int NumElems = VT.getVectorNumElements();
5217   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5218          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5219          Cond.getOpcode() == ISD::BUILD_VECTOR);
5220
5221   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5222   // binary ones here.
5223   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5224     return SDValue();
5225
5226   // We're sure we have an even number of elements due to the
5227   // concat_vectors we have as arguments to vselect.
5228   // Skip BV elements until we find one that's not an UNDEF
5229   // After we find an UNDEF element, keep looping until we get to half the
5230   // length of the BV and see if all the non-undef nodes are the same.
5231   ConstantSDNode *BottomHalf = nullptr;
5232   for (int i = 0; i < NumElems / 2; ++i) {
5233     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5234       continue;
5235
5236     if (BottomHalf == nullptr)
5237       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5238     else if (Cond->getOperand(i).getNode() != BottomHalf)
5239       return SDValue();
5240   }
5241
5242   // Do the same for the second half of the BuildVector
5243   ConstantSDNode *TopHalf = nullptr;
5244   for (int i = NumElems / 2; i < NumElems; ++i) {
5245     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5246       continue;
5247
5248     if (TopHalf == nullptr)
5249       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5250     else if (Cond->getOperand(i).getNode() != TopHalf)
5251       return SDValue();
5252   }
5253
5254   assert(TopHalf && BottomHalf &&
5255          "One half of the selector was all UNDEFs and the other was all the "
5256          "same value. This should have been addressed before this function.");
5257   return DAG.getNode(
5258       ISD::CONCAT_VECTORS, dl, VT,
5259       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5260       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5261 }
5262
5263 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5264
5265   if (Level >= AfterLegalizeTypes)
5266     return SDValue();
5267
5268   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5269   SDValue Mask = MSC->getMask();
5270   SDValue Data  = MSC->getValue();
5271   SDLoc DL(N);
5272
5273   // If the MSCATTER data type requires splitting and the mask is provided by a
5274   // SETCC, then split both nodes and its operands before legalization. This
5275   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5276   // and enables future optimizations (e.g. min/max pattern matching on X86).
5277   if (Mask.getOpcode() != ISD::SETCC)
5278     return SDValue();
5279
5280   // Check if any splitting is required.
5281   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5282       TargetLowering::TypeSplitVector)
5283     return SDValue();
5284   SDValue MaskLo, MaskHi, Lo, Hi;
5285   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5286
5287   EVT LoVT, HiVT;
5288   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5289
5290   SDValue Chain = MSC->getChain();
5291
5292   EVT MemoryVT = MSC->getMemoryVT();
5293   unsigned Alignment = MSC->getOriginalAlignment();
5294
5295   EVT LoMemVT, HiMemVT;
5296   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5297
5298   SDValue DataLo, DataHi;
5299   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5300
5301   SDValue BasePtr = MSC->getBasePtr();
5302   SDValue IndexLo, IndexHi;
5303   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5304
5305   MachineMemOperand *MMO = DAG.getMachineFunction().
5306     getMachineMemOperand(MSC->getPointerInfo(),
5307                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5308                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5309
5310   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5311   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5312                             DL, OpsLo, MMO);
5313
5314   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5315   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5316                             DL, OpsHi, MMO);
5317
5318   AddToWorklist(Lo.getNode());
5319   AddToWorklist(Hi.getNode());
5320
5321   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5322 }
5323
5324 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5325
5326   if (Level >= AfterLegalizeTypes)
5327     return SDValue();
5328
5329   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5330   SDValue Mask = MST->getMask();
5331   SDValue Data  = MST->getValue();
5332   SDLoc DL(N);
5333
5334   // If the MSTORE data type requires splitting and the mask is provided by a
5335   // SETCC, then split both nodes and its operands before legalization. This
5336   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5337   // and enables future optimizations (e.g. min/max pattern matching on X86).
5338   if (Mask.getOpcode() == ISD::SETCC) {
5339
5340     // Check if any splitting is required.
5341     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5342         TargetLowering::TypeSplitVector)
5343       return SDValue();
5344
5345     SDValue MaskLo, MaskHi, Lo, Hi;
5346     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5347
5348     EVT LoVT, HiVT;
5349     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5350
5351     SDValue Chain = MST->getChain();
5352     SDValue Ptr   = MST->getBasePtr();
5353
5354     EVT MemoryVT = MST->getMemoryVT();
5355     unsigned Alignment = MST->getOriginalAlignment();
5356
5357     // if Alignment is equal to the vector size,
5358     // take the half of it for the second part
5359     unsigned SecondHalfAlignment =
5360       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5361          Alignment/2 : Alignment;
5362
5363     EVT LoMemVT, HiMemVT;
5364     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5365
5366     SDValue DataLo, DataHi;
5367     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5368
5369     MachineMemOperand *MMO = DAG.getMachineFunction().
5370       getMachineMemOperand(MST->getPointerInfo(),
5371                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5372                            Alignment, MST->getAAInfo(), MST->getRanges());
5373
5374     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5375                             MST->isTruncatingStore());
5376
5377     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5378     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5379                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5380
5381     MMO = DAG.getMachineFunction().
5382       getMachineMemOperand(MST->getPointerInfo(),
5383                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5384                            SecondHalfAlignment, MST->getAAInfo(),
5385                            MST->getRanges());
5386
5387     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5388                             MST->isTruncatingStore());
5389
5390     AddToWorklist(Lo.getNode());
5391     AddToWorklist(Hi.getNode());
5392
5393     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5394   }
5395   return SDValue();
5396 }
5397
5398 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5399
5400   if (Level >= AfterLegalizeTypes)
5401     return SDValue();
5402
5403   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5404   SDValue Mask = MGT->getMask();
5405   SDLoc DL(N);
5406
5407   // If the MGATHER result requires splitting and the mask is provided by a
5408   // SETCC, then split both nodes and its operands before legalization. This
5409   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5410   // and enables future optimizations (e.g. min/max pattern matching on X86).
5411
5412   if (Mask.getOpcode() != ISD::SETCC)
5413     return SDValue();
5414
5415   EVT VT = N->getValueType(0);
5416
5417   // Check if any splitting is required.
5418   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5419       TargetLowering::TypeSplitVector)
5420     return SDValue();
5421
5422   SDValue MaskLo, MaskHi, Lo, Hi;
5423   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5424
5425   SDValue Src0 = MGT->getValue();
5426   SDValue Src0Lo, Src0Hi;
5427   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5428
5429   EVT LoVT, HiVT;
5430   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5431
5432   SDValue Chain = MGT->getChain();
5433   EVT MemoryVT = MGT->getMemoryVT();
5434   unsigned Alignment = MGT->getOriginalAlignment();
5435
5436   EVT LoMemVT, HiMemVT;
5437   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5438
5439   SDValue BasePtr = MGT->getBasePtr();
5440   SDValue Index = MGT->getIndex();
5441   SDValue IndexLo, IndexHi;
5442   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5443
5444   MachineMemOperand *MMO = DAG.getMachineFunction().
5445     getMachineMemOperand(MGT->getPointerInfo(),
5446                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5447                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5448
5449   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5450   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5451                             MMO);
5452
5453   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5454   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5455                             MMO);
5456
5457   AddToWorklist(Lo.getNode());
5458   AddToWorklist(Hi.getNode());
5459
5460   // Build a factor node to remember that this load is independent of the
5461   // other one.
5462   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5463                       Hi.getValue(1));
5464
5465   // Legalized the chain result - switch anything that used the old chain to
5466   // use the new one.
5467   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5468
5469   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5470
5471   SDValue RetOps[] = { GatherRes, Chain };
5472   return DAG.getMergeValues(RetOps, DL);
5473 }
5474
5475 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5476
5477   if (Level >= AfterLegalizeTypes)
5478     return SDValue();
5479
5480   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5481   SDValue Mask = MLD->getMask();
5482   SDLoc DL(N);
5483
5484   // If the MLOAD result requires splitting and the mask is provided by a
5485   // SETCC, then split both nodes and its operands before legalization. This
5486   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5487   // and enables future optimizations (e.g. min/max pattern matching on X86).
5488
5489   if (Mask.getOpcode() == ISD::SETCC) {
5490     EVT VT = N->getValueType(0);
5491
5492     // Check if any splitting is required.
5493     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5494         TargetLowering::TypeSplitVector)
5495       return SDValue();
5496
5497     SDValue MaskLo, MaskHi, Lo, Hi;
5498     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5499
5500     SDValue Src0 = MLD->getSrc0();
5501     SDValue Src0Lo, Src0Hi;
5502     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5503
5504     EVT LoVT, HiVT;
5505     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5506
5507     SDValue Chain = MLD->getChain();
5508     SDValue Ptr   = MLD->getBasePtr();
5509     EVT MemoryVT = MLD->getMemoryVT();
5510     unsigned Alignment = MLD->getOriginalAlignment();
5511
5512     // if Alignment is equal to the vector size,
5513     // take the half of it for the second part
5514     unsigned SecondHalfAlignment =
5515       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5516          Alignment/2 : Alignment;
5517
5518     EVT LoMemVT, HiMemVT;
5519     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5520
5521     MachineMemOperand *MMO = DAG.getMachineFunction().
5522     getMachineMemOperand(MLD->getPointerInfo(),
5523                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5524                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5525
5526     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5527                            ISD::NON_EXTLOAD);
5528
5529     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5530     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5531                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5532
5533     MMO = DAG.getMachineFunction().
5534     getMachineMemOperand(MLD->getPointerInfo(),
5535                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5536                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5537
5538     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5539                            ISD::NON_EXTLOAD);
5540
5541     AddToWorklist(Lo.getNode());
5542     AddToWorklist(Hi.getNode());
5543
5544     // Build a factor node to remember that this load is independent of the
5545     // other one.
5546     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5547                         Hi.getValue(1));
5548
5549     // Legalized the chain result - switch anything that used the old chain to
5550     // use the new one.
5551     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5552
5553     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5554
5555     SDValue RetOps[] = { LoadRes, Chain };
5556     return DAG.getMergeValues(RetOps, DL);
5557   }
5558   return SDValue();
5559 }
5560
5561 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5562   SDValue N0 = N->getOperand(0);
5563   SDValue N1 = N->getOperand(1);
5564   SDValue N2 = N->getOperand(2);
5565   SDLoc DL(N);
5566
5567   // Canonicalize integer abs.
5568   // vselect (setg[te] X,  0),  X, -X ->
5569   // vselect (setgt    X, -1),  X, -X ->
5570   // vselect (setl[te] X,  0), -X,  X ->
5571   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5572   if (N0.getOpcode() == ISD::SETCC) {
5573     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5574     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5575     bool isAbs = false;
5576     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5577
5578     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5579          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5580         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5581       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5582     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5583              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5584       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5585
5586     if (isAbs) {
5587       EVT VT = LHS.getValueType();
5588       SDValue Shift = DAG.getNode(
5589           ISD::SRA, DL, VT, LHS,
5590           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5591       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5592       AddToWorklist(Shift.getNode());
5593       AddToWorklist(Add.getNode());
5594       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5595     }
5596   }
5597
5598   if (SimplifySelectOps(N, N1, N2))
5599     return SDValue(N, 0);  // Don't revisit N.
5600
5601   // If the VSELECT result requires splitting and the mask is provided by a
5602   // SETCC, then split both nodes and its operands before legalization. This
5603   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5604   // and enables future optimizations (e.g. min/max pattern matching on X86).
5605   if (N0.getOpcode() == ISD::SETCC) {
5606     EVT VT = N->getValueType(0);
5607
5608     // Check if any splitting is required.
5609     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5610         TargetLowering::TypeSplitVector)
5611       return SDValue();
5612
5613     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5614     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5615     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5616     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5617
5618     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5619     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5620
5621     // Add the new VSELECT nodes to the work list in case they need to be split
5622     // again.
5623     AddToWorklist(Lo.getNode());
5624     AddToWorklist(Hi.getNode());
5625
5626     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5627   }
5628
5629   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5630   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5631     return N1;
5632   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5633   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5634     return N2;
5635
5636   // The ConvertSelectToConcatVector function is assuming both the above
5637   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5638   // and addressed.
5639   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5640       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5641       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5642     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5643       return CV;
5644   }
5645
5646   return SDValue();
5647 }
5648
5649 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5650   SDValue N0 = N->getOperand(0);
5651   SDValue N1 = N->getOperand(1);
5652   SDValue N2 = N->getOperand(2);
5653   SDValue N3 = N->getOperand(3);
5654   SDValue N4 = N->getOperand(4);
5655   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5656
5657   // fold select_cc lhs, rhs, x, x, cc -> x
5658   if (N2 == N3)
5659     return N2;
5660
5661   // Determine if the condition we're dealing with is constant
5662   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5663                               N0, N1, CC, SDLoc(N), false);
5664   if (SCC.getNode()) {
5665     AddToWorklist(SCC.getNode());
5666
5667     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5668       if (!SCCC->isNullValue())
5669         return N2;    // cond always true -> true val
5670       else
5671         return N3;    // cond always false -> false val
5672     } else if (SCC->getOpcode() == ISD::UNDEF) {
5673       // When the condition is UNDEF, just return the first operand. This is
5674       // coherent the DAG creation, no setcc node is created in this case
5675       return N2;
5676     } else if (SCC.getOpcode() == ISD::SETCC) {
5677       // Fold to a simpler select_cc
5678       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5679                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5680                          SCC.getOperand(2));
5681     }
5682   }
5683
5684   // If we can fold this based on the true/false value, do so.
5685   if (SimplifySelectOps(N, N2, N3))
5686     return SDValue(N, 0);  // Don't revisit N.
5687
5688   // fold select_cc into other things, such as min/max/abs
5689   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5690 }
5691
5692 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5693   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5694                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5695                        SDLoc(N));
5696 }
5697
5698 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5699 /// a build_vector of constants.
5700 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5701 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5702 /// Vector extends are not folded if operations are legal; this is to
5703 /// avoid introducing illegal build_vector dag nodes.
5704 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5705                                          SelectionDAG &DAG, bool LegalTypes,
5706                                          bool LegalOperations) {
5707   unsigned Opcode = N->getOpcode();
5708   SDValue N0 = N->getOperand(0);
5709   EVT VT = N->getValueType(0);
5710
5711   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5712          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5713          && "Expected EXTEND dag node in input!");
5714
5715   // fold (sext c1) -> c1
5716   // fold (zext c1) -> c1
5717   // fold (aext c1) -> c1
5718   if (isa<ConstantSDNode>(N0))
5719     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5720
5721   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5722   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5723   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5724   EVT SVT = VT.getScalarType();
5725   if (!(VT.isVector() &&
5726       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5727       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5728     return nullptr;
5729
5730   // We can fold this node into a build_vector.
5731   unsigned VTBits = SVT.getSizeInBits();
5732   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5733   SmallVector<SDValue, 8> Elts;
5734   unsigned NumElts = VT.getVectorNumElements();
5735   SDLoc DL(N);
5736
5737   for (unsigned i=0; i != NumElts; ++i) {
5738     SDValue Op = N0->getOperand(i);
5739     if (Op->getOpcode() == ISD::UNDEF) {
5740       Elts.push_back(DAG.getUNDEF(SVT));
5741       continue;
5742     }
5743
5744     SDLoc DL(Op);
5745     // Get the constant value and if needed trunc it to the size of the type.
5746     // Nodes like build_vector might have constants wider than the scalar type.
5747     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5748     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5749       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5750     else
5751       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5752   }
5753
5754   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5755 }
5756
5757 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5758 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5759 // transformation. Returns true if extension are possible and the above
5760 // mentioned transformation is profitable.
5761 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5762                                     unsigned ExtOpc,
5763                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5764                                     const TargetLowering &TLI) {
5765   bool HasCopyToRegUses = false;
5766   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5767   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5768                             UE = N0.getNode()->use_end();
5769        UI != UE; ++UI) {
5770     SDNode *User = *UI;
5771     if (User == N)
5772       continue;
5773     if (UI.getUse().getResNo() != N0.getResNo())
5774       continue;
5775     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5776     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5777       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5778       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5779         // Sign bits will be lost after a zext.
5780         return false;
5781       bool Add = false;
5782       for (unsigned i = 0; i != 2; ++i) {
5783         SDValue UseOp = User->getOperand(i);
5784         if (UseOp == N0)
5785           continue;
5786         if (!isa<ConstantSDNode>(UseOp))
5787           return false;
5788         Add = true;
5789       }
5790       if (Add)
5791         ExtendNodes.push_back(User);
5792       continue;
5793     }
5794     // If truncates aren't free and there are users we can't
5795     // extend, it isn't worthwhile.
5796     if (!isTruncFree)
5797       return false;
5798     // Remember if this value is live-out.
5799     if (User->getOpcode() == ISD::CopyToReg)
5800       HasCopyToRegUses = true;
5801   }
5802
5803   if (HasCopyToRegUses) {
5804     bool BothLiveOut = false;
5805     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5806          UI != UE; ++UI) {
5807       SDUse &Use = UI.getUse();
5808       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5809         BothLiveOut = true;
5810         break;
5811       }
5812     }
5813     if (BothLiveOut)
5814       // Both unextended and extended values are live out. There had better be
5815       // a good reason for the transformation.
5816       return ExtendNodes.size();
5817   }
5818   return true;
5819 }
5820
5821 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5822                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5823                                   ISD::NodeType ExtType) {
5824   // Extend SetCC uses if necessary.
5825   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5826     SDNode *SetCC = SetCCs[i];
5827     SmallVector<SDValue, 4> Ops;
5828
5829     for (unsigned j = 0; j != 2; ++j) {
5830       SDValue SOp = SetCC->getOperand(j);
5831       if (SOp == Trunc)
5832         Ops.push_back(ExtLoad);
5833       else
5834         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5835     }
5836
5837     Ops.push_back(SetCC->getOperand(2));
5838     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5839   }
5840 }
5841
5842 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5843 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5844   SDValue N0 = N->getOperand(0);
5845   EVT DstVT = N->getValueType(0);
5846   EVT SrcVT = N0.getValueType();
5847
5848   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5849           N->getOpcode() == ISD::ZERO_EXTEND) &&
5850          "Unexpected node type (not an extend)!");
5851
5852   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5853   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5854   //   (v8i32 (sext (v8i16 (load x))))
5855   // into:
5856   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5857   //                          (v4i32 (sextload (x + 16)))))
5858   // Where uses of the original load, i.e.:
5859   //   (v8i16 (load x))
5860   // are replaced with:
5861   //   (v8i16 (truncate
5862   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5863   //                            (v4i32 (sextload (x + 16)))))))
5864   //
5865   // This combine is only applicable to illegal, but splittable, vectors.
5866   // All legal types, and illegal non-vector types, are handled elsewhere.
5867   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5868   //
5869   if (N0->getOpcode() != ISD::LOAD)
5870     return SDValue();
5871
5872   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5873
5874   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5875       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5876       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5877     return SDValue();
5878
5879   SmallVector<SDNode *, 4> SetCCs;
5880   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5881     return SDValue();
5882
5883   ISD::LoadExtType ExtType =
5884       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5885
5886   // Try to split the vector types to get down to legal types.
5887   EVT SplitSrcVT = SrcVT;
5888   EVT SplitDstVT = DstVT;
5889   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5890          SplitSrcVT.getVectorNumElements() > 1) {
5891     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5892     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5893   }
5894
5895   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5896     return SDValue();
5897
5898   SDLoc DL(N);
5899   const unsigned NumSplits =
5900       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5901   const unsigned Stride = SplitSrcVT.getStoreSize();
5902   SmallVector<SDValue, 4> Loads;
5903   SmallVector<SDValue, 4> Chains;
5904
5905   SDValue BasePtr = LN0->getBasePtr();
5906   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5907     const unsigned Offset = Idx * Stride;
5908     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5909
5910     SDValue SplitLoad = DAG.getExtLoad(
5911         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5912         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5913         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5914         Align, LN0->getAAInfo());
5915
5916     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5917                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5918
5919     Loads.push_back(SplitLoad.getValue(0));
5920     Chains.push_back(SplitLoad.getValue(1));
5921   }
5922
5923   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5924   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5925
5926   CombineTo(N, NewValue);
5927
5928   // Replace uses of the original load (before extension)
5929   // with a truncate of the concatenated sextloaded vectors.
5930   SDValue Trunc =
5931       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5932   CombineTo(N0.getNode(), Trunc, NewChain);
5933   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5934                   (ISD::NodeType)N->getOpcode());
5935   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5936 }
5937
5938 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5939   SDValue N0 = N->getOperand(0);
5940   EVT VT = N->getValueType(0);
5941
5942   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5943                                               LegalOperations))
5944     return SDValue(Res, 0);
5945
5946   // fold (sext (sext x)) -> (sext x)
5947   // fold (sext (aext x)) -> (sext x)
5948   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5949     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5950                        N0.getOperand(0));
5951
5952   if (N0.getOpcode() == ISD::TRUNCATE) {
5953     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5954     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5955     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5956       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5957       if (NarrowLoad.getNode() != N0.getNode()) {
5958         CombineTo(N0.getNode(), NarrowLoad);
5959         // CombineTo deleted the truncate, if needed, but not what's under it.
5960         AddToWorklist(oye);
5961       }
5962       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5963     }
5964
5965     // See if the value being truncated is already sign extended.  If so, just
5966     // eliminate the trunc/sext pair.
5967     SDValue Op = N0.getOperand(0);
5968     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5969     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5970     unsigned DestBits = VT.getScalarType().getSizeInBits();
5971     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5972
5973     if (OpBits == DestBits) {
5974       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5975       // bits, it is already ready.
5976       if (NumSignBits > DestBits-MidBits)
5977         return Op;
5978     } else if (OpBits < DestBits) {
5979       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5980       // bits, just sext from i32.
5981       if (NumSignBits > OpBits-MidBits)
5982         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5983     } else {
5984       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5985       // bits, just truncate to i32.
5986       if (NumSignBits > OpBits-MidBits)
5987         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5988     }
5989
5990     // fold (sext (truncate x)) -> (sextinreg x).
5991     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5992                                                  N0.getValueType())) {
5993       if (OpBits < DestBits)
5994         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5995       else if (OpBits > DestBits)
5996         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5997       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5998                          DAG.getValueType(N0.getValueType()));
5999     }
6000   }
6001
6002   // fold (sext (load x)) -> (sext (truncate (sextload x)))
6003   // Only generate vector extloads when 1) they're legal, and 2) they are
6004   // deemed desirable by the target.
6005   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6006       ((!LegalOperations && !VT.isVector() &&
6007         !cast<LoadSDNode>(N0)->isVolatile()) ||
6008        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
6009     bool DoXform = true;
6010     SmallVector<SDNode*, 4> SetCCs;
6011     if (!N0.hasOneUse())
6012       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
6013     if (VT.isVector())
6014       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6015     if (DoXform) {
6016       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6018                                        LN0->getChain(),
6019                                        LN0->getBasePtr(), N0.getValueType(),
6020                                        LN0->getMemOperand());
6021       CombineTo(N, ExtLoad);
6022       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6023                                   N0.getValueType(), ExtLoad);
6024       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6025       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6026                       ISD::SIGN_EXTEND);
6027       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6028     }
6029   }
6030
6031   // fold (sext (load x)) to multiple smaller sextloads.
6032   // Only on illegal but splittable vectors.
6033   if (SDValue ExtLoad = CombineExtLoad(N))
6034     return ExtLoad;
6035
6036   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6037   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6038   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6039       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6040     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6041     EVT MemVT = LN0->getMemoryVT();
6042     if ((!LegalOperations && !LN0->isVolatile()) ||
6043         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6044       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6045                                        LN0->getChain(),
6046                                        LN0->getBasePtr(), MemVT,
6047                                        LN0->getMemOperand());
6048       CombineTo(N, ExtLoad);
6049       CombineTo(N0.getNode(),
6050                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6051                             N0.getValueType(), ExtLoad),
6052                 ExtLoad.getValue(1));
6053       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6054     }
6055   }
6056
6057   // fold (sext (and/or/xor (load x), cst)) ->
6058   //      (and/or/xor (sextload x), (sext cst))
6059   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6060        N0.getOpcode() == ISD::XOR) &&
6061       isa<LoadSDNode>(N0.getOperand(0)) &&
6062       N0.getOperand(1).getOpcode() == ISD::Constant &&
6063       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6064       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6065     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6066     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6067       bool DoXform = true;
6068       SmallVector<SDNode*, 4> SetCCs;
6069       if (!N0.hasOneUse())
6070         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6071                                           SetCCs, TLI);
6072       if (DoXform) {
6073         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6074                                          LN0->getChain(), LN0->getBasePtr(),
6075                                          LN0->getMemoryVT(),
6076                                          LN0->getMemOperand());
6077         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6078         Mask = Mask.sext(VT.getSizeInBits());
6079         SDLoc DL(N);
6080         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6081                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6082         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6083                                     SDLoc(N0.getOperand(0)),
6084                                     N0.getOperand(0).getValueType(), ExtLoad);
6085         CombineTo(N, And);
6086         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6087         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6088                         ISD::SIGN_EXTEND);
6089         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6090       }
6091     }
6092   }
6093
6094   if (N0.getOpcode() == ISD::SETCC) {
6095     EVT N0VT = N0.getOperand(0).getValueType();
6096     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6097     // Only do this before legalize for now.
6098     if (VT.isVector() && !LegalOperations &&
6099         TLI.getBooleanContents(N0VT) ==
6100             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6101       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6102       // of the same size as the compared operands. Only optimize sext(setcc())
6103       // if this is the case.
6104       EVT SVT = getSetCCResultType(N0VT);
6105
6106       // We know that the # elements of the results is the same as the
6107       // # elements of the compare (and the # elements of the compare result
6108       // for that matter).  Check to see that they are the same size.  If so,
6109       // we know that the element size of the sext'd result matches the
6110       // element size of the compare operands.
6111       if (VT.getSizeInBits() == SVT.getSizeInBits())
6112         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6113                              N0.getOperand(1),
6114                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6115
6116       // If the desired elements are smaller or larger than the source
6117       // elements we can use a matching integer vector type and then
6118       // truncate/sign extend
6119       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6120       if (SVT == MatchingVectorType) {
6121         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6122                                N0.getOperand(0), N0.getOperand(1),
6123                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6124         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6125       }
6126     }
6127
6128     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6129     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6130     SDLoc DL(N);
6131     SDValue NegOne =
6132       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6133     SDValue SCC =
6134       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6135                        NegOne, DAG.getConstant(0, DL, VT),
6136                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6137     if (SCC.getNode()) return SCC;
6138
6139     if (!VT.isVector()) {
6140       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6141       if (!LegalOperations ||
6142           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6143         SDLoc DL(N);
6144         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6145         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6146                                      N0.getOperand(0), N0.getOperand(1), CC);
6147         return DAG.getSelect(DL, VT, SetCC,
6148                              NegOne, DAG.getConstant(0, DL, VT));
6149       }
6150     }
6151   }
6152
6153   // fold (sext x) -> (zext x) if the sign bit is known zero.
6154   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6155       DAG.SignBitIsZero(N0))
6156     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6157
6158   return SDValue();
6159 }
6160
6161 // isTruncateOf - If N is a truncate of some other value, return true, record
6162 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6163 // This function computes KnownZero to avoid a duplicated call to
6164 // computeKnownBits in the caller.
6165 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6166                          APInt &KnownZero) {
6167   APInt KnownOne;
6168   if (N->getOpcode() == ISD::TRUNCATE) {
6169     Op = N->getOperand(0);
6170     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6171     return true;
6172   }
6173
6174   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6175       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6176     return false;
6177
6178   SDValue Op0 = N->getOperand(0);
6179   SDValue Op1 = N->getOperand(1);
6180   assert(Op0.getValueType() == Op1.getValueType());
6181
6182   if (isNullConstant(Op0))
6183     Op = Op1;
6184   else if (isNullConstant(Op1))
6185     Op = Op0;
6186   else
6187     return false;
6188
6189   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6190
6191   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6192     return false;
6193
6194   return true;
6195 }
6196
6197 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6198   SDValue N0 = N->getOperand(0);
6199   EVT VT = N->getValueType(0);
6200
6201   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6202                                               LegalOperations))
6203     return SDValue(Res, 0);
6204
6205   // fold (zext (zext x)) -> (zext x)
6206   // fold (zext (aext x)) -> (zext x)
6207   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6208     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6209                        N0.getOperand(0));
6210
6211   // fold (zext (truncate x)) -> (zext x) or
6212   //      (zext (truncate x)) -> (truncate x)
6213   // This is valid when the truncated bits of x are already zero.
6214   // FIXME: We should extend this to work for vectors too.
6215   SDValue Op;
6216   APInt KnownZero;
6217   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6218     APInt TruncatedBits =
6219       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6220       APInt(Op.getValueSizeInBits(), 0) :
6221       APInt::getBitsSet(Op.getValueSizeInBits(),
6222                         N0.getValueSizeInBits(),
6223                         std::min(Op.getValueSizeInBits(),
6224                                  VT.getSizeInBits()));
6225     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6226       if (VT.bitsGT(Op.getValueType()))
6227         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6228       if (VT.bitsLT(Op.getValueType()))
6229         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6230
6231       return Op;
6232     }
6233   }
6234
6235   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6236   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6237   if (N0.getOpcode() == ISD::TRUNCATE) {
6238     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6239       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6240       if (NarrowLoad.getNode() != N0.getNode()) {
6241         CombineTo(N0.getNode(), NarrowLoad);
6242         // CombineTo deleted the truncate, if needed, but not what's under it.
6243         AddToWorklist(oye);
6244       }
6245       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6246     }
6247   }
6248
6249   // fold (zext (truncate x)) -> (and x, mask)
6250   if (N0.getOpcode() == ISD::TRUNCATE) {
6251     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6252     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6253     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6254       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6255       if (NarrowLoad.getNode() != N0.getNode()) {
6256         CombineTo(N0.getNode(), NarrowLoad);
6257         // CombineTo deleted the truncate, if needed, but not what's under it.
6258         AddToWorklist(oye);
6259       }
6260       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6261     }
6262
6263     EVT SrcVT = N0.getOperand(0).getValueType();
6264     EVT MinVT = N0.getValueType();
6265
6266     // Try to mask before the extension to avoid having to generate a larger mask,
6267     // possibly over several sub-vectors.
6268     if (SrcVT.bitsLT(VT)) {
6269       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6270                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6271         SDValue Op = N0.getOperand(0);
6272         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6273         AddToWorklist(Op.getNode());
6274         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6275       }
6276     }
6277
6278     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6279       SDValue Op = N0.getOperand(0);
6280       if (SrcVT.bitsLT(VT)) {
6281         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6282         AddToWorklist(Op.getNode());
6283       } else if (SrcVT.bitsGT(VT)) {
6284         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6285         AddToWorklist(Op.getNode());
6286       }
6287       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6288     }
6289   }
6290
6291   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6292   // if either of the casts is not free.
6293   if (N0.getOpcode() == ISD::AND &&
6294       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6295       N0.getOperand(1).getOpcode() == ISD::Constant &&
6296       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6297                            N0.getValueType()) ||
6298        !TLI.isZExtFree(N0.getValueType(), VT))) {
6299     SDValue X = N0.getOperand(0).getOperand(0);
6300     if (X.getValueType().bitsLT(VT)) {
6301       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6302     } else if (X.getValueType().bitsGT(VT)) {
6303       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6304     }
6305     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6306     Mask = Mask.zext(VT.getSizeInBits());
6307     SDLoc DL(N);
6308     return DAG.getNode(ISD::AND, DL, VT,
6309                        X, DAG.getConstant(Mask, DL, VT));
6310   }
6311
6312   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6313   // Only generate vector extloads when 1) they're legal, and 2) they are
6314   // deemed desirable by the target.
6315   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6316       ((!LegalOperations && !VT.isVector() &&
6317         !cast<LoadSDNode>(N0)->isVolatile()) ||
6318        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6319     bool DoXform = true;
6320     SmallVector<SDNode*, 4> SetCCs;
6321     if (!N0.hasOneUse())
6322       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6323     if (VT.isVector())
6324       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6325     if (DoXform) {
6326       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6327       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6328                                        LN0->getChain(),
6329                                        LN0->getBasePtr(), N0.getValueType(),
6330                                        LN0->getMemOperand());
6331       CombineTo(N, ExtLoad);
6332       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6333                                   N0.getValueType(), ExtLoad);
6334       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6335
6336       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6337                       ISD::ZERO_EXTEND);
6338       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6339     }
6340   }
6341
6342   // fold (zext (load x)) to multiple smaller zextloads.
6343   // Only on illegal but splittable vectors.
6344   if (SDValue ExtLoad = CombineExtLoad(N))
6345     return ExtLoad;
6346
6347   // fold (zext (and/or/xor (load x), cst)) ->
6348   //      (and/or/xor (zextload x), (zext cst))
6349   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6350        N0.getOpcode() == ISD::XOR) &&
6351       isa<LoadSDNode>(N0.getOperand(0)) &&
6352       N0.getOperand(1).getOpcode() == ISD::Constant &&
6353       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6354       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6355     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6356     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6357       bool DoXform = true;
6358       SmallVector<SDNode*, 4> SetCCs;
6359       if (!N0.hasOneUse())
6360         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6361                                           SetCCs, TLI);
6362       if (DoXform) {
6363         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6364                                          LN0->getChain(), LN0->getBasePtr(),
6365                                          LN0->getMemoryVT(),
6366                                          LN0->getMemOperand());
6367         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6368         Mask = Mask.zext(VT.getSizeInBits());
6369         SDLoc DL(N);
6370         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6371                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6372         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6373                                     SDLoc(N0.getOperand(0)),
6374                                     N0.getOperand(0).getValueType(), ExtLoad);
6375         CombineTo(N, And);
6376         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6377         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6378                         ISD::ZERO_EXTEND);
6379         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6380       }
6381     }
6382   }
6383
6384   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6385   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6386   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6387       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6388     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6389     EVT MemVT = LN0->getMemoryVT();
6390     if ((!LegalOperations && !LN0->isVolatile()) ||
6391         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6392       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6393                                        LN0->getChain(),
6394                                        LN0->getBasePtr(), MemVT,
6395                                        LN0->getMemOperand());
6396       CombineTo(N, ExtLoad);
6397       CombineTo(N0.getNode(),
6398                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6399                             ExtLoad),
6400                 ExtLoad.getValue(1));
6401       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6402     }
6403   }
6404
6405   if (N0.getOpcode() == ISD::SETCC) {
6406     if (!LegalOperations && VT.isVector() &&
6407         N0.getValueType().getVectorElementType() == MVT::i1) {
6408       EVT N0VT = N0.getOperand(0).getValueType();
6409       if (getSetCCResultType(N0VT) == N0.getValueType())
6410         return SDValue();
6411
6412       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6413       // Only do this before legalize for now.
6414       EVT EltVT = VT.getVectorElementType();
6415       SDLoc DL(N);
6416       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6417                                     DAG.getConstant(1, DL, EltVT));
6418       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6419         // We know that the # elements of the results is the same as the
6420         // # elements of the compare (and the # elements of the compare result
6421         // for that matter).  Check to see that they are the same size.  If so,
6422         // we know that the element size of the sext'd result matches the
6423         // element size of the compare operands.
6424         return DAG.getNode(ISD::AND, DL, VT,
6425                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6426                                          N0.getOperand(1),
6427                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6428                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6429                                        OneOps));
6430
6431       // If the desired elements are smaller or larger than the source
6432       // elements we can use a matching integer vector type and then
6433       // truncate/sign extend
6434       EVT MatchingElementType =
6435         EVT::getIntegerVT(*DAG.getContext(),
6436                           N0VT.getScalarType().getSizeInBits());
6437       EVT MatchingVectorType =
6438         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6439                          N0VT.getVectorNumElements());
6440       SDValue VsetCC =
6441         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6442                       N0.getOperand(1),
6443                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6444       return DAG.getNode(ISD::AND, DL, VT,
6445                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6446                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6447     }
6448
6449     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6450     SDLoc DL(N);
6451     SDValue SCC =
6452       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6453                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6454                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6455     if (SCC.getNode()) return SCC;
6456   }
6457
6458   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6459   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6460       isa<ConstantSDNode>(N0.getOperand(1)) &&
6461       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6462       N0.hasOneUse()) {
6463     SDValue ShAmt = N0.getOperand(1);
6464     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6465     if (N0.getOpcode() == ISD::SHL) {
6466       SDValue InnerZExt = N0.getOperand(0);
6467       // If the original shl may be shifting out bits, do not perform this
6468       // transformation.
6469       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6470         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6471       if (ShAmtVal > KnownZeroBits)
6472         return SDValue();
6473     }
6474
6475     SDLoc DL(N);
6476
6477     // Ensure that the shift amount is wide enough for the shifted value.
6478     if (VT.getSizeInBits() >= 256)
6479       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6480
6481     return DAG.getNode(N0.getOpcode(), DL, VT,
6482                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6483                        ShAmt);
6484   }
6485
6486   return SDValue();
6487 }
6488
6489 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6490   SDValue N0 = N->getOperand(0);
6491   EVT VT = N->getValueType(0);
6492
6493   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6494                                               LegalOperations))
6495     return SDValue(Res, 0);
6496
6497   // fold (aext (aext x)) -> (aext x)
6498   // fold (aext (zext x)) -> (zext x)
6499   // fold (aext (sext x)) -> (sext x)
6500   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6501       N0.getOpcode() == ISD::ZERO_EXTEND ||
6502       N0.getOpcode() == ISD::SIGN_EXTEND)
6503     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6504
6505   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6506   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6507   if (N0.getOpcode() == ISD::TRUNCATE) {
6508     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6509       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6510       if (NarrowLoad.getNode() != N0.getNode()) {
6511         CombineTo(N0.getNode(), NarrowLoad);
6512         // CombineTo deleted the truncate, if needed, but not what's under it.
6513         AddToWorklist(oye);
6514       }
6515       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6516     }
6517   }
6518
6519   // fold (aext (truncate x))
6520   if (N0.getOpcode() == ISD::TRUNCATE) {
6521     SDValue TruncOp = N0.getOperand(0);
6522     if (TruncOp.getValueType() == VT)
6523       return TruncOp; // x iff x size == zext size.
6524     if (TruncOp.getValueType().bitsGT(VT))
6525       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6526     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6527   }
6528
6529   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6530   // if the trunc is not free.
6531   if (N0.getOpcode() == ISD::AND &&
6532       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6533       N0.getOperand(1).getOpcode() == ISD::Constant &&
6534       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6535                           N0.getValueType())) {
6536     SDValue X = N0.getOperand(0).getOperand(0);
6537     if (X.getValueType().bitsLT(VT)) {
6538       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6539     } else if (X.getValueType().bitsGT(VT)) {
6540       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6541     }
6542     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6543     Mask = Mask.zext(VT.getSizeInBits());
6544     SDLoc DL(N);
6545     return DAG.getNode(ISD::AND, DL, VT,
6546                        X, DAG.getConstant(Mask, DL, VT));
6547   }
6548
6549   // fold (aext (load x)) -> (aext (truncate (extload x)))
6550   // None of the supported targets knows how to perform load and any_ext
6551   // on vectors in one instruction.  We only perform this transformation on
6552   // scalars.
6553   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6554       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6555       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6556     bool DoXform = true;
6557     SmallVector<SDNode*, 4> SetCCs;
6558     if (!N0.hasOneUse())
6559       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6560     if (DoXform) {
6561       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6562       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6563                                        LN0->getChain(),
6564                                        LN0->getBasePtr(), N0.getValueType(),
6565                                        LN0->getMemOperand());
6566       CombineTo(N, ExtLoad);
6567       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6568                                   N0.getValueType(), ExtLoad);
6569       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6570       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6571                       ISD::ANY_EXTEND);
6572       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6573     }
6574   }
6575
6576   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6577   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6578   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6579   if (N0.getOpcode() == ISD::LOAD &&
6580       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6581       N0.hasOneUse()) {
6582     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6583     ISD::LoadExtType ExtType = LN0->getExtensionType();
6584     EVT MemVT = LN0->getMemoryVT();
6585     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6586       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6587                                        VT, LN0->getChain(), LN0->getBasePtr(),
6588                                        MemVT, LN0->getMemOperand());
6589       CombineTo(N, ExtLoad);
6590       CombineTo(N0.getNode(),
6591                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6592                             N0.getValueType(), ExtLoad),
6593                 ExtLoad.getValue(1));
6594       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6595     }
6596   }
6597
6598   if (N0.getOpcode() == ISD::SETCC) {
6599     // For vectors:
6600     // aext(setcc) -> vsetcc
6601     // aext(setcc) -> truncate(vsetcc)
6602     // aext(setcc) -> aext(vsetcc)
6603     // Only do this before legalize for now.
6604     if (VT.isVector() && !LegalOperations) {
6605       EVT N0VT = N0.getOperand(0).getValueType();
6606         // We know that the # elements of the results is the same as the
6607         // # elements of the compare (and the # elements of the compare result
6608         // for that matter).  Check to see that they are the same size.  If so,
6609         // we know that the element size of the sext'd result matches the
6610         // element size of the compare operands.
6611       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6612         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6613                              N0.getOperand(1),
6614                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6615       // If the desired elements are smaller or larger than the source
6616       // elements we can use a matching integer vector type and then
6617       // truncate/any extend
6618       else {
6619         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6620         SDValue VsetCC =
6621           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6622                         N0.getOperand(1),
6623                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6624         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6625       }
6626     }
6627
6628     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6629     SDLoc DL(N);
6630     SDValue SCC =
6631       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6632                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6633                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6634     if (SCC.getNode())
6635       return SCC;
6636   }
6637
6638   return SDValue();
6639 }
6640
6641 /// See if the specified operand can be simplified with the knowledge that only
6642 /// the bits specified by Mask are used.  If so, return the simpler operand,
6643 /// otherwise return a null SDValue.
6644 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6645   switch (V.getOpcode()) {
6646   default: break;
6647   case ISD::Constant: {
6648     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6649     assert(CV && "Const value should be ConstSDNode.");
6650     const APInt &CVal = CV->getAPIntValue();
6651     APInt NewVal = CVal & Mask;
6652     if (NewVal != CVal)
6653       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6654     break;
6655   }
6656   case ISD::OR:
6657   case ISD::XOR:
6658     // If the LHS or RHS don't contribute bits to the or, drop them.
6659     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6660       return V.getOperand(1);
6661     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6662       return V.getOperand(0);
6663     break;
6664   case ISD::SRL:
6665     // Only look at single-use SRLs.
6666     if (!V.getNode()->hasOneUse())
6667       break;
6668     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6669       // See if we can recursively simplify the LHS.
6670       unsigned Amt = RHSC->getZExtValue();
6671
6672       // Watch out for shift count overflow though.
6673       if (Amt >= Mask.getBitWidth()) break;
6674       APInt NewMask = Mask << Amt;
6675       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6676         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6677                            SimplifyLHS, V.getOperand(1));
6678     }
6679   }
6680   return SDValue();
6681 }
6682
6683 /// If the result of a wider load is shifted to right of N  bits and then
6684 /// truncated to a narrower type and where N is a multiple of number of bits of
6685 /// the narrower type, transform it to a narrower load from address + N / num of
6686 /// bits of new type. If the result is to be extended, also fold the extension
6687 /// to form a extending load.
6688 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6689   unsigned Opc = N->getOpcode();
6690
6691   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6692   SDValue N0 = N->getOperand(0);
6693   EVT VT = N->getValueType(0);
6694   EVT ExtVT = VT;
6695
6696   // This transformation isn't valid for vector loads.
6697   if (VT.isVector())
6698     return SDValue();
6699
6700   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6701   // extended to VT.
6702   if (Opc == ISD::SIGN_EXTEND_INREG) {
6703     ExtType = ISD::SEXTLOAD;
6704     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6705   } else if (Opc == ISD::SRL) {
6706     // Another special-case: SRL is basically zero-extending a narrower value.
6707     ExtType = ISD::ZEXTLOAD;
6708     N0 = SDValue(N, 0);
6709     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6710     if (!N01) return SDValue();
6711     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6712                               VT.getSizeInBits() - N01->getZExtValue());
6713   }
6714   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6715     return SDValue();
6716
6717   unsigned EVTBits = ExtVT.getSizeInBits();
6718
6719   // Do not generate loads of non-round integer types since these can
6720   // be expensive (and would be wrong if the type is not byte sized).
6721   if (!ExtVT.isRound())
6722     return SDValue();
6723
6724   unsigned ShAmt = 0;
6725   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6726     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6727       ShAmt = N01->getZExtValue();
6728       // Is the shift amount a multiple of size of VT?
6729       if ((ShAmt & (EVTBits-1)) == 0) {
6730         N0 = N0.getOperand(0);
6731         // Is the load width a multiple of size of VT?
6732         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6733           return SDValue();
6734       }
6735
6736       // At this point, we must have a load or else we can't do the transform.
6737       if (!isa<LoadSDNode>(N0)) return SDValue();
6738
6739       // Because a SRL must be assumed to *need* to zero-extend the high bits
6740       // (as opposed to anyext the high bits), we can't combine the zextload
6741       // lowering of SRL and an sextload.
6742       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6743         return SDValue();
6744
6745       // If the shift amount is larger than the input type then we're not
6746       // accessing any of the loaded bytes.  If the load was a zextload/extload
6747       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6748       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6749         return SDValue();
6750     }
6751   }
6752
6753   // If the load is shifted left (and the result isn't shifted back right),
6754   // we can fold the truncate through the shift.
6755   unsigned ShLeftAmt = 0;
6756   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6757       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6758     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6759       ShLeftAmt = N01->getZExtValue();
6760       N0 = N0.getOperand(0);
6761     }
6762   }
6763
6764   // If we haven't found a load, we can't narrow it.  Don't transform one with
6765   // multiple uses, this would require adding a new load.
6766   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6767     return SDValue();
6768
6769   // Don't change the width of a volatile load.
6770   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6771   if (LN0->isVolatile())
6772     return SDValue();
6773
6774   // Verify that we are actually reducing a load width here.
6775   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6776     return SDValue();
6777
6778   // For the transform to be legal, the load must produce only two values
6779   // (the value loaded and the chain).  Don't transform a pre-increment
6780   // load, for example, which produces an extra value.  Otherwise the
6781   // transformation is not equivalent, and the downstream logic to replace
6782   // uses gets things wrong.
6783   if (LN0->getNumValues() > 2)
6784     return SDValue();
6785
6786   // If the load that we're shrinking is an extload and we're not just
6787   // discarding the extension we can't simply shrink the load. Bail.
6788   // TODO: It would be possible to merge the extensions in some cases.
6789   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6790       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6791     return SDValue();
6792
6793   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6794     return SDValue();
6795
6796   EVT PtrType = N0.getOperand(1).getValueType();
6797
6798   if (PtrType == MVT::Untyped || PtrType.isExtended())
6799     // It's not possible to generate a constant of extended or untyped type.
6800     return SDValue();
6801
6802   // For big endian targets, we need to adjust the offset to the pointer to
6803   // load the correct bytes.
6804   if (DAG.getDataLayout().isBigEndian()) {
6805     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6806     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6807     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6808   }
6809
6810   uint64_t PtrOff = ShAmt / 8;
6811   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6812   SDLoc DL(LN0);
6813   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6814                                PtrType, LN0->getBasePtr(),
6815                                DAG.getConstant(PtrOff, DL, PtrType));
6816   AddToWorklist(NewPtr.getNode());
6817
6818   SDValue Load;
6819   if (ExtType == ISD::NON_EXTLOAD)
6820     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6821                         LN0->getPointerInfo().getWithOffset(PtrOff),
6822                         LN0->isVolatile(), LN0->isNonTemporal(),
6823                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6824   else
6825     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6826                           LN0->getPointerInfo().getWithOffset(PtrOff),
6827                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6828                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6829
6830   // Replace the old load's chain with the new load's chain.
6831   WorklistRemover DeadNodes(*this);
6832   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6833
6834   // Shift the result left, if we've swallowed a left shift.
6835   SDValue Result = Load;
6836   if (ShLeftAmt != 0) {
6837     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6838     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6839       ShImmTy = VT;
6840     // If the shift amount is as large as the result size (but, presumably,
6841     // no larger than the source) then the useful bits of the result are
6842     // zero; we can't simply return the shortened shift, because the result
6843     // of that operation is undefined.
6844     SDLoc DL(N0);
6845     if (ShLeftAmt >= VT.getSizeInBits())
6846       Result = DAG.getConstant(0, DL, VT);
6847     else
6848       Result = DAG.getNode(ISD::SHL, DL, VT,
6849                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6850   }
6851
6852   // Return the new loaded value.
6853   return Result;
6854 }
6855
6856 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6857   SDValue N0 = N->getOperand(0);
6858   SDValue N1 = N->getOperand(1);
6859   EVT VT = N->getValueType(0);
6860   EVT EVT = cast<VTSDNode>(N1)->getVT();
6861   unsigned VTBits = VT.getScalarType().getSizeInBits();
6862   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6863
6864   if (N0.isUndef())
6865     return DAG.getUNDEF(VT);
6866
6867   // fold (sext_in_reg c1) -> c1
6868   if (isConstantIntBuildVectorOrConstantInt(N0))
6869     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6870
6871   // If the input is already sign extended, just drop the extension.
6872   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6873     return N0;
6874
6875   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6876   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6877       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6878     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6879                        N0.getOperand(0), N1);
6880
6881   // fold (sext_in_reg (sext x)) -> (sext x)
6882   // fold (sext_in_reg (aext x)) -> (sext x)
6883   // if x is small enough.
6884   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6885     SDValue N00 = N0.getOperand(0);
6886     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6887         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6888       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6889   }
6890
6891   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6892   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6893     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6894
6895   // fold operands of sext_in_reg based on knowledge that the top bits are not
6896   // demanded.
6897   if (SimplifyDemandedBits(SDValue(N, 0)))
6898     return SDValue(N, 0);
6899
6900   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6901   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6902   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6903     return NarrowLoad;
6904
6905   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6906   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6907   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6908   if (N0.getOpcode() == ISD::SRL) {
6909     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6910       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6911         // We can turn this into an SRA iff the input to the SRL is already sign
6912         // extended enough.
6913         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6914         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6915           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6916                              N0.getOperand(0), N0.getOperand(1));
6917       }
6918   }
6919
6920   // fold (sext_inreg (extload x)) -> (sextload x)
6921   if (ISD::isEXTLoad(N0.getNode()) &&
6922       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6923       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6924       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6925        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6926     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6927     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6928                                      LN0->getChain(),
6929                                      LN0->getBasePtr(), EVT,
6930                                      LN0->getMemOperand());
6931     CombineTo(N, ExtLoad);
6932     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6933     AddToWorklist(ExtLoad.getNode());
6934     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6935   }
6936   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6937   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6938       N0.hasOneUse() &&
6939       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6940       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6941        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6942     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6943     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6944                                      LN0->getChain(),
6945                                      LN0->getBasePtr(), EVT,
6946                                      LN0->getMemOperand());
6947     CombineTo(N, ExtLoad);
6948     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6949     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6950   }
6951
6952   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6953   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6954     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6955                                        N0.getOperand(1), false);
6956     if (BSwap.getNode())
6957       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6958                          BSwap, N1);
6959   }
6960
6961   return SDValue();
6962 }
6963
6964 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6965   SDValue N0 = N->getOperand(0);
6966   EVT VT = N->getValueType(0);
6967
6968   if (N0.getOpcode() == ISD::UNDEF)
6969     return DAG.getUNDEF(VT);
6970
6971   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6972                                               LegalOperations))
6973     return SDValue(Res, 0);
6974
6975   return SDValue();
6976 }
6977
6978 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6979   SDValue N0 = N->getOperand(0);
6980   EVT VT = N->getValueType(0);
6981   bool isLE = DAG.getDataLayout().isLittleEndian();
6982
6983   // noop truncate
6984   if (N0.getValueType() == N->getValueType(0))
6985     return N0;
6986   // fold (truncate c1) -> c1
6987   if (isConstantIntBuildVectorOrConstantInt(N0))
6988     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6989   // fold (truncate (truncate x)) -> (truncate x)
6990   if (N0.getOpcode() == ISD::TRUNCATE)
6991     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6992   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6993   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6994       N0.getOpcode() == ISD::SIGN_EXTEND ||
6995       N0.getOpcode() == ISD::ANY_EXTEND) {
6996     if (N0.getOperand(0).getValueType().bitsLT(VT))
6997       // if the source is smaller than the dest, we still need an extend
6998       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6999                          N0.getOperand(0));
7000     if (N0.getOperand(0).getValueType().bitsGT(VT))
7001       // if the source is larger than the dest, than we just need the truncate
7002       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
7003     // if the source and dest are the same type, we can drop both the extend
7004     // and the truncate.
7005     return N0.getOperand(0);
7006   }
7007
7008   // Fold extract-and-trunc into a narrow extract. For example:
7009   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
7010   //   i32 y = TRUNCATE(i64 x)
7011   //        -- becomes --
7012   //   v16i8 b = BITCAST (v2i64 val)
7013   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
7014   //
7015   // Note: We only run this optimization after type legalization (which often
7016   // creates this pattern) and before operation legalization after which
7017   // we need to be more careful about the vector instructions that we generate.
7018   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7019       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
7020
7021     EVT VecTy = N0.getOperand(0).getValueType();
7022     EVT ExTy = N0.getValueType();
7023     EVT TrTy = N->getValueType(0);
7024
7025     unsigned NumElem = VecTy.getVectorNumElements();
7026     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
7027
7028     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
7029     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7030
7031     SDValue EltNo = N0->getOperand(1);
7032     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7033       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7034       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7035       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7036
7037       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7038                               NVT, N0.getOperand(0));
7039
7040       SDLoc DL(N);
7041       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7042                          DL, TrTy, V,
7043                          DAG.getConstant(Index, DL, IndexTy));
7044     }
7045   }
7046
7047   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7048   if (N0.getOpcode() == ISD::SELECT) {
7049     EVT SrcVT = N0.getValueType();
7050     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7051         TLI.isTruncateFree(SrcVT, VT)) {
7052       SDLoc SL(N0);
7053       SDValue Cond = N0.getOperand(0);
7054       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7055       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7056       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7057     }
7058   }
7059
7060   // Fold a series of buildvector, bitcast, and truncate if possible.
7061   // For example fold
7062   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7063   //   (2xi32 (buildvector x, y)).
7064   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7065       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7066       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7067       N0.getOperand(0).hasOneUse()) {
7068
7069     SDValue BuildVect = N0.getOperand(0);
7070     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7071     EVT TruncVecEltTy = VT.getVectorElementType();
7072
7073     // Check that the element types match.
7074     if (BuildVectEltTy == TruncVecEltTy) {
7075       // Now we only need to compute the offset of the truncated elements.
7076       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7077       unsigned TruncVecNumElts = VT.getVectorNumElements();
7078       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7079
7080       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7081              "Invalid number of elements");
7082
7083       SmallVector<SDValue, 8> Opnds;
7084       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7085         Opnds.push_back(BuildVect.getOperand(i));
7086
7087       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7088     }
7089   }
7090
7091   // See if we can simplify the input to this truncate through knowledge that
7092   // only the low bits are being used.
7093   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7094   // Currently we only perform this optimization on scalars because vectors
7095   // may have different active low bits.
7096   if (!VT.isVector()) {
7097     SDValue Shorter =
7098       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7099                                                VT.getSizeInBits()));
7100     if (Shorter.getNode())
7101       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7102   }
7103   // fold (truncate (load x)) -> (smaller load x)
7104   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7105   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7106     if (SDValue Reduced = ReduceLoadWidth(N))
7107       return Reduced;
7108
7109     // Handle the case where the load remains an extending load even
7110     // after truncation.
7111     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7112       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7113       if (!LN0->isVolatile() &&
7114           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7115         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7116                                          VT, LN0->getChain(), LN0->getBasePtr(),
7117                                          LN0->getMemoryVT(),
7118                                          LN0->getMemOperand());
7119         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7120         return NewLoad;
7121       }
7122     }
7123   }
7124   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7125   // where ... are all 'undef'.
7126   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7127     SmallVector<EVT, 8> VTs;
7128     SDValue V;
7129     unsigned Idx = 0;
7130     unsigned NumDefs = 0;
7131
7132     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7133       SDValue X = N0.getOperand(i);
7134       if (X.getOpcode() != ISD::UNDEF) {
7135         V = X;
7136         Idx = i;
7137         NumDefs++;
7138       }
7139       // Stop if more than one members are non-undef.
7140       if (NumDefs > 1)
7141         break;
7142       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7143                                      VT.getVectorElementType(),
7144                                      X.getValueType().getVectorNumElements()));
7145     }
7146
7147     if (NumDefs == 0)
7148       return DAG.getUNDEF(VT);
7149
7150     if (NumDefs == 1) {
7151       assert(V.getNode() && "The single defined operand is empty!");
7152       SmallVector<SDValue, 8> Opnds;
7153       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7154         if (i != Idx) {
7155           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7156           continue;
7157         }
7158         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7159         AddToWorklist(NV.getNode());
7160         Opnds.push_back(NV);
7161       }
7162       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7163     }
7164   }
7165
7166   // Simplify the operands using demanded-bits information.
7167   if (!VT.isVector() &&
7168       SimplifyDemandedBits(SDValue(N, 0)))
7169     return SDValue(N, 0);
7170
7171   return SDValue();
7172 }
7173
7174 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7175   SDValue Elt = N->getOperand(i);
7176   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7177     return Elt.getNode();
7178   return Elt.getOperand(Elt.getResNo()).getNode();
7179 }
7180
7181 /// build_pair (load, load) -> load
7182 /// if load locations are consecutive.
7183 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7184   assert(N->getOpcode() == ISD::BUILD_PAIR);
7185
7186   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7187   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7188   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7189       LD1->getAddressSpace() != LD2->getAddressSpace())
7190     return SDValue();
7191   EVT LD1VT = LD1->getValueType(0);
7192
7193   if (ISD::isNON_EXTLoad(LD2) &&
7194       LD2->hasOneUse() &&
7195       // If both are volatile this would reduce the number of volatile loads.
7196       // If one is volatile it might be ok, but play conservative and bail out.
7197       !LD1->isVolatile() &&
7198       !LD2->isVolatile() &&
7199       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7200     unsigned Align = LD1->getAlignment();
7201     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7202         VT.getTypeForEVT(*DAG.getContext()));
7203
7204     if (NewAlign <= Align &&
7205         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7206       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7207                          LD1->getBasePtr(), LD1->getPointerInfo(),
7208                          false, false, false, Align);
7209   }
7210
7211   return SDValue();
7212 }
7213
7214 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7215   SDValue N0 = N->getOperand(0);
7216   EVT VT = N->getValueType(0);
7217
7218   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7219   // Only do this before legalize, since afterward the target may be depending
7220   // on the bitconvert.
7221   // First check to see if this is all constant.
7222   if (!LegalTypes &&
7223       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7224       VT.isVector()) {
7225     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7226
7227     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7228     assert(!DestEltVT.isVector() &&
7229            "Element type of vector ValueType must not be vector!");
7230     if (isSimple)
7231       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7232   }
7233
7234   // If the input is a constant, let getNode fold it.
7235   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7236     // If we can't allow illegal operations, we need to check that this is just
7237     // a fp -> int or int -> conversion and that the resulting operation will
7238     // be legal.
7239     if (!LegalOperations ||
7240         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7241          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7242         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7243          TLI.isOperationLegal(ISD::Constant, VT)))
7244       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7245   }
7246
7247   // (conv (conv x, t1), t2) -> (conv x, t2)
7248   if (N0.getOpcode() == ISD::BITCAST)
7249     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7250                        N0.getOperand(0));
7251
7252   // fold (conv (load x)) -> (load (conv*)x)
7253   // If the resultant load doesn't need a higher alignment than the original!
7254   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7255       // Do not change the width of a volatile load.
7256       !cast<LoadSDNode>(N0)->isVolatile() &&
7257       // Do not remove the cast if the types differ in endian layout.
7258       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7259           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7260       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7261       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7262     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7263     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7264         VT.getTypeForEVT(*DAG.getContext()));
7265     unsigned OrigAlign = LN0->getAlignment();
7266
7267     if (Align <= OrigAlign) {
7268       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7269                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7270                                  LN0->isVolatile(), LN0->isNonTemporal(),
7271                                  LN0->isInvariant(), OrigAlign,
7272                                  LN0->getAAInfo());
7273       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7274       return Load;
7275     }
7276   }
7277
7278   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7279   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7280   // This often reduces constant pool loads.
7281   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7282        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7283       N0.getNode()->hasOneUse() && VT.isInteger() &&
7284       !VT.isVector() && !N0.getValueType().isVector()) {
7285     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7286                                   N0.getOperand(0));
7287     AddToWorklist(NewConv.getNode());
7288
7289     SDLoc DL(N);
7290     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7291     if (N0.getOpcode() == ISD::FNEG)
7292       return DAG.getNode(ISD::XOR, DL, VT,
7293                          NewConv, DAG.getConstant(SignBit, DL, VT));
7294     assert(N0.getOpcode() == ISD::FABS);
7295     return DAG.getNode(ISD::AND, DL, VT,
7296                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7297   }
7298
7299   // fold (bitconvert (fcopysign cst, x)) ->
7300   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7301   // Note that we don't handle (copysign x, cst) because this can always be
7302   // folded to an fneg or fabs.
7303   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7304       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7305       VT.isInteger() && !VT.isVector()) {
7306     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7307     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7308     if (isTypeLegal(IntXVT)) {
7309       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7310                               IntXVT, N0.getOperand(1));
7311       AddToWorklist(X.getNode());
7312
7313       // If X has a different width than the result/lhs, sext it or truncate it.
7314       unsigned VTWidth = VT.getSizeInBits();
7315       if (OrigXWidth < VTWidth) {
7316         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7317         AddToWorklist(X.getNode());
7318       } else if (OrigXWidth > VTWidth) {
7319         // To get the sign bit in the right place, we have to shift it right
7320         // before truncating.
7321         SDLoc DL(X);
7322         X = DAG.getNode(ISD::SRL, DL,
7323                         X.getValueType(), X,
7324                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7325                                         X.getValueType()));
7326         AddToWorklist(X.getNode());
7327         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7328         AddToWorklist(X.getNode());
7329       }
7330
7331       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7332       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7333                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7334       AddToWorklist(X.getNode());
7335
7336       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7337                                 VT, N0.getOperand(0));
7338       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7339                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7340       AddToWorklist(Cst.getNode());
7341
7342       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7343     }
7344   }
7345
7346   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7347   if (N0.getOpcode() == ISD::BUILD_PAIR)
7348     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7349       return CombineLD;
7350
7351   // Remove double bitcasts from shuffles - this is often a legacy of
7352   // XformToShuffleWithZero being used to combine bitmaskings (of
7353   // float vectors bitcast to integer vectors) into shuffles.
7354   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7355   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7356       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7357       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7358       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7359     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7360
7361     // If operands are a bitcast, peek through if it casts the original VT.
7362     // If operands are a constant, just bitcast back to original VT.
7363     auto PeekThroughBitcast = [&](SDValue Op) {
7364       if (Op.getOpcode() == ISD::BITCAST &&
7365           Op.getOperand(0).getValueType() == VT)
7366         return SDValue(Op.getOperand(0));
7367       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7368           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7369         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7370       return SDValue();
7371     };
7372
7373     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7374     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7375     if (!(SV0 && SV1))
7376       return SDValue();
7377
7378     int MaskScale =
7379         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7380     SmallVector<int, 8> NewMask;
7381     for (int M : SVN->getMask())
7382       for (int i = 0; i != MaskScale; ++i)
7383         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7384
7385     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7386     if (!LegalMask) {
7387       std::swap(SV0, SV1);
7388       ShuffleVectorSDNode::commuteMask(NewMask);
7389       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7390     }
7391
7392     if (LegalMask)
7393       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7394   }
7395
7396   return SDValue();
7397 }
7398
7399 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7400   EVT VT = N->getValueType(0);
7401   return CombineConsecutiveLoads(N, VT);
7402 }
7403
7404 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7405 /// operands. DstEltVT indicates the destination element value type.
7406 SDValue DAGCombiner::
7407 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7408   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7409
7410   // If this is already the right type, we're done.
7411   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7412
7413   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7414   unsigned DstBitSize = DstEltVT.getSizeInBits();
7415
7416   // If this is a conversion of N elements of one type to N elements of another
7417   // type, convert each element.  This handles FP<->INT cases.
7418   if (SrcBitSize == DstBitSize) {
7419     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7420                               BV->getValueType(0).getVectorNumElements());
7421
7422     // Due to the FP element handling below calling this routine recursively,
7423     // we can end up with a scalar-to-vector node here.
7424     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7425       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7426                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7427                                      DstEltVT, BV->getOperand(0)));
7428
7429     SmallVector<SDValue, 8> Ops;
7430     for (SDValue Op : BV->op_values()) {
7431       // If the vector element type is not legal, the BUILD_VECTOR operands
7432       // are promoted and implicitly truncated.  Make that explicit here.
7433       if (Op.getValueType() != SrcEltVT)
7434         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7435       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7436                                 DstEltVT, Op));
7437       AddToWorklist(Ops.back().getNode());
7438     }
7439     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7440   }
7441
7442   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7443   // handle annoying details of growing/shrinking FP values, we convert them to
7444   // int first.
7445   if (SrcEltVT.isFloatingPoint()) {
7446     // Convert the input float vector to a int vector where the elements are the
7447     // same sizes.
7448     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7449     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7450     SrcEltVT = IntVT;
7451   }
7452
7453   // Now we know the input is an integer vector.  If the output is a FP type,
7454   // convert to integer first, then to FP of the right size.
7455   if (DstEltVT.isFloatingPoint()) {
7456     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7457     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7458
7459     // Next, convert to FP elements of the same size.
7460     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7461   }
7462
7463   SDLoc DL(BV);
7464
7465   // Okay, we know the src/dst types are both integers of differing types.
7466   // Handling growing first.
7467   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7468   if (SrcBitSize < DstBitSize) {
7469     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7470
7471     SmallVector<SDValue, 8> Ops;
7472     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7473          i += NumInputsPerOutput) {
7474       bool isLE = DAG.getDataLayout().isLittleEndian();
7475       APInt NewBits = APInt(DstBitSize, 0);
7476       bool EltIsUndef = true;
7477       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7478         // Shift the previously computed bits over.
7479         NewBits <<= SrcBitSize;
7480         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7481         if (Op.getOpcode() == ISD::UNDEF) continue;
7482         EltIsUndef = false;
7483
7484         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7485                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7486       }
7487
7488       if (EltIsUndef)
7489         Ops.push_back(DAG.getUNDEF(DstEltVT));
7490       else
7491         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7492     }
7493
7494     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7495     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7496   }
7497
7498   // Finally, this must be the case where we are shrinking elements: each input
7499   // turns into multiple outputs.
7500   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7501   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7502                             NumOutputsPerInput*BV->getNumOperands());
7503   SmallVector<SDValue, 8> Ops;
7504
7505   for (const SDValue &Op : BV->op_values()) {
7506     if (Op.getOpcode() == ISD::UNDEF) {
7507       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7508       continue;
7509     }
7510
7511     APInt OpVal = cast<ConstantSDNode>(Op)->
7512                   getAPIntValue().zextOrTrunc(SrcBitSize);
7513
7514     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7515       APInt ThisVal = OpVal.trunc(DstBitSize);
7516       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7517       OpVal = OpVal.lshr(DstBitSize);
7518     }
7519
7520     // For big endian targets, swap the order of the pieces of each element.
7521     if (DAG.getDataLayout().isBigEndian())
7522       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7523   }
7524
7525   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7526 }
7527
7528 /// Try to perform FMA combining on a given FADD node.
7529 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7530   SDValue N0 = N->getOperand(0);
7531   SDValue N1 = N->getOperand(1);
7532   EVT VT = N->getValueType(0);
7533   SDLoc SL(N);
7534
7535   const TargetOptions &Options = DAG.getTarget().Options;
7536   bool AllowFusion =
7537       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7538
7539   // Floating-point multiply-add with intermediate rounding.
7540   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7541
7542   // Floating-point multiply-add without intermediate rounding.
7543   bool HasFMA =
7544       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7545       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7546
7547   // No valid opcode, do not combine.
7548   if (!HasFMAD && !HasFMA)
7549     return SDValue();
7550
7551   // Always prefer FMAD to FMA for precision.
7552   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7553   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7554   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7555
7556   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7557   // prefer to fold the multiply with fewer uses.
7558   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7559       N1.getOpcode() == ISD::FMUL) {
7560     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7561       std::swap(N0, N1);
7562   }
7563
7564   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7565   if (N0.getOpcode() == ISD::FMUL &&
7566       (Aggressive || N0->hasOneUse())) {
7567     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7568                        N0.getOperand(0), N0.getOperand(1), N1);
7569   }
7570
7571   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7572   // Note: Commutes FADD operands.
7573   if (N1.getOpcode() == ISD::FMUL &&
7574       (Aggressive || N1->hasOneUse())) {
7575     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7576                        N1.getOperand(0), N1.getOperand(1), N0);
7577   }
7578
7579   // Look through FP_EXTEND nodes to do more combining.
7580   if (AllowFusion && LookThroughFPExt) {
7581     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7582     if (N0.getOpcode() == ISD::FP_EXTEND) {
7583       SDValue N00 = N0.getOperand(0);
7584       if (N00.getOpcode() == ISD::FMUL)
7585         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7586                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7587                                        N00.getOperand(0)),
7588                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589                                        N00.getOperand(1)), N1);
7590     }
7591
7592     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7593     // Note: Commutes FADD operands.
7594     if (N1.getOpcode() == ISD::FP_EXTEND) {
7595       SDValue N10 = N1.getOperand(0);
7596       if (N10.getOpcode() == ISD::FMUL)
7597         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7598                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7599                                        N10.getOperand(0)),
7600                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7601                                        N10.getOperand(1)), N0);
7602     }
7603   }
7604
7605   // More folding opportunities when target permits.
7606   if ((AllowFusion || HasFMAD)  && Aggressive) {
7607     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7608     if (N0.getOpcode() == PreferredFusedOpcode &&
7609         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7610       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7611                          N0.getOperand(0), N0.getOperand(1),
7612                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7613                                      N0.getOperand(2).getOperand(0),
7614                                      N0.getOperand(2).getOperand(1),
7615                                      N1));
7616     }
7617
7618     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7619     if (N1->getOpcode() == PreferredFusedOpcode &&
7620         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7621       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7622                          N1.getOperand(0), N1.getOperand(1),
7623                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7624                                      N1.getOperand(2).getOperand(0),
7625                                      N1.getOperand(2).getOperand(1),
7626                                      N0));
7627     }
7628
7629     if (AllowFusion && LookThroughFPExt) {
7630       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7631       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7632       auto FoldFAddFMAFPExtFMul = [&] (
7633           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7634         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7635                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7636                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7637                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7638                                        Z));
7639       };
7640       if (N0.getOpcode() == PreferredFusedOpcode) {
7641         SDValue N02 = N0.getOperand(2);
7642         if (N02.getOpcode() == ISD::FP_EXTEND) {
7643           SDValue N020 = N02.getOperand(0);
7644           if (N020.getOpcode() == ISD::FMUL)
7645             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7646                                         N020.getOperand(0), N020.getOperand(1),
7647                                         N1);
7648         }
7649       }
7650
7651       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7652       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7653       // FIXME: This turns two single-precision and one double-precision
7654       // operation into two double-precision operations, which might not be
7655       // interesting for all targets, especially GPUs.
7656       auto FoldFAddFPExtFMAFMul = [&] (
7657           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7658         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7659                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7660                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7661                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7662                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7663                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7664                                        Z));
7665       };
7666       if (N0.getOpcode() == ISD::FP_EXTEND) {
7667         SDValue N00 = N0.getOperand(0);
7668         if (N00.getOpcode() == PreferredFusedOpcode) {
7669           SDValue N002 = N00.getOperand(2);
7670           if (N002.getOpcode() == ISD::FMUL)
7671             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7672                                         N002.getOperand(0), N002.getOperand(1),
7673                                         N1);
7674         }
7675       }
7676
7677       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7678       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7679       if (N1.getOpcode() == PreferredFusedOpcode) {
7680         SDValue N12 = N1.getOperand(2);
7681         if (N12.getOpcode() == ISD::FP_EXTEND) {
7682           SDValue N120 = N12.getOperand(0);
7683           if (N120.getOpcode() == ISD::FMUL)
7684             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7685                                         N120.getOperand(0), N120.getOperand(1),
7686                                         N0);
7687         }
7688       }
7689
7690       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7691       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7692       // FIXME: This turns two single-precision and one double-precision
7693       // operation into two double-precision operations, which might not be
7694       // interesting for all targets, especially GPUs.
7695       if (N1.getOpcode() == ISD::FP_EXTEND) {
7696         SDValue N10 = N1.getOperand(0);
7697         if (N10.getOpcode() == PreferredFusedOpcode) {
7698           SDValue N102 = N10.getOperand(2);
7699           if (N102.getOpcode() == ISD::FMUL)
7700             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7701                                         N102.getOperand(0), N102.getOperand(1),
7702                                         N0);
7703         }
7704       }
7705     }
7706   }
7707
7708   return SDValue();
7709 }
7710
7711 /// Try to perform FMA combining on a given FSUB node.
7712 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7713   SDValue N0 = N->getOperand(0);
7714   SDValue N1 = N->getOperand(1);
7715   EVT VT = N->getValueType(0);
7716   SDLoc SL(N);
7717
7718   const TargetOptions &Options = DAG.getTarget().Options;
7719   bool AllowFusion =
7720       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7721
7722   // Floating-point multiply-add with intermediate rounding.
7723   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7724
7725   // Floating-point multiply-add without intermediate rounding.
7726   bool HasFMA =
7727       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7728       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7729
7730   // No valid opcode, do not combine.
7731   if (!HasFMAD && !HasFMA)
7732     return SDValue();
7733
7734   // Always prefer FMAD to FMA for precision.
7735   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7736   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7737   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7738
7739   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7740   if (N0.getOpcode() == ISD::FMUL &&
7741       (Aggressive || N0->hasOneUse())) {
7742     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743                        N0.getOperand(0), N0.getOperand(1),
7744                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7745   }
7746
7747   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7748   // Note: Commutes FSUB operands.
7749   if (N1.getOpcode() == ISD::FMUL &&
7750       (Aggressive || N1->hasOneUse()))
7751     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7752                        DAG.getNode(ISD::FNEG, SL, VT,
7753                                    N1.getOperand(0)),
7754                        N1.getOperand(1), N0);
7755
7756   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7757   if (N0.getOpcode() == ISD::FNEG &&
7758       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7759       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7760     SDValue N00 = N0.getOperand(0).getOperand(0);
7761     SDValue N01 = N0.getOperand(0).getOperand(1);
7762     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7764                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7765   }
7766
7767   // Look through FP_EXTEND nodes to do more combining.
7768   if (AllowFusion && LookThroughFPExt) {
7769     // fold (fsub (fpext (fmul x, y)), z)
7770     //   -> (fma (fpext x), (fpext y), (fneg z))
7771     if (N0.getOpcode() == ISD::FP_EXTEND) {
7772       SDValue N00 = N0.getOperand(0);
7773       if (N00.getOpcode() == ISD::FMUL)
7774         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7775                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7776                                        N00.getOperand(0)),
7777                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7778                                        N00.getOperand(1)),
7779                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7780     }
7781
7782     // fold (fsub x, (fpext (fmul y, z)))
7783     //   -> (fma (fneg (fpext y)), (fpext z), x)
7784     // Note: Commutes FSUB operands.
7785     if (N1.getOpcode() == ISD::FP_EXTEND) {
7786       SDValue N10 = N1.getOperand(0);
7787       if (N10.getOpcode() == ISD::FMUL)
7788         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7789                            DAG.getNode(ISD::FNEG, SL, VT,
7790                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7791                                                    N10.getOperand(0))),
7792                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7793                                        N10.getOperand(1)),
7794                            N0);
7795     }
7796
7797     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7798     //   -> (fneg (fma (fpext x), (fpext y), z))
7799     // Note: This could be removed with appropriate canonicalization of the
7800     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7801     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7802     // from implementing the canonicalization in visitFSUB.
7803     if (N0.getOpcode() == ISD::FP_EXTEND) {
7804       SDValue N00 = N0.getOperand(0);
7805       if (N00.getOpcode() == ISD::FNEG) {
7806         SDValue N000 = N00.getOperand(0);
7807         if (N000.getOpcode() == ISD::FMUL) {
7808           return DAG.getNode(ISD::FNEG, SL, VT,
7809                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7810                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7811                                                      N000.getOperand(0)),
7812                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7813                                                      N000.getOperand(1)),
7814                                          N1));
7815         }
7816       }
7817     }
7818
7819     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7820     //   -> (fneg (fma (fpext x)), (fpext y), z)
7821     // Note: This could be removed with appropriate canonicalization of the
7822     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7823     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7824     // from implementing the canonicalization in visitFSUB.
7825     if (N0.getOpcode() == ISD::FNEG) {
7826       SDValue N00 = N0.getOperand(0);
7827       if (N00.getOpcode() == ISD::FP_EXTEND) {
7828         SDValue N000 = N00.getOperand(0);
7829         if (N000.getOpcode() == ISD::FMUL) {
7830           return DAG.getNode(ISD::FNEG, SL, VT,
7831                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7832                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7833                                                      N000.getOperand(0)),
7834                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7835                                                      N000.getOperand(1)),
7836                                          N1));
7837         }
7838       }
7839     }
7840
7841   }
7842
7843   // More folding opportunities when target permits.
7844   if ((AllowFusion || HasFMAD) && Aggressive) {
7845     // fold (fsub (fma x, y, (fmul u, v)), z)
7846     //   -> (fma x, y (fma u, v, (fneg z)))
7847     if (N0.getOpcode() == PreferredFusedOpcode &&
7848         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7849       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7850                          N0.getOperand(0), N0.getOperand(1),
7851                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7852                                      N0.getOperand(2).getOperand(0),
7853                                      N0.getOperand(2).getOperand(1),
7854                                      DAG.getNode(ISD::FNEG, SL, VT,
7855                                                  N1)));
7856     }
7857
7858     // fold (fsub x, (fma y, z, (fmul u, v)))
7859     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7860     if (N1.getOpcode() == PreferredFusedOpcode &&
7861         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7862       SDValue N20 = N1.getOperand(2).getOperand(0);
7863       SDValue N21 = N1.getOperand(2).getOperand(1);
7864       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7865                          DAG.getNode(ISD::FNEG, SL, VT,
7866                                      N1.getOperand(0)),
7867                          N1.getOperand(1),
7868                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7869                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7870
7871                                      N21, N0));
7872     }
7873
7874     if (AllowFusion && LookThroughFPExt) {
7875       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7876       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7877       if (N0.getOpcode() == PreferredFusedOpcode) {
7878         SDValue N02 = N0.getOperand(2);
7879         if (N02.getOpcode() == ISD::FP_EXTEND) {
7880           SDValue N020 = N02.getOperand(0);
7881           if (N020.getOpcode() == ISD::FMUL)
7882             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7883                                N0.getOperand(0), N0.getOperand(1),
7884                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7885                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7886                                                        N020.getOperand(0)),
7887                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7888                                                        N020.getOperand(1)),
7889                                            DAG.getNode(ISD::FNEG, SL, VT,
7890                                                        N1)));
7891         }
7892       }
7893
7894       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7895       //   -> (fma (fpext x), (fpext y),
7896       //           (fma (fpext u), (fpext v), (fneg z)))
7897       // FIXME: This turns two single-precision and one double-precision
7898       // operation into two double-precision operations, which might not be
7899       // interesting for all targets, especially GPUs.
7900       if (N0.getOpcode() == ISD::FP_EXTEND) {
7901         SDValue N00 = N0.getOperand(0);
7902         if (N00.getOpcode() == PreferredFusedOpcode) {
7903           SDValue N002 = N00.getOperand(2);
7904           if (N002.getOpcode() == ISD::FMUL)
7905             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7906                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7907                                            N00.getOperand(0)),
7908                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7909                                            N00.getOperand(1)),
7910                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7911                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7912                                                        N002.getOperand(0)),
7913                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7914                                                        N002.getOperand(1)),
7915                                            DAG.getNode(ISD::FNEG, SL, VT,
7916                                                        N1)));
7917         }
7918       }
7919
7920       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7921       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7922       if (N1.getOpcode() == PreferredFusedOpcode &&
7923         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7924         SDValue N120 = N1.getOperand(2).getOperand(0);
7925         if (N120.getOpcode() == ISD::FMUL) {
7926           SDValue N1200 = N120.getOperand(0);
7927           SDValue N1201 = N120.getOperand(1);
7928           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7929                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7930                              N1.getOperand(1),
7931                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7932                                          DAG.getNode(ISD::FNEG, SL, VT,
7933                                              DAG.getNode(ISD::FP_EXTEND, SL,
7934                                                          VT, N1200)),
7935                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7936                                                      N1201),
7937                                          N0));
7938         }
7939       }
7940
7941       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7942       //   -> (fma (fneg (fpext y)), (fpext z),
7943       //           (fma (fneg (fpext u)), (fpext v), x))
7944       // FIXME: This turns two single-precision and one double-precision
7945       // operation into two double-precision operations, which might not be
7946       // interesting for all targets, especially GPUs.
7947       if (N1.getOpcode() == ISD::FP_EXTEND &&
7948         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7949         SDValue N100 = N1.getOperand(0).getOperand(0);
7950         SDValue N101 = N1.getOperand(0).getOperand(1);
7951         SDValue N102 = N1.getOperand(0).getOperand(2);
7952         if (N102.getOpcode() == ISD::FMUL) {
7953           SDValue N1020 = N102.getOperand(0);
7954           SDValue N1021 = N102.getOperand(1);
7955           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7956                              DAG.getNode(ISD::FNEG, SL, VT,
7957                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7958                                                      N100)),
7959                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7960                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7961                                          DAG.getNode(ISD::FNEG, SL, VT,
7962                                              DAG.getNode(ISD::FP_EXTEND, SL,
7963                                                          VT, N1020)),
7964                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7965                                                      N1021),
7966                                          N0));
7967         }
7968       }
7969     }
7970   }
7971
7972   return SDValue();
7973 }
7974
7975 /// Try to perform FMA combining on a given FMUL node.
7976 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7977   SDValue N0 = N->getOperand(0);
7978   SDValue N1 = N->getOperand(1);
7979   EVT VT = N->getValueType(0);
7980   SDLoc SL(N);
7981
7982   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7983
7984   const TargetOptions &Options = DAG.getTarget().Options;
7985   bool AllowFusion =
7986       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7987
7988   // Floating-point multiply-add with intermediate rounding.
7989   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7990
7991   // Floating-point multiply-add without intermediate rounding.
7992   bool HasFMA =
7993       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7994       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7995
7996   // No valid opcode, do not combine.
7997   if (!HasFMAD && !HasFMA)
7998     return SDValue();
7999
8000   // Always prefer FMAD to FMA for precision.
8001   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
8002   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
8003
8004   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
8005   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
8006   auto FuseFADD = [&](SDValue X, SDValue Y) {
8007     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
8008       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8009       if (XC1 && XC1->isExactlyValue(+1.0))
8010         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8011       if (XC1 && XC1->isExactlyValue(-1.0))
8012         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8013                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8014     }
8015     return SDValue();
8016   };
8017
8018   if (SDValue FMA = FuseFADD(N0, N1))
8019     return FMA;
8020   if (SDValue FMA = FuseFADD(N1, N0))
8021     return FMA;
8022
8023   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
8024   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
8025   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
8026   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
8027   auto FuseFSUB = [&](SDValue X, SDValue Y) {
8028     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
8029       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8030       if (XC0 && XC0->isExactlyValue(+1.0))
8031         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8032                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8033                            Y);
8034       if (XC0 && XC0->isExactlyValue(-1.0))
8035         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8036                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8037                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8038
8039       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8040       if (XC1 && XC1->isExactlyValue(+1.0))
8041         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8042                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8043       if (XC1 && XC1->isExactlyValue(-1.0))
8044         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8045     }
8046     return SDValue();
8047   };
8048
8049   if (SDValue FMA = FuseFSUB(N0, N1))
8050     return FMA;
8051   if (SDValue FMA = FuseFSUB(N1, N0))
8052     return FMA;
8053
8054   return SDValue();
8055 }
8056
8057 SDValue DAGCombiner::visitFADD(SDNode *N) {
8058   SDValue N0 = N->getOperand(0);
8059   SDValue N1 = N->getOperand(1);
8060   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8061   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8062   EVT VT = N->getValueType(0);
8063   SDLoc DL(N);
8064   const TargetOptions &Options = DAG.getTarget().Options;
8065   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8066
8067   // fold vector ops
8068   if (VT.isVector())
8069     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8070       return FoldedVOp;
8071
8072   // fold (fadd c1, c2) -> c1 + c2
8073   if (N0CFP && N1CFP)
8074     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8075
8076   // canonicalize constant to RHS
8077   if (N0CFP && !N1CFP)
8078     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8079
8080   // fold (fadd A, (fneg B)) -> (fsub A, B)
8081   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8082       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8083     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8084                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8085
8086   // fold (fadd (fneg A), B) -> (fsub B, A)
8087   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8088       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8089     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8090                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8091
8092   // If 'unsafe math' is enabled, fold lots of things.
8093   if (Options.UnsafeFPMath) {
8094     // No FP constant should be created after legalization as Instruction
8095     // Selection pass has a hard time dealing with FP constants.
8096     bool AllowNewConst = (Level < AfterLegalizeDAG);
8097
8098     // fold (fadd A, 0) -> A
8099     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8100       if (N1C->isZero())
8101         return N0;
8102
8103     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8104     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8105         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8106       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8107                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8108                                      Flags),
8109                          Flags);
8110
8111     // If allowed, fold (fadd (fneg x), x) -> 0.0
8112     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8113       return DAG.getConstantFP(0.0, DL, VT);
8114
8115     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8116     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8117       return DAG.getConstantFP(0.0, DL, VT);
8118
8119     // We can fold chains of FADD's of the same value into multiplications.
8120     // This transform is not safe in general because we are reducing the number
8121     // of rounding steps.
8122     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8123       if (N0.getOpcode() == ISD::FMUL) {
8124         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8125         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8126
8127         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8128         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8129           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8130                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8131           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8132         }
8133
8134         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8135         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8136             N1.getOperand(0) == N1.getOperand(1) &&
8137             N0.getOperand(0) == N1.getOperand(0)) {
8138           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8139                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8140           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8141         }
8142       }
8143
8144       if (N1.getOpcode() == ISD::FMUL) {
8145         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8146         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8147
8148         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8149         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8150           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8151                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8152           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8153         }
8154
8155         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8156         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8157             N0.getOperand(0) == N0.getOperand(1) &&
8158             N1.getOperand(0) == N0.getOperand(0)) {
8159           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8160                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8161           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8162         }
8163       }
8164
8165       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8166         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8167         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8168         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8169             (N0.getOperand(0) == N1)) {
8170           return DAG.getNode(ISD::FMUL, DL, VT,
8171                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8172         }
8173       }
8174
8175       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8176         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8177         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8178         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8179             N1.getOperand(0) == N0) {
8180           return DAG.getNode(ISD::FMUL, DL, VT,
8181                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8182         }
8183       }
8184
8185       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8186       if (AllowNewConst &&
8187           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8188           N0.getOperand(0) == N0.getOperand(1) &&
8189           N1.getOperand(0) == N1.getOperand(1) &&
8190           N0.getOperand(0) == N1.getOperand(0)) {
8191         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8192                            DAG.getConstantFP(4.0, DL, VT), Flags);
8193       }
8194     }
8195   } // enable-unsafe-fp-math
8196
8197   // FADD -> FMA combines:
8198   if (SDValue Fused = visitFADDForFMACombine(N)) {
8199     AddToWorklist(Fused.getNode());
8200     return Fused;
8201   }
8202
8203   return SDValue();
8204 }
8205
8206 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8207   SDValue N0 = N->getOperand(0);
8208   SDValue N1 = N->getOperand(1);
8209   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8210   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8211   EVT VT = N->getValueType(0);
8212   SDLoc dl(N);
8213   const TargetOptions &Options = DAG.getTarget().Options;
8214   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8215
8216   // fold vector ops
8217   if (VT.isVector())
8218     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8219       return FoldedVOp;
8220
8221   // fold (fsub c1, c2) -> c1-c2
8222   if (N0CFP && N1CFP)
8223     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8224
8225   // fold (fsub A, (fneg B)) -> (fadd A, B)
8226   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8227     return DAG.getNode(ISD::FADD, dl, VT, N0,
8228                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8229
8230   // If 'unsafe math' is enabled, fold lots of things.
8231   if (Options.UnsafeFPMath) {
8232     // (fsub A, 0) -> A
8233     if (N1CFP && N1CFP->isZero())
8234       return N0;
8235
8236     // (fsub 0, B) -> -B
8237     if (N0CFP && N0CFP->isZero()) {
8238       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8239         return GetNegatedExpression(N1, DAG, LegalOperations);
8240       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8241         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8242     }
8243
8244     // (fsub x, x) -> 0.0
8245     if (N0 == N1)
8246       return DAG.getConstantFP(0.0f, dl, VT);
8247
8248     // (fsub x, (fadd x, y)) -> (fneg y)
8249     // (fsub x, (fadd y, x)) -> (fneg y)
8250     if (N1.getOpcode() == ISD::FADD) {
8251       SDValue N10 = N1->getOperand(0);
8252       SDValue N11 = N1->getOperand(1);
8253
8254       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8255         return GetNegatedExpression(N11, DAG, LegalOperations);
8256
8257       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8258         return GetNegatedExpression(N10, DAG, LegalOperations);
8259     }
8260   }
8261
8262   // FSUB -> FMA combines:
8263   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8264     AddToWorklist(Fused.getNode());
8265     return Fused;
8266   }
8267
8268   return SDValue();
8269 }
8270
8271 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8272   SDValue N0 = N->getOperand(0);
8273   SDValue N1 = N->getOperand(1);
8274   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8275   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8276   EVT VT = N->getValueType(0);
8277   SDLoc DL(N);
8278   const TargetOptions &Options = DAG.getTarget().Options;
8279   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8280
8281   // fold vector ops
8282   if (VT.isVector()) {
8283     // This just handles C1 * C2 for vectors. Other vector folds are below.
8284     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8285       return FoldedVOp;
8286   }
8287
8288   // fold (fmul c1, c2) -> c1*c2
8289   if (N0CFP && N1CFP)
8290     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8291
8292   // canonicalize constant to RHS
8293   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8294      !isConstantFPBuildVectorOrConstantFP(N1))
8295     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8296
8297   // fold (fmul A, 1.0) -> A
8298   if (N1CFP && N1CFP->isExactlyValue(1.0))
8299     return N0;
8300
8301   if (Options.UnsafeFPMath) {
8302     // fold (fmul A, 0) -> 0
8303     if (N1CFP && N1CFP->isZero())
8304       return N1;
8305
8306     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8307     if (N0.getOpcode() == ISD::FMUL) {
8308       // Fold scalars or any vector constants (not just splats).
8309       // This fold is done in general by InstCombine, but extra fmul insts
8310       // may have been generated during lowering.
8311       SDValue N00 = N0.getOperand(0);
8312       SDValue N01 = N0.getOperand(1);
8313       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8314       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8315       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8316
8317       // Check 1: Make sure that the first operand of the inner multiply is NOT
8318       // a constant. Otherwise, we may induce infinite looping.
8319       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8320         // Check 2: Make sure that the second operand of the inner multiply and
8321         // the second operand of the outer multiply are constants.
8322         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8323             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8324           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8325           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8326         }
8327       }
8328     }
8329
8330     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8331     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8332     // during an early run of DAGCombiner can prevent folding with fmuls
8333     // inserted during lowering.
8334     if (N0.getOpcode() == ISD::FADD &&
8335         (N0.getOperand(0) == N0.getOperand(1)) &&
8336         N0.hasOneUse()) {
8337       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8338       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8339       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8340     }
8341   }
8342
8343   // fold (fmul X, 2.0) -> (fadd X, X)
8344   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8345     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8346
8347   // fold (fmul X, -1.0) -> (fneg X)
8348   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8349     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8350       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8351
8352   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8353   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8354     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8355       // Both can be negated for free, check to see if at least one is cheaper
8356       // negated.
8357       if (LHSNeg == 2 || RHSNeg == 2)
8358         return DAG.getNode(ISD::FMUL, DL, VT,
8359                            GetNegatedExpression(N0, DAG, LegalOperations),
8360                            GetNegatedExpression(N1, DAG, LegalOperations),
8361                            Flags);
8362     }
8363   }
8364
8365   // FMUL -> FMA combines:
8366   if (SDValue Fused = visitFMULForFMACombine(N)) {
8367     AddToWorklist(Fused.getNode());
8368     return Fused;
8369   }
8370
8371   return SDValue();
8372 }
8373
8374 SDValue DAGCombiner::visitFMA(SDNode *N) {
8375   SDValue N0 = N->getOperand(0);
8376   SDValue N1 = N->getOperand(1);
8377   SDValue N2 = N->getOperand(2);
8378   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8379   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8380   EVT VT = N->getValueType(0);
8381   SDLoc dl(N);
8382   const TargetOptions &Options = DAG.getTarget().Options;
8383
8384   // Constant fold FMA.
8385   if (isa<ConstantFPSDNode>(N0) &&
8386       isa<ConstantFPSDNode>(N1) &&
8387       isa<ConstantFPSDNode>(N2)) {
8388     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8389   }
8390
8391   if (Options.UnsafeFPMath) {
8392     if (N0CFP && N0CFP->isZero())
8393       return N2;
8394     if (N1CFP && N1CFP->isZero())
8395       return N2;
8396   }
8397   // TODO: The FMA node should have flags that propagate to these nodes.
8398   if (N0CFP && N0CFP->isExactlyValue(1.0))
8399     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8400   if (N1CFP && N1CFP->isExactlyValue(1.0))
8401     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8402
8403   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8404   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8405      !isConstantFPBuildVectorOrConstantFP(N1))
8406     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8407
8408   // TODO: FMA nodes should have flags that propagate to the created nodes.
8409   // For now, create a Flags object for use with all unsafe math transforms.
8410   SDNodeFlags Flags;
8411   Flags.setUnsafeAlgebra(true);
8412
8413   if (Options.UnsafeFPMath) {
8414     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8415     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8416         isConstantFPBuildVectorOrConstantFP(N1) &&
8417         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8418       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8419                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8420                                      &Flags), &Flags);
8421     }
8422
8423     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8424     if (N0.getOpcode() == ISD::FMUL &&
8425         isConstantFPBuildVectorOrConstantFP(N1) &&
8426         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8427       return DAG.getNode(ISD::FMA, dl, VT,
8428                          N0.getOperand(0),
8429                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8430                                      &Flags),
8431                          N2);
8432     }
8433   }
8434
8435   // (fma x, 1, y) -> (fadd x, y)
8436   // (fma x, -1, y) -> (fadd (fneg x), y)
8437   if (N1CFP) {
8438     if (N1CFP->isExactlyValue(1.0))
8439       // TODO: The FMA node should have flags that propagate to this node.
8440       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8441
8442     if (N1CFP->isExactlyValue(-1.0) &&
8443         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8444       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8445       AddToWorklist(RHSNeg.getNode());
8446       // TODO: The FMA node should have flags that propagate to this node.
8447       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8448     }
8449   }
8450
8451   if (Options.UnsafeFPMath) {
8452     // (fma x, c, x) -> (fmul x, (c+1))
8453     if (N1CFP && N0 == N2) {
8454     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8455                          DAG.getNode(ISD::FADD, dl, VT,
8456                                      N1, DAG.getConstantFP(1.0, dl, VT),
8457                                      &Flags), &Flags);
8458     }
8459
8460     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8461     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8462       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8463                          DAG.getNode(ISD::FADD, dl, VT,
8464                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8465                                      &Flags), &Flags);
8466     }
8467   }
8468
8469   return SDValue();
8470 }
8471
8472 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8473 // reciprocal.
8474 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8475 // Notice that this is not always beneficial. One reason is different target
8476 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8477 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8478 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8479 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8480   bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
8481   const SDNodeFlags *Flags = N->getFlags();
8482   if (!UnsafeMath && !Flags->hasAllowReciprocal())
8483     return SDValue();
8484
8485   // Skip if current node is a reciprocal.
8486   SDValue N0 = N->getOperand(0);
8487   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8488   if (N0CFP && N0CFP->isExactlyValue(1.0))
8489     return SDValue();
8490
8491   // Exit early if the target does not want this transform or if there can't
8492   // possibly be enough uses of the divisor to make the transform worthwhile.
8493   SDValue N1 = N->getOperand(1);
8494   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8495   if (!MinUses || N1->use_size() < MinUses)
8496     return SDValue();
8497
8498   // Find all FDIV users of the same divisor.
8499   // Use a set because duplicates may be present in the user list.
8500   SetVector<SDNode *> Users;
8501   for (auto *U : N1->uses()) {
8502     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
8503       // This division is eligible for optimization only if global unsafe math
8504       // is enabled or if this division allows reciprocal formation.
8505       if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
8506         Users.insert(U);
8507     }
8508   }
8509
8510   // Now that we have the actual number of divisor uses, make sure it meets
8511   // the minimum threshold specified by the target.
8512   if (Users.size() < MinUses)
8513     return SDValue();
8514
8515   EVT VT = N->getValueType(0);
8516   SDLoc DL(N);
8517   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8518   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8519
8520   // Dividend / Divisor -> Dividend * Reciprocal
8521   for (auto *U : Users) {
8522     SDValue Dividend = U->getOperand(0);
8523     if (Dividend != FPOne) {
8524       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8525                                     Reciprocal, Flags);
8526       CombineTo(U, NewNode);
8527     } else if (U != Reciprocal.getNode()) {
8528       // In the absence of fast-math-flags, this user node is always the
8529       // same node as Reciprocal, but with FMF they may be different nodes.
8530       CombineTo(U, Reciprocal);
8531     }
8532   }
8533   return SDValue(N, 0);  // N was replaced.
8534 }
8535
8536 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8537   SDValue N0 = N->getOperand(0);
8538   SDValue N1 = N->getOperand(1);
8539   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8540   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8541   EVT VT = N->getValueType(0);
8542   SDLoc DL(N);
8543   const TargetOptions &Options = DAG.getTarget().Options;
8544   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8545
8546   // fold vector ops
8547   if (VT.isVector())
8548     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8549       return FoldedVOp;
8550
8551   // fold (fdiv c1, c2) -> c1/c2
8552   if (N0CFP && N1CFP)
8553     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8554
8555   if (Options.UnsafeFPMath) {
8556     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8557     if (N1CFP) {
8558       // Compute the reciprocal 1.0 / c2.
8559       APFloat N1APF = N1CFP->getValueAPF();
8560       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8561       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8562       // Only do the transform if the reciprocal is a legal fp immediate that
8563       // isn't too nasty (eg NaN, denormal, ...).
8564       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8565           (!LegalOperations ||
8566            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8567            // backend)... we should handle this gracefully after Legalize.
8568            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8569            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8570            TLI.isFPImmLegal(Recip, VT)))
8571         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8572                            DAG.getConstantFP(Recip, DL, VT), Flags);
8573     }
8574
8575     // If this FDIV is part of a reciprocal square root, it may be folded
8576     // into a target-specific square root estimate instruction.
8577     if (N1.getOpcode() == ISD::FSQRT) {
8578       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8579         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8580       }
8581     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8582                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8583       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8584                                           Flags)) {
8585         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8586         AddToWorklist(RV.getNode());
8587         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8588       }
8589     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8590                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8591       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8592                                           Flags)) {
8593         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8594         AddToWorklist(RV.getNode());
8595         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8596       }
8597     } else if (N1.getOpcode() == ISD::FMUL) {
8598       // Look through an FMUL. Even though this won't remove the FDIV directly,
8599       // it's still worthwhile to get rid of the FSQRT if possible.
8600       SDValue SqrtOp;
8601       SDValue OtherOp;
8602       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8603         SqrtOp = N1.getOperand(0);
8604         OtherOp = N1.getOperand(1);
8605       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8606         SqrtOp = N1.getOperand(1);
8607         OtherOp = N1.getOperand(0);
8608       }
8609       if (SqrtOp.getNode()) {
8610         // We found a FSQRT, so try to make this fold:
8611         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8612         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8613           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8614           AddToWorklist(RV.getNode());
8615           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8616         }
8617       }
8618     }
8619
8620     // Fold into a reciprocal estimate and multiply instead of a real divide.
8621     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8622       AddToWorklist(RV.getNode());
8623       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8624     }
8625   }
8626
8627   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8628   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8629     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8630       // Both can be negated for free, check to see if at least one is cheaper
8631       // negated.
8632       if (LHSNeg == 2 || RHSNeg == 2)
8633         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8634                            GetNegatedExpression(N0, DAG, LegalOperations),
8635                            GetNegatedExpression(N1, DAG, LegalOperations),
8636                            Flags);
8637     }
8638   }
8639
8640   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8641     return CombineRepeatedDivisors;
8642
8643   return SDValue();
8644 }
8645
8646 SDValue DAGCombiner::visitFREM(SDNode *N) {
8647   SDValue N0 = N->getOperand(0);
8648   SDValue N1 = N->getOperand(1);
8649   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8650   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8651   EVT VT = N->getValueType(0);
8652
8653   // fold (frem c1, c2) -> fmod(c1,c2)
8654   if (N0CFP && N1CFP)
8655     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8656                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8657
8658   return SDValue();
8659 }
8660
8661 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8662   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8663     return SDValue();
8664
8665   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8666   // For now, create a Flags object for use with all unsafe math transforms.
8667   SDNodeFlags Flags;
8668   Flags.setUnsafeAlgebra(true);
8669
8670   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8671   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8672   if (!RV)
8673     return SDValue();
8674
8675   EVT VT = RV.getValueType();
8676   SDLoc DL(N);
8677   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8678   AddToWorklist(RV.getNode());
8679
8680   // Unfortunately, RV is now NaN if the input was exactly 0.
8681   // Select out this case and force the answer to 0.
8682   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8683   EVT CCVT = getSetCCResultType(VT);
8684   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8685   AddToWorklist(ZeroCmp.getNode());
8686   AddToWorklist(RV.getNode());
8687
8688   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8689                      ZeroCmp, Zero, RV);
8690 }
8691
8692 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8693   SDValue N0 = N->getOperand(0);
8694   SDValue N1 = N->getOperand(1);
8695   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8696   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8697   EVT VT = N->getValueType(0);
8698
8699   if (N0CFP && N1CFP)  // Constant fold
8700     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8701
8702   if (N1CFP) {
8703     const APFloat& V = N1CFP->getValueAPF();
8704     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8705     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8706     if (!V.isNegative()) {
8707       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8708         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8709     } else {
8710       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8711         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8712                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8713     }
8714   }
8715
8716   // copysign(fabs(x), y) -> copysign(x, y)
8717   // copysign(fneg(x), y) -> copysign(x, y)
8718   // copysign(copysign(x,z), y) -> copysign(x, y)
8719   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8720       N0.getOpcode() == ISD::FCOPYSIGN)
8721     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8722                        N0.getOperand(0), N1);
8723
8724   // copysign(x, abs(y)) -> abs(x)
8725   if (N1.getOpcode() == ISD::FABS)
8726     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8727
8728   // copysign(x, copysign(y,z)) -> copysign(x, z)
8729   if (N1.getOpcode() == ISD::FCOPYSIGN)
8730     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8731                        N0, N1.getOperand(1));
8732
8733   // copysign(x, fp_extend(y)) -> copysign(x, y)
8734   // copysign(x, fp_round(y)) -> copysign(x, y)
8735   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8736     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8737                        N0, N1.getOperand(0));
8738
8739   return SDValue();
8740 }
8741
8742 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8743   SDValue N0 = N->getOperand(0);
8744   EVT VT = N->getValueType(0);
8745   EVT OpVT = N0.getValueType();
8746
8747   // fold (sint_to_fp c1) -> c1fp
8748   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8749       // ...but only if the target supports immediate floating-point values
8750       (!LegalOperations ||
8751        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8752     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8753
8754   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8755   // but UINT_TO_FP is legal on this target, try to convert.
8756   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8757       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8758     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8759     if (DAG.SignBitIsZero(N0))
8760       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8761   }
8762
8763   // The next optimizations are desirable only if SELECT_CC can be lowered.
8764   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8765     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8766     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8767         !VT.isVector() &&
8768         (!LegalOperations ||
8769          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8770       SDLoc DL(N);
8771       SDValue Ops[] =
8772         { N0.getOperand(0), N0.getOperand(1),
8773           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8774           N0.getOperand(2) };
8775       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8776     }
8777
8778     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8779     //      (select_cc x, y, 1.0, 0.0,, cc)
8780     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8781         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8782         (!LegalOperations ||
8783          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8784       SDLoc DL(N);
8785       SDValue Ops[] =
8786         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8787           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8788           N0.getOperand(0).getOperand(2) };
8789       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8790     }
8791   }
8792
8793   return SDValue();
8794 }
8795
8796 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8797   SDValue N0 = N->getOperand(0);
8798   EVT VT = N->getValueType(0);
8799   EVT OpVT = N0.getValueType();
8800
8801   // fold (uint_to_fp c1) -> c1fp
8802   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8803       // ...but only if the target supports immediate floating-point values
8804       (!LegalOperations ||
8805        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8806     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8807
8808   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8809   // but SINT_TO_FP is legal on this target, try to convert.
8810   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8811       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8812     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8813     if (DAG.SignBitIsZero(N0))
8814       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8815   }
8816
8817   // The next optimizations are desirable only if SELECT_CC can be lowered.
8818   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8819     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8820
8821     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8822         (!LegalOperations ||
8823          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8824       SDLoc DL(N);
8825       SDValue Ops[] =
8826         { N0.getOperand(0), N0.getOperand(1),
8827           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8828           N0.getOperand(2) };
8829       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8830     }
8831   }
8832
8833   return SDValue();
8834 }
8835
8836 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8837 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8838   SDValue N0 = N->getOperand(0);
8839   EVT VT = N->getValueType(0);
8840
8841   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8842     return SDValue();
8843
8844   SDValue Src = N0.getOperand(0);
8845   EVT SrcVT = Src.getValueType();
8846   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8847   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8848
8849   // We can safely assume the conversion won't overflow the output range,
8850   // because (for example) (uint8_t)18293.f is undefined behavior.
8851
8852   // Since we can assume the conversion won't overflow, our decision as to
8853   // whether the input will fit in the float should depend on the minimum
8854   // of the input range and output range.
8855
8856   // This means this is also safe for a signed input and unsigned output, since
8857   // a negative input would lead to undefined behavior.
8858   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8859   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8860   unsigned ActualSize = std::min(InputSize, OutputSize);
8861   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8862
8863   // We can only fold away the float conversion if the input range can be
8864   // represented exactly in the float range.
8865   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8866     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8867       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8868                                                        : ISD::ZERO_EXTEND;
8869       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8870     }
8871     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8872       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8873     if (SrcVT == VT)
8874       return Src;
8875     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8876   }
8877   return SDValue();
8878 }
8879
8880 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8881   SDValue N0 = N->getOperand(0);
8882   EVT VT = N->getValueType(0);
8883
8884   // fold (fp_to_sint c1fp) -> c1
8885   if (isConstantFPBuildVectorOrConstantFP(N0))
8886     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8887
8888   return FoldIntToFPToInt(N, DAG);
8889 }
8890
8891 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8892   SDValue N0 = N->getOperand(0);
8893   EVT VT = N->getValueType(0);
8894
8895   // fold (fp_to_uint c1fp) -> c1
8896   if (isConstantFPBuildVectorOrConstantFP(N0))
8897     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8898
8899   return FoldIntToFPToInt(N, DAG);
8900 }
8901
8902 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8903   SDValue N0 = N->getOperand(0);
8904   SDValue N1 = N->getOperand(1);
8905   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8906   EVT VT = N->getValueType(0);
8907
8908   // fold (fp_round c1fp) -> c1fp
8909   if (N0CFP)
8910     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8911
8912   // fold (fp_round (fp_extend x)) -> x
8913   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8914     return N0.getOperand(0);
8915
8916   // fold (fp_round (fp_round x)) -> (fp_round x)
8917   if (N0.getOpcode() == ISD::FP_ROUND) {
8918     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8919     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8920     // If the first fp_round isn't a value preserving truncation, it might
8921     // introduce a tie in the second fp_round, that wouldn't occur in the
8922     // single-step fp_round we want to fold to.
8923     // In other words, double rounding isn't the same as rounding.
8924     // Also, this is a value preserving truncation iff both fp_round's are.
8925     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8926       SDLoc DL(N);
8927       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8928                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8929     }
8930   }
8931
8932   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8933   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8934     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8935                               N0.getOperand(0), N1);
8936     AddToWorklist(Tmp.getNode());
8937     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8938                        Tmp, N0.getOperand(1));
8939   }
8940
8941   return SDValue();
8942 }
8943
8944 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8945   SDValue N0 = N->getOperand(0);
8946   EVT VT = N->getValueType(0);
8947   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8948   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8949
8950   // fold (fp_round_inreg c1fp) -> c1fp
8951   if (N0CFP && isTypeLegal(EVT)) {
8952     SDLoc DL(N);
8953     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8954     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8955   }
8956
8957   return SDValue();
8958 }
8959
8960 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8961   SDValue N0 = N->getOperand(0);
8962   EVT VT = N->getValueType(0);
8963
8964   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8965   if (N->hasOneUse() &&
8966       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8967     return SDValue();
8968
8969   // fold (fp_extend c1fp) -> c1fp
8970   if (isConstantFPBuildVectorOrConstantFP(N0))
8971     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8972
8973   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8974   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8975       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8976     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8977
8978   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8979   // value of X.
8980   if (N0.getOpcode() == ISD::FP_ROUND
8981       && N0.getNode()->getConstantOperandVal(1) == 1) {
8982     SDValue In = N0.getOperand(0);
8983     if (In.getValueType() == VT) return In;
8984     if (VT.bitsLT(In.getValueType()))
8985       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8986                          In, N0.getOperand(1));
8987     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8988   }
8989
8990   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8991   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8992        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8993     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8994     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8995                                      LN0->getChain(),
8996                                      LN0->getBasePtr(), N0.getValueType(),
8997                                      LN0->getMemOperand());
8998     CombineTo(N, ExtLoad);
8999     CombineTo(N0.getNode(),
9000               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
9001                           N0.getValueType(), ExtLoad,
9002                           DAG.getIntPtrConstant(1, SDLoc(N0))),
9003               ExtLoad.getValue(1));
9004     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9005   }
9006
9007   return SDValue();
9008 }
9009
9010 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
9011   SDValue N0 = N->getOperand(0);
9012   EVT VT = N->getValueType(0);
9013
9014   // fold (fceil c1) -> fceil(c1)
9015   if (isConstantFPBuildVectorOrConstantFP(N0))
9016     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
9017
9018   return SDValue();
9019 }
9020
9021 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
9022   SDValue N0 = N->getOperand(0);
9023   EVT VT = N->getValueType(0);
9024
9025   // fold (ftrunc c1) -> ftrunc(c1)
9026   if (isConstantFPBuildVectorOrConstantFP(N0))
9027     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
9028
9029   return SDValue();
9030 }
9031
9032 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
9033   SDValue N0 = N->getOperand(0);
9034   EVT VT = N->getValueType(0);
9035
9036   // fold (ffloor c1) -> ffloor(c1)
9037   if (isConstantFPBuildVectorOrConstantFP(N0))
9038     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9039
9040   return SDValue();
9041 }
9042
9043 // FIXME: FNEG and FABS have a lot in common; refactor.
9044 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9045   SDValue N0 = N->getOperand(0);
9046   EVT VT = N->getValueType(0);
9047
9048   // Constant fold FNEG.
9049   if (isConstantFPBuildVectorOrConstantFP(N0))
9050     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9051
9052   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9053                          &DAG.getTarget().Options))
9054     return GetNegatedExpression(N0, DAG, LegalOperations);
9055
9056   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9057   // constant pool values.
9058   if (!TLI.isFNegFree(VT) &&
9059       N0.getOpcode() == ISD::BITCAST &&
9060       N0.getNode()->hasOneUse()) {
9061     SDValue Int = N0.getOperand(0);
9062     EVT IntVT = Int.getValueType();
9063     if (IntVT.isInteger() && !IntVT.isVector()) {
9064       APInt SignMask;
9065       if (N0.getValueType().isVector()) {
9066         // For a vector, get a mask such as 0x80... per scalar element
9067         // and splat it.
9068         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9069         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9070       } else {
9071         // For a scalar, just generate 0x80...
9072         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9073       }
9074       SDLoc DL0(N0);
9075       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9076                         DAG.getConstant(SignMask, DL0, IntVT));
9077       AddToWorklist(Int.getNode());
9078       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9079     }
9080   }
9081
9082   // (fneg (fmul c, x)) -> (fmul -c, x)
9083   if (N0.getOpcode() == ISD::FMUL &&
9084       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9085     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9086     if (CFP1) {
9087       APFloat CVal = CFP1->getValueAPF();
9088       CVal.changeSign();
9089       if (Level >= AfterLegalizeDAG &&
9090           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9091            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9092         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9093                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9094                                        N0.getOperand(1)),
9095                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9096     }
9097   }
9098
9099   return SDValue();
9100 }
9101
9102 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9103   SDValue N0 = N->getOperand(0);
9104   SDValue N1 = N->getOperand(1);
9105   EVT VT = N->getValueType(0);
9106   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9107   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9108
9109   if (N0CFP && N1CFP) {
9110     const APFloat &C0 = N0CFP->getValueAPF();
9111     const APFloat &C1 = N1CFP->getValueAPF();
9112     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9113   }
9114
9115   // Canonicalize to constant on RHS.
9116   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9117      !isConstantFPBuildVectorOrConstantFP(N1))
9118     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9119
9120   return SDValue();
9121 }
9122
9123 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9124   SDValue N0 = N->getOperand(0);
9125   SDValue N1 = N->getOperand(1);
9126   EVT VT = N->getValueType(0);
9127   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9128   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9129
9130   if (N0CFP && N1CFP) {
9131     const APFloat &C0 = N0CFP->getValueAPF();
9132     const APFloat &C1 = N1CFP->getValueAPF();
9133     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9134   }
9135
9136   // Canonicalize to constant on RHS.
9137   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9138      !isConstantFPBuildVectorOrConstantFP(N1))
9139     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9140
9141   return SDValue();
9142 }
9143
9144 SDValue DAGCombiner::visitFABS(SDNode *N) {
9145   SDValue N0 = N->getOperand(0);
9146   EVT VT = N->getValueType(0);
9147
9148   // fold (fabs c1) -> fabs(c1)
9149   if (isConstantFPBuildVectorOrConstantFP(N0))
9150     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9151
9152   // fold (fabs (fabs x)) -> (fabs x)
9153   if (N0.getOpcode() == ISD::FABS)
9154     return N->getOperand(0);
9155
9156   // fold (fabs (fneg x)) -> (fabs x)
9157   // fold (fabs (fcopysign x, y)) -> (fabs x)
9158   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9159     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9160
9161   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9162   // constant pool values.
9163   if (!TLI.isFAbsFree(VT) &&
9164       N0.getOpcode() == ISD::BITCAST &&
9165       N0.getNode()->hasOneUse()) {
9166     SDValue Int = N0.getOperand(0);
9167     EVT IntVT = Int.getValueType();
9168     if (IntVT.isInteger() && !IntVT.isVector()) {
9169       APInt SignMask;
9170       if (N0.getValueType().isVector()) {
9171         // For a vector, get a mask such as 0x7f... per scalar element
9172         // and splat it.
9173         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9174         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9175       } else {
9176         // For a scalar, just generate 0x7f...
9177         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9178       }
9179       SDLoc DL(N0);
9180       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9181                         DAG.getConstant(SignMask, DL, IntVT));
9182       AddToWorklist(Int.getNode());
9183       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9184     }
9185   }
9186
9187   return SDValue();
9188 }
9189
9190 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9191   SDValue Chain = N->getOperand(0);
9192   SDValue N1 = N->getOperand(1);
9193   SDValue N2 = N->getOperand(2);
9194
9195   // If N is a constant we could fold this into a fallthrough or unconditional
9196   // branch. However that doesn't happen very often in normal code, because
9197   // Instcombine/SimplifyCFG should have handled the available opportunities.
9198   // If we did this folding here, it would be necessary to update the
9199   // MachineBasicBlock CFG, which is awkward.
9200
9201   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9202   // on the target.
9203   if (N1.getOpcode() == ISD::SETCC &&
9204       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9205                                    N1.getOperand(0).getValueType())) {
9206     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9207                        Chain, N1.getOperand(2),
9208                        N1.getOperand(0), N1.getOperand(1), N2);
9209   }
9210
9211   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9212       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9213        (N1.getOperand(0).hasOneUse() &&
9214         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9215     SDNode *Trunc = nullptr;
9216     if (N1.getOpcode() == ISD::TRUNCATE) {
9217       // Look pass the truncate.
9218       Trunc = N1.getNode();
9219       N1 = N1.getOperand(0);
9220     }
9221
9222     // Match this pattern so that we can generate simpler code:
9223     //
9224     //   %a = ...
9225     //   %b = and i32 %a, 2
9226     //   %c = srl i32 %b, 1
9227     //   brcond i32 %c ...
9228     //
9229     // into
9230     //
9231     //   %a = ...
9232     //   %b = and i32 %a, 2
9233     //   %c = setcc eq %b, 0
9234     //   brcond %c ...
9235     //
9236     // This applies only when the AND constant value has one bit set and the
9237     // SRL constant is equal to the log2 of the AND constant. The back-end is
9238     // smart enough to convert the result into a TEST/JMP sequence.
9239     SDValue Op0 = N1.getOperand(0);
9240     SDValue Op1 = N1.getOperand(1);
9241
9242     if (Op0.getOpcode() == ISD::AND &&
9243         Op1.getOpcode() == ISD::Constant) {
9244       SDValue AndOp1 = Op0.getOperand(1);
9245
9246       if (AndOp1.getOpcode() == ISD::Constant) {
9247         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9248
9249         if (AndConst.isPowerOf2() &&
9250             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9251           SDLoc DL(N);
9252           SDValue SetCC =
9253             DAG.getSetCC(DL,
9254                          getSetCCResultType(Op0.getValueType()),
9255                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9256                          ISD::SETNE);
9257
9258           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9259                                           MVT::Other, Chain, SetCC, N2);
9260           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9261           // will convert it back to (X & C1) >> C2.
9262           CombineTo(N, NewBRCond, false);
9263           // Truncate is dead.
9264           if (Trunc)
9265             deleteAndRecombine(Trunc);
9266           // Replace the uses of SRL with SETCC
9267           WorklistRemover DeadNodes(*this);
9268           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9269           deleteAndRecombine(N1.getNode());
9270           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9271         }
9272       }
9273     }
9274
9275     if (Trunc)
9276       // Restore N1 if the above transformation doesn't match.
9277       N1 = N->getOperand(1);
9278   }
9279
9280   // Transform br(xor(x, y)) -> br(x != y)
9281   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9282   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9283     SDNode *TheXor = N1.getNode();
9284     SDValue Op0 = TheXor->getOperand(0);
9285     SDValue Op1 = TheXor->getOperand(1);
9286     if (Op0.getOpcode() == Op1.getOpcode()) {
9287       // Avoid missing important xor optimizations.
9288       if (SDValue Tmp = visitXOR(TheXor)) {
9289         if (Tmp.getNode() != TheXor) {
9290           DEBUG(dbgs() << "\nReplacing.8 ";
9291                 TheXor->dump(&DAG);
9292                 dbgs() << "\nWith: ";
9293                 Tmp.getNode()->dump(&DAG);
9294                 dbgs() << '\n');
9295           WorklistRemover DeadNodes(*this);
9296           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9297           deleteAndRecombine(TheXor);
9298           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9299                              MVT::Other, Chain, Tmp, N2);
9300         }
9301
9302         // visitXOR has changed XOR's operands or replaced the XOR completely,
9303         // bail out.
9304         return SDValue(N, 0);
9305       }
9306     }
9307
9308     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9309       bool Equal = false;
9310       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9311           Op0.getOpcode() == ISD::XOR) {
9312         TheXor = Op0.getNode();
9313         Equal = true;
9314       }
9315
9316       EVT SetCCVT = N1.getValueType();
9317       if (LegalTypes)
9318         SetCCVT = getSetCCResultType(SetCCVT);
9319       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9320                                    SetCCVT,
9321                                    Op0, Op1,
9322                                    Equal ? ISD::SETEQ : ISD::SETNE);
9323       // Replace the uses of XOR with SETCC
9324       WorklistRemover DeadNodes(*this);
9325       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9326       deleteAndRecombine(N1.getNode());
9327       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9328                          MVT::Other, Chain, SetCC, N2);
9329     }
9330   }
9331
9332   return SDValue();
9333 }
9334
9335 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9336 //
9337 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9338   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9339   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9340
9341   // If N is a constant we could fold this into a fallthrough or unconditional
9342   // branch. However that doesn't happen very often in normal code, because
9343   // Instcombine/SimplifyCFG should have handled the available opportunities.
9344   // If we did this folding here, it would be necessary to update the
9345   // MachineBasicBlock CFG, which is awkward.
9346
9347   // Use SimplifySetCC to simplify SETCC's.
9348   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9349                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9350                                false);
9351   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9352
9353   // fold to a simpler setcc
9354   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9355     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9356                        N->getOperand(0), Simp.getOperand(2),
9357                        Simp.getOperand(0), Simp.getOperand(1),
9358                        N->getOperand(4));
9359
9360   return SDValue();
9361 }
9362
9363 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9364 /// and that N may be folded in the load / store addressing mode.
9365 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9366                                     SelectionDAG &DAG,
9367                                     const TargetLowering &TLI) {
9368   EVT VT;
9369   unsigned AS;
9370
9371   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9372     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9373       return false;
9374     VT = LD->getMemoryVT();
9375     AS = LD->getAddressSpace();
9376   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9377     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9378       return false;
9379     VT = ST->getMemoryVT();
9380     AS = ST->getAddressSpace();
9381   } else
9382     return false;
9383
9384   TargetLowering::AddrMode AM;
9385   if (N->getOpcode() == ISD::ADD) {
9386     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9387     if (Offset)
9388       // [reg +/- imm]
9389       AM.BaseOffs = Offset->getSExtValue();
9390     else
9391       // [reg +/- reg]
9392       AM.Scale = 1;
9393   } else if (N->getOpcode() == ISD::SUB) {
9394     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9395     if (Offset)
9396       // [reg +/- imm]
9397       AM.BaseOffs = -Offset->getSExtValue();
9398     else
9399       // [reg +/- reg]
9400       AM.Scale = 1;
9401   } else
9402     return false;
9403
9404   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9405                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9406 }
9407
9408 /// Try turning a load/store into a pre-indexed load/store when the base
9409 /// pointer is an add or subtract and it has other uses besides the load/store.
9410 /// After the transformation, the new indexed load/store has effectively folded
9411 /// the add/subtract in and all of its other uses are redirected to the
9412 /// new load/store.
9413 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9414   if (Level < AfterLegalizeDAG)
9415     return false;
9416
9417   bool isLoad = true;
9418   SDValue Ptr;
9419   EVT VT;
9420   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9421     if (LD->isIndexed())
9422       return false;
9423     VT = LD->getMemoryVT();
9424     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9425         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9426       return false;
9427     Ptr = LD->getBasePtr();
9428   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9429     if (ST->isIndexed())
9430       return false;
9431     VT = ST->getMemoryVT();
9432     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9433         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9434       return false;
9435     Ptr = ST->getBasePtr();
9436     isLoad = false;
9437   } else {
9438     return false;
9439   }
9440
9441   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9442   // out.  There is no reason to make this a preinc/predec.
9443   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9444       Ptr.getNode()->hasOneUse())
9445     return false;
9446
9447   // Ask the target to do addressing mode selection.
9448   SDValue BasePtr;
9449   SDValue Offset;
9450   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9451   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9452     return false;
9453
9454   // Backends without true r+i pre-indexed forms may need to pass a
9455   // constant base with a variable offset so that constant coercion
9456   // will work with the patterns in canonical form.
9457   bool Swapped = false;
9458   if (isa<ConstantSDNode>(BasePtr)) {
9459     std::swap(BasePtr, Offset);
9460     Swapped = true;
9461   }
9462
9463   // Don't create a indexed load / store with zero offset.
9464   if (isNullConstant(Offset))
9465     return false;
9466
9467   // Try turning it into a pre-indexed load / store except when:
9468   // 1) The new base ptr is a frame index.
9469   // 2) If N is a store and the new base ptr is either the same as or is a
9470   //    predecessor of the value being stored.
9471   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9472   //    that would create a cycle.
9473   // 4) All uses are load / store ops that use it as old base ptr.
9474
9475   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9476   // (plus the implicit offset) to a register to preinc anyway.
9477   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9478     return false;
9479
9480   // Check #2.
9481   if (!isLoad) {
9482     SDValue Val = cast<StoreSDNode>(N)->getValue();
9483     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9484       return false;
9485   }
9486
9487   // If the offset is a constant, there may be other adds of constants that
9488   // can be folded with this one. We should do this to avoid having to keep
9489   // a copy of the original base pointer.
9490   SmallVector<SDNode *, 16> OtherUses;
9491   if (isa<ConstantSDNode>(Offset))
9492     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9493                               UE = BasePtr.getNode()->use_end();
9494          UI != UE; ++UI) {
9495       SDUse &Use = UI.getUse();
9496       // Skip the use that is Ptr and uses of other results from BasePtr's
9497       // node (important for nodes that return multiple results).
9498       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9499         continue;
9500
9501       if (Use.getUser()->isPredecessorOf(N))
9502         continue;
9503
9504       if (Use.getUser()->getOpcode() != ISD::ADD &&
9505           Use.getUser()->getOpcode() != ISD::SUB) {
9506         OtherUses.clear();
9507         break;
9508       }
9509
9510       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9511       if (!isa<ConstantSDNode>(Op1)) {
9512         OtherUses.clear();
9513         break;
9514       }
9515
9516       // FIXME: In some cases, we can be smarter about this.
9517       if (Op1.getValueType() != Offset.getValueType()) {
9518         OtherUses.clear();
9519         break;
9520       }
9521
9522       OtherUses.push_back(Use.getUser());
9523     }
9524
9525   if (Swapped)
9526     std::swap(BasePtr, Offset);
9527
9528   // Now check for #3 and #4.
9529   bool RealUse = false;
9530
9531   // Caches for hasPredecessorHelper
9532   SmallPtrSet<const SDNode *, 32> Visited;
9533   SmallVector<const SDNode *, 16> Worklist;
9534
9535   for (SDNode *Use : Ptr.getNode()->uses()) {
9536     if (Use == N)
9537       continue;
9538     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9539       return false;
9540
9541     // If Ptr may be folded in addressing mode of other use, then it's
9542     // not profitable to do this transformation.
9543     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9544       RealUse = true;
9545   }
9546
9547   if (!RealUse)
9548     return false;
9549
9550   SDValue Result;
9551   if (isLoad)
9552     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9553                                 BasePtr, Offset, AM);
9554   else
9555     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9556                                  BasePtr, Offset, AM);
9557   ++PreIndexedNodes;
9558   ++NodesCombined;
9559   DEBUG(dbgs() << "\nReplacing.4 ";
9560         N->dump(&DAG);
9561         dbgs() << "\nWith: ";
9562         Result.getNode()->dump(&DAG);
9563         dbgs() << '\n');
9564   WorklistRemover DeadNodes(*this);
9565   if (isLoad) {
9566     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9567     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9568   } else {
9569     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9570   }
9571
9572   // Finally, since the node is now dead, remove it from the graph.
9573   deleteAndRecombine(N);
9574
9575   if (Swapped)
9576     std::swap(BasePtr, Offset);
9577
9578   // Replace other uses of BasePtr that can be updated to use Ptr
9579   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9580     unsigned OffsetIdx = 1;
9581     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9582       OffsetIdx = 0;
9583     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9584            BasePtr.getNode() && "Expected BasePtr operand");
9585
9586     // We need to replace ptr0 in the following expression:
9587     //   x0 * offset0 + y0 * ptr0 = t0
9588     // knowing that
9589     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9590     //
9591     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9592     // indexed load/store and the expresion that needs to be re-written.
9593     //
9594     // Therefore, we have:
9595     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9596
9597     ConstantSDNode *CN =
9598       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9599     int X0, X1, Y0, Y1;
9600     APInt Offset0 = CN->getAPIntValue();
9601     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9602
9603     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9604     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9605     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9606     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9607
9608     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9609
9610     APInt CNV = Offset0;
9611     if (X0 < 0) CNV = -CNV;
9612     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9613     else CNV = CNV - Offset1;
9614
9615     SDLoc DL(OtherUses[i]);
9616
9617     // We can now generate the new expression.
9618     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9619     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9620
9621     SDValue NewUse = DAG.getNode(Opcode,
9622                                  DL,
9623                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9624     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9625     deleteAndRecombine(OtherUses[i]);
9626   }
9627
9628   // Replace the uses of Ptr with uses of the updated base value.
9629   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9630   deleteAndRecombine(Ptr.getNode());
9631
9632   return true;
9633 }
9634
9635 /// Try to combine a load/store with a add/sub of the base pointer node into a
9636 /// post-indexed load/store. The transformation folded the add/subtract into the
9637 /// new indexed load/store effectively and all of its uses are redirected to the
9638 /// new load/store.
9639 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9640   if (Level < AfterLegalizeDAG)
9641     return false;
9642
9643   bool isLoad = true;
9644   SDValue Ptr;
9645   EVT VT;
9646   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9647     if (LD->isIndexed())
9648       return false;
9649     VT = LD->getMemoryVT();
9650     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9651         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9652       return false;
9653     Ptr = LD->getBasePtr();
9654   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9655     if (ST->isIndexed())
9656       return false;
9657     VT = ST->getMemoryVT();
9658     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9659         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9660       return false;
9661     Ptr = ST->getBasePtr();
9662     isLoad = false;
9663   } else {
9664     return false;
9665   }
9666
9667   if (Ptr.getNode()->hasOneUse())
9668     return false;
9669
9670   for (SDNode *Op : Ptr.getNode()->uses()) {
9671     if (Op == N ||
9672         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9673       continue;
9674
9675     SDValue BasePtr;
9676     SDValue Offset;
9677     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9678     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9679       // Don't create a indexed load / store with zero offset.
9680       if (isNullConstant(Offset))
9681         continue;
9682
9683       // Try turning it into a post-indexed load / store except when
9684       // 1) All uses are load / store ops that use it as base ptr (and
9685       //    it may be folded as addressing mmode).
9686       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9687       //    nor a successor of N. Otherwise, if Op is folded that would
9688       //    create a cycle.
9689
9690       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9691         continue;
9692
9693       // Check for #1.
9694       bool TryNext = false;
9695       for (SDNode *Use : BasePtr.getNode()->uses()) {
9696         if (Use == Ptr.getNode())
9697           continue;
9698
9699         // If all the uses are load / store addresses, then don't do the
9700         // transformation.
9701         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9702           bool RealUse = false;
9703           for (SDNode *UseUse : Use->uses()) {
9704             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9705               RealUse = true;
9706           }
9707
9708           if (!RealUse) {
9709             TryNext = true;
9710             break;
9711           }
9712         }
9713       }
9714
9715       if (TryNext)
9716         continue;
9717
9718       // Check for #2
9719       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9720         SDValue Result = isLoad
9721           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9722                                BasePtr, Offset, AM)
9723           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9724                                 BasePtr, Offset, AM);
9725         ++PostIndexedNodes;
9726         ++NodesCombined;
9727         DEBUG(dbgs() << "\nReplacing.5 ";
9728               N->dump(&DAG);
9729               dbgs() << "\nWith: ";
9730               Result.getNode()->dump(&DAG);
9731               dbgs() << '\n');
9732         WorklistRemover DeadNodes(*this);
9733         if (isLoad) {
9734           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9735           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9736         } else {
9737           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9738         }
9739
9740         // Finally, since the node is now dead, remove it from the graph.
9741         deleteAndRecombine(N);
9742
9743         // Replace the uses of Use with uses of the updated base value.
9744         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9745                                       Result.getValue(isLoad ? 1 : 0));
9746         deleteAndRecombine(Op);
9747         return true;
9748       }
9749     }
9750   }
9751
9752   return false;
9753 }
9754
9755 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9756 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9757   ISD::MemIndexedMode AM = LD->getAddressingMode();
9758   assert(AM != ISD::UNINDEXED);
9759   SDValue BP = LD->getOperand(1);
9760   SDValue Inc = LD->getOperand(2);
9761
9762   // Some backends use TargetConstants for load offsets, but don't expect
9763   // TargetConstants in general ADD nodes. We can convert these constants into
9764   // regular Constants (if the constant is not opaque).
9765   assert((Inc.getOpcode() != ISD::TargetConstant ||
9766           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9767          "Cannot split out indexing using opaque target constants");
9768   if (Inc.getOpcode() == ISD::TargetConstant) {
9769     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9770     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9771                           ConstInc->getValueType(0));
9772   }
9773
9774   unsigned Opc =
9775       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9776   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9777 }
9778
9779 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9780   LoadSDNode *LD  = cast<LoadSDNode>(N);
9781   SDValue Chain = LD->getChain();
9782   SDValue Ptr   = LD->getBasePtr();
9783
9784   // If load is not volatile and there are no uses of the loaded value (and
9785   // the updated indexed value in case of indexed loads), change uses of the
9786   // chain value into uses of the chain input (i.e. delete the dead load).
9787   if (!LD->isVolatile()) {
9788     if (N->getValueType(1) == MVT::Other) {
9789       // Unindexed loads.
9790       if (!N->hasAnyUseOfValue(0)) {
9791         // It's not safe to use the two value CombineTo variant here. e.g.
9792         // v1, chain2 = load chain1, loc
9793         // v2, chain3 = load chain2, loc
9794         // v3         = add v2, c
9795         // Now we replace use of chain2 with chain1.  This makes the second load
9796         // isomorphic to the one we are deleting, and thus makes this load live.
9797         DEBUG(dbgs() << "\nReplacing.6 ";
9798               N->dump(&DAG);
9799               dbgs() << "\nWith chain: ";
9800               Chain.getNode()->dump(&DAG);
9801               dbgs() << "\n");
9802         WorklistRemover DeadNodes(*this);
9803         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9804
9805         if (N->use_empty())
9806           deleteAndRecombine(N);
9807
9808         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9809       }
9810     } else {
9811       // Indexed loads.
9812       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9813
9814       // If this load has an opaque TargetConstant offset, then we cannot split
9815       // the indexing into an add/sub directly (that TargetConstant may not be
9816       // valid for a different type of node, and we cannot convert an opaque
9817       // target constant into a regular constant).
9818       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9819                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9820
9821       if (!N->hasAnyUseOfValue(0) &&
9822           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9823         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9824         SDValue Index;
9825         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9826           Index = SplitIndexingFromLoad(LD);
9827           // Try to fold the base pointer arithmetic into subsequent loads and
9828           // stores.
9829           AddUsersToWorklist(N);
9830         } else
9831           Index = DAG.getUNDEF(N->getValueType(1));
9832         DEBUG(dbgs() << "\nReplacing.7 ";
9833               N->dump(&DAG);
9834               dbgs() << "\nWith: ";
9835               Undef.getNode()->dump(&DAG);
9836               dbgs() << " and 2 other values\n");
9837         WorklistRemover DeadNodes(*this);
9838         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9839         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9840         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9841         deleteAndRecombine(N);
9842         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9843       }
9844     }
9845   }
9846
9847   // If this load is directly stored, replace the load value with the stored
9848   // value.
9849   // TODO: Handle store large -> read small portion.
9850   // TODO: Handle TRUNCSTORE/LOADEXT
9851   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9852     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9853       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9854       if (PrevST->getBasePtr() == Ptr &&
9855           PrevST->getValue().getValueType() == N->getValueType(0))
9856       return CombineTo(N, Chain.getOperand(1), Chain);
9857     }
9858   }
9859
9860   // Try to infer better alignment information than the load already has.
9861   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9862     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9863       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9864         SDValue NewLoad =
9865                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9866                               LD->getValueType(0),
9867                               Chain, Ptr, LD->getPointerInfo(),
9868                               LD->getMemoryVT(),
9869                               LD->isVolatile(), LD->isNonTemporal(),
9870                               LD->isInvariant(), Align, LD->getAAInfo());
9871         if (NewLoad.getNode() != N)
9872           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9873       }
9874     }
9875   }
9876
9877   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9878                                                   : DAG.getSubtarget().useAA();
9879 #ifndef NDEBUG
9880   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9881       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9882     UseAA = false;
9883 #endif
9884   if (UseAA && LD->isUnindexed()) {
9885     // Walk up chain skipping non-aliasing memory nodes.
9886     SDValue BetterChain = FindBetterChain(N, Chain);
9887
9888     // If there is a better chain.
9889     if (Chain != BetterChain) {
9890       SDValue ReplLoad;
9891
9892       // Replace the chain to void dependency.
9893       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9894         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9895                                BetterChain, Ptr, LD->getMemOperand());
9896       } else {
9897         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9898                                   LD->getValueType(0),
9899                                   BetterChain, Ptr, LD->getMemoryVT(),
9900                                   LD->getMemOperand());
9901       }
9902
9903       // Create token factor to keep old chain connected.
9904       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9905                                   MVT::Other, Chain, ReplLoad.getValue(1));
9906
9907       // Make sure the new and old chains are cleaned up.
9908       AddToWorklist(Token.getNode());
9909
9910       // Replace uses with load result and token factor. Don't add users
9911       // to work list.
9912       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9913     }
9914   }
9915
9916   // Try transforming N to an indexed load.
9917   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9918     return SDValue(N, 0);
9919
9920   // Try to slice up N to more direct loads if the slices are mapped to
9921   // different register banks or pairing can take place.
9922   if (SliceUpLoad(N))
9923     return SDValue(N, 0);
9924
9925   return SDValue();
9926 }
9927
9928 namespace {
9929 /// \brief Helper structure used to slice a load in smaller loads.
9930 /// Basically a slice is obtained from the following sequence:
9931 /// Origin = load Ty1, Base
9932 /// Shift = srl Ty1 Origin, CstTy Amount
9933 /// Inst = trunc Shift to Ty2
9934 ///
9935 /// Then, it will be rewriten into:
9936 /// Slice = load SliceTy, Base + SliceOffset
9937 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9938 ///
9939 /// SliceTy is deduced from the number of bits that are actually used to
9940 /// build Inst.
9941 struct LoadedSlice {
9942   /// \brief Helper structure used to compute the cost of a slice.
9943   struct Cost {
9944     /// Are we optimizing for code size.
9945     bool ForCodeSize;
9946     /// Various cost.
9947     unsigned Loads;
9948     unsigned Truncates;
9949     unsigned CrossRegisterBanksCopies;
9950     unsigned ZExts;
9951     unsigned Shift;
9952
9953     Cost(bool ForCodeSize = false)
9954         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9955           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9956
9957     /// \brief Get the cost of one isolated slice.
9958     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9959         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9960           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9961       EVT TruncType = LS.Inst->getValueType(0);
9962       EVT LoadedType = LS.getLoadedType();
9963       if (TruncType != LoadedType &&
9964           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9965         ZExts = 1;
9966     }
9967
9968     /// \brief Account for slicing gain in the current cost.
9969     /// Slicing provide a few gains like removing a shift or a
9970     /// truncate. This method allows to grow the cost of the original
9971     /// load with the gain from this slice.
9972     void addSliceGain(const LoadedSlice &LS) {
9973       // Each slice saves a truncate.
9974       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9975       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9976                               LS.Inst->getValueType(0)))
9977         ++Truncates;
9978       // If there is a shift amount, this slice gets rid of it.
9979       if (LS.Shift)
9980         ++Shift;
9981       // If this slice can merge a cross register bank copy, account for it.
9982       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9983         ++CrossRegisterBanksCopies;
9984     }
9985
9986     Cost &operator+=(const Cost &RHS) {
9987       Loads += RHS.Loads;
9988       Truncates += RHS.Truncates;
9989       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9990       ZExts += RHS.ZExts;
9991       Shift += RHS.Shift;
9992       return *this;
9993     }
9994
9995     bool operator==(const Cost &RHS) const {
9996       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9997              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9998              ZExts == RHS.ZExts && Shift == RHS.Shift;
9999     }
10000
10001     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
10002
10003     bool operator<(const Cost &RHS) const {
10004       // Assume cross register banks copies are as expensive as loads.
10005       // FIXME: Do we want some more target hooks?
10006       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
10007       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
10008       // Unless we are optimizing for code size, consider the
10009       // expensive operation first.
10010       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
10011         return ExpensiveOpsLHS < ExpensiveOpsRHS;
10012       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
10013              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
10014     }
10015
10016     bool operator>(const Cost &RHS) const { return RHS < *this; }
10017
10018     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
10019
10020     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
10021   };
10022   // The last instruction that represent the slice. This should be a
10023   // truncate instruction.
10024   SDNode *Inst;
10025   // The original load instruction.
10026   LoadSDNode *Origin;
10027   // The right shift amount in bits from the original load.
10028   unsigned Shift;
10029   // The DAG from which Origin came from.
10030   // This is used to get some contextual information about legal types, etc.
10031   SelectionDAG *DAG;
10032
10033   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
10034               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
10035       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10036
10037   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10038   /// \return Result is \p BitWidth and has used bits set to 1 and
10039   ///         not used bits set to 0.
10040   APInt getUsedBits() const {
10041     // Reproduce the trunc(lshr) sequence:
10042     // - Start from the truncated value.
10043     // - Zero extend to the desired bit width.
10044     // - Shift left.
10045     assert(Origin && "No original load to compare against.");
10046     unsigned BitWidth = Origin->getValueSizeInBits(0);
10047     assert(Inst && "This slice is not bound to an instruction");
10048     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10049            "Extracted slice is bigger than the whole type!");
10050     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10051     UsedBits.setAllBits();
10052     UsedBits = UsedBits.zext(BitWidth);
10053     UsedBits <<= Shift;
10054     return UsedBits;
10055   }
10056
10057   /// \brief Get the size of the slice to be loaded in bytes.
10058   unsigned getLoadedSize() const {
10059     unsigned SliceSize = getUsedBits().countPopulation();
10060     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10061     return SliceSize / 8;
10062   }
10063
10064   /// \brief Get the type that will be loaded for this slice.
10065   /// Note: This may not be the final type for the slice.
10066   EVT getLoadedType() const {
10067     assert(DAG && "Missing context");
10068     LLVMContext &Ctxt = *DAG->getContext();
10069     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10070   }
10071
10072   /// \brief Get the alignment of the load used for this slice.
10073   unsigned getAlignment() const {
10074     unsigned Alignment = Origin->getAlignment();
10075     unsigned Offset = getOffsetFromBase();
10076     if (Offset != 0)
10077       Alignment = MinAlign(Alignment, Alignment + Offset);
10078     return Alignment;
10079   }
10080
10081   /// \brief Check if this slice can be rewritten with legal operations.
10082   bool isLegal() const {
10083     // An invalid slice is not legal.
10084     if (!Origin || !Inst || !DAG)
10085       return false;
10086
10087     // Offsets are for indexed load only, we do not handle that.
10088     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10089       return false;
10090
10091     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10092
10093     // Check that the type is legal.
10094     EVT SliceType = getLoadedType();
10095     if (!TLI.isTypeLegal(SliceType))
10096       return false;
10097
10098     // Check that the load is legal for this type.
10099     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10100       return false;
10101
10102     // Check that the offset can be computed.
10103     // 1. Check its type.
10104     EVT PtrType = Origin->getBasePtr().getValueType();
10105     if (PtrType == MVT::Untyped || PtrType.isExtended())
10106       return false;
10107
10108     // 2. Check that it fits in the immediate.
10109     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10110       return false;
10111
10112     // 3. Check that the computation is legal.
10113     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10114       return false;
10115
10116     // Check that the zext is legal if it needs one.
10117     EVT TruncateType = Inst->getValueType(0);
10118     if (TruncateType != SliceType &&
10119         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10120       return false;
10121
10122     return true;
10123   }
10124
10125   /// \brief Get the offset in bytes of this slice in the original chunk of
10126   /// bits.
10127   /// \pre DAG != nullptr.
10128   uint64_t getOffsetFromBase() const {
10129     assert(DAG && "Missing context.");
10130     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10131     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10132     uint64_t Offset = Shift / 8;
10133     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10134     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10135            "The size of the original loaded type is not a multiple of a"
10136            " byte.");
10137     // If Offset is bigger than TySizeInBytes, it means we are loading all
10138     // zeros. This should have been optimized before in the process.
10139     assert(TySizeInBytes > Offset &&
10140            "Invalid shift amount for given loaded size");
10141     if (IsBigEndian)
10142       Offset = TySizeInBytes - Offset - getLoadedSize();
10143     return Offset;
10144   }
10145
10146   /// \brief Generate the sequence of instructions to load the slice
10147   /// represented by this object and redirect the uses of this slice to
10148   /// this new sequence of instructions.
10149   /// \pre this->Inst && this->Origin are valid Instructions and this
10150   /// object passed the legal check: LoadedSlice::isLegal returned true.
10151   /// \return The last instruction of the sequence used to load the slice.
10152   SDValue loadSlice() const {
10153     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10154     const SDValue &OldBaseAddr = Origin->getBasePtr();
10155     SDValue BaseAddr = OldBaseAddr;
10156     // Get the offset in that chunk of bytes w.r.t. the endianess.
10157     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10158     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10159     if (Offset) {
10160       // BaseAddr = BaseAddr + Offset.
10161       EVT ArithType = BaseAddr.getValueType();
10162       SDLoc DL(Origin);
10163       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10164                               DAG->getConstant(Offset, DL, ArithType));
10165     }
10166
10167     // Create the type of the loaded slice according to its size.
10168     EVT SliceType = getLoadedType();
10169
10170     // Create the load for the slice.
10171     SDValue LastInst = DAG->getLoad(
10172         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10173         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10174         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10175     // If the final type is not the same as the loaded type, this means that
10176     // we have to pad with zero. Create a zero extend for that.
10177     EVT FinalType = Inst->getValueType(0);
10178     if (SliceType != FinalType)
10179       LastInst =
10180           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10181     return LastInst;
10182   }
10183
10184   /// \brief Check if this slice can be merged with an expensive cross register
10185   /// bank copy. E.g.,
10186   /// i = load i32
10187   /// f = bitcast i32 i to float
10188   bool canMergeExpensiveCrossRegisterBankCopy() const {
10189     if (!Inst || !Inst->hasOneUse())
10190       return false;
10191     SDNode *Use = *Inst->use_begin();
10192     if (Use->getOpcode() != ISD::BITCAST)
10193       return false;
10194     assert(DAG && "Missing context");
10195     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10196     EVT ResVT = Use->getValueType(0);
10197     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10198     const TargetRegisterClass *ArgRC =
10199         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10200     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10201       return false;
10202
10203     // At this point, we know that we perform a cross-register-bank copy.
10204     // Check if it is expensive.
10205     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10206     // Assume bitcasts are cheap, unless both register classes do not
10207     // explicitly share a common sub class.
10208     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10209       return false;
10210
10211     // Check if it will be merged with the load.
10212     // 1. Check the alignment constraint.
10213     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10214         ResVT.getTypeForEVT(*DAG->getContext()));
10215
10216     if (RequiredAlignment > getAlignment())
10217       return false;
10218
10219     // 2. Check that the load is a legal operation for that type.
10220     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10221       return false;
10222
10223     // 3. Check that we do not have a zext in the way.
10224     if (Inst->getValueType(0) != getLoadedType())
10225       return false;
10226
10227     return true;
10228   }
10229 };
10230 }
10231
10232 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10233 /// \p UsedBits looks like 0..0 1..1 0..0.
10234 static bool areUsedBitsDense(const APInt &UsedBits) {
10235   // If all the bits are one, this is dense!
10236   if (UsedBits.isAllOnesValue())
10237     return true;
10238
10239   // Get rid of the unused bits on the right.
10240   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10241   // Get rid of the unused bits on the left.
10242   if (NarrowedUsedBits.countLeadingZeros())
10243     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10244   // Check that the chunk of bits is completely used.
10245   return NarrowedUsedBits.isAllOnesValue();
10246 }
10247
10248 /// \brief Check whether or not \p First and \p Second are next to each other
10249 /// in memory. This means that there is no hole between the bits loaded
10250 /// by \p First and the bits loaded by \p Second.
10251 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10252                                      const LoadedSlice &Second) {
10253   assert(First.Origin == Second.Origin && First.Origin &&
10254          "Unable to match different memory origins.");
10255   APInt UsedBits = First.getUsedBits();
10256   assert((UsedBits & Second.getUsedBits()) == 0 &&
10257          "Slices are not supposed to overlap.");
10258   UsedBits |= Second.getUsedBits();
10259   return areUsedBitsDense(UsedBits);
10260 }
10261
10262 /// \brief Adjust the \p GlobalLSCost according to the target
10263 /// paring capabilities and the layout of the slices.
10264 /// \pre \p GlobalLSCost should account for at least as many loads as
10265 /// there is in the slices in \p LoadedSlices.
10266 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10267                                  LoadedSlice::Cost &GlobalLSCost) {
10268   unsigned NumberOfSlices = LoadedSlices.size();
10269   // If there is less than 2 elements, no pairing is possible.
10270   if (NumberOfSlices < 2)
10271     return;
10272
10273   // Sort the slices so that elements that are likely to be next to each
10274   // other in memory are next to each other in the list.
10275   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10276             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10277     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10278     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10279   });
10280   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10281   // First (resp. Second) is the first (resp. Second) potentially candidate
10282   // to be placed in a paired load.
10283   const LoadedSlice *First = nullptr;
10284   const LoadedSlice *Second = nullptr;
10285   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10286                 // Set the beginning of the pair.
10287                                                            First = Second) {
10288
10289     Second = &LoadedSlices[CurrSlice];
10290
10291     // If First is NULL, it means we start a new pair.
10292     // Get to the next slice.
10293     if (!First)
10294       continue;
10295
10296     EVT LoadedType = First->getLoadedType();
10297
10298     // If the types of the slices are different, we cannot pair them.
10299     if (LoadedType != Second->getLoadedType())
10300       continue;
10301
10302     // Check if the target supplies paired loads for this type.
10303     unsigned RequiredAlignment = 0;
10304     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10305       // move to the next pair, this type is hopeless.
10306       Second = nullptr;
10307       continue;
10308     }
10309     // Check if we meet the alignment requirement.
10310     if (RequiredAlignment > First->getAlignment())
10311       continue;
10312
10313     // Check that both loads are next to each other in memory.
10314     if (!areSlicesNextToEachOther(*First, *Second))
10315       continue;
10316
10317     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10318     --GlobalLSCost.Loads;
10319     // Move to the next pair.
10320     Second = nullptr;
10321   }
10322 }
10323
10324 /// \brief Check the profitability of all involved LoadedSlice.
10325 /// Currently, it is considered profitable if there is exactly two
10326 /// involved slices (1) which are (2) next to each other in memory, and
10327 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10328 ///
10329 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10330 /// the elements themselves.
10331 ///
10332 /// FIXME: When the cost model will be mature enough, we can relax
10333 /// constraints (1) and (2).
10334 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10335                                 const APInt &UsedBits, bool ForCodeSize) {
10336   unsigned NumberOfSlices = LoadedSlices.size();
10337   if (StressLoadSlicing)
10338     return NumberOfSlices > 1;
10339
10340   // Check (1).
10341   if (NumberOfSlices != 2)
10342     return false;
10343
10344   // Check (2).
10345   if (!areUsedBitsDense(UsedBits))
10346     return false;
10347
10348   // Check (3).
10349   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10350   // The original code has one big load.
10351   OrigCost.Loads = 1;
10352   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10353     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10354     // Accumulate the cost of all the slices.
10355     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10356     GlobalSlicingCost += SliceCost;
10357
10358     // Account as cost in the original configuration the gain obtained
10359     // with the current slices.
10360     OrigCost.addSliceGain(LS);
10361   }
10362
10363   // If the target supports paired load, adjust the cost accordingly.
10364   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10365   return OrigCost > GlobalSlicingCost;
10366 }
10367
10368 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10369 /// operations, split it in the various pieces being extracted.
10370 ///
10371 /// This sort of thing is introduced by SROA.
10372 /// This slicing takes care not to insert overlapping loads.
10373 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10374 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10375   if (Level < AfterLegalizeDAG)
10376     return false;
10377
10378   LoadSDNode *LD = cast<LoadSDNode>(N);
10379   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10380       !LD->getValueType(0).isInteger())
10381     return false;
10382
10383   // Keep track of already used bits to detect overlapping values.
10384   // In that case, we will just abort the transformation.
10385   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10386
10387   SmallVector<LoadedSlice, 4> LoadedSlices;
10388
10389   // Check if this load is used as several smaller chunks of bits.
10390   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10391   // of computation for each trunc.
10392   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10393        UI != UIEnd; ++UI) {
10394     // Skip the uses of the chain.
10395     if (UI.getUse().getResNo() != 0)
10396       continue;
10397
10398     SDNode *User = *UI;
10399     unsigned Shift = 0;
10400
10401     // Check if this is a trunc(lshr).
10402     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10403         isa<ConstantSDNode>(User->getOperand(1))) {
10404       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10405       User = *User->use_begin();
10406     }
10407
10408     // At this point, User is a Truncate, iff we encountered, trunc or
10409     // trunc(lshr).
10410     if (User->getOpcode() != ISD::TRUNCATE)
10411       return false;
10412
10413     // The width of the type must be a power of 2 and greater than 8-bits.
10414     // Otherwise the load cannot be represented in LLVM IR.
10415     // Moreover, if we shifted with a non-8-bits multiple, the slice
10416     // will be across several bytes. We do not support that.
10417     unsigned Width = User->getValueSizeInBits(0);
10418     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10419       return 0;
10420
10421     // Build the slice for this chain of computations.
10422     LoadedSlice LS(User, LD, Shift, &DAG);
10423     APInt CurrentUsedBits = LS.getUsedBits();
10424
10425     // Check if this slice overlaps with another.
10426     if ((CurrentUsedBits & UsedBits) != 0)
10427       return false;
10428     // Update the bits used globally.
10429     UsedBits |= CurrentUsedBits;
10430
10431     // Check if the new slice would be legal.
10432     if (!LS.isLegal())
10433       return false;
10434
10435     // Record the slice.
10436     LoadedSlices.push_back(LS);
10437   }
10438
10439   // Abort slicing if it does not seem to be profitable.
10440   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10441     return false;
10442
10443   ++SlicedLoads;
10444
10445   // Rewrite each chain to use an independent load.
10446   // By construction, each chain can be represented by a unique load.
10447
10448   // Prepare the argument for the new token factor for all the slices.
10449   SmallVector<SDValue, 8> ArgChains;
10450   for (SmallVectorImpl<LoadedSlice>::const_iterator
10451            LSIt = LoadedSlices.begin(),
10452            LSItEnd = LoadedSlices.end();
10453        LSIt != LSItEnd; ++LSIt) {
10454     SDValue SliceInst = LSIt->loadSlice();
10455     CombineTo(LSIt->Inst, SliceInst, true);
10456     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10457       SliceInst = SliceInst.getOperand(0);
10458     assert(SliceInst->getOpcode() == ISD::LOAD &&
10459            "It takes more than a zext to get to the loaded slice!!");
10460     ArgChains.push_back(SliceInst.getValue(1));
10461   }
10462
10463   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10464                               ArgChains);
10465   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10466   return true;
10467 }
10468
10469 /// Check to see if V is (and load (ptr), imm), where the load is having
10470 /// specific bytes cleared out.  If so, return the byte size being masked out
10471 /// and the shift amount.
10472 static std::pair<unsigned, unsigned>
10473 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10474   std::pair<unsigned, unsigned> Result(0, 0);
10475
10476   // Check for the structure we're looking for.
10477   if (V->getOpcode() != ISD::AND ||
10478       !isa<ConstantSDNode>(V->getOperand(1)) ||
10479       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10480     return Result;
10481
10482   // Check the chain and pointer.
10483   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10484   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10485
10486   // The store should be chained directly to the load or be an operand of a
10487   // tokenfactor.
10488   if (LD == Chain.getNode())
10489     ; // ok.
10490   else if (Chain->getOpcode() != ISD::TokenFactor)
10491     return Result; // Fail.
10492   else {
10493     bool isOk = false;
10494     for (const SDValue &ChainOp : Chain->op_values())
10495       if (ChainOp.getNode() == LD) {
10496         isOk = true;
10497         break;
10498       }
10499     if (!isOk) return Result;
10500   }
10501
10502   // This only handles simple types.
10503   if (V.getValueType() != MVT::i16 &&
10504       V.getValueType() != MVT::i32 &&
10505       V.getValueType() != MVT::i64)
10506     return Result;
10507
10508   // Check the constant mask.  Invert it so that the bits being masked out are
10509   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10510   // follow the sign bit for uniformity.
10511   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10512   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10513   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10514   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10515   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10516   if (NotMaskLZ == 64) return Result;  // All zero mask.
10517
10518   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10519   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10520     return Result;
10521
10522   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10523   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10524     NotMaskLZ -= 64-V.getValueSizeInBits();
10525
10526   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10527   switch (MaskedBytes) {
10528   case 1:
10529   case 2:
10530   case 4: break;
10531   default: return Result; // All one mask, or 5-byte mask.
10532   }
10533
10534   // Verify that the first bit starts at a multiple of mask so that the access
10535   // is aligned the same as the access width.
10536   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10537
10538   Result.first = MaskedBytes;
10539   Result.second = NotMaskTZ/8;
10540   return Result;
10541 }
10542
10543
10544 /// Check to see if IVal is something that provides a value as specified by
10545 /// MaskInfo. If so, replace the specified store with a narrower store of
10546 /// truncated IVal.
10547 static SDNode *
10548 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10549                                 SDValue IVal, StoreSDNode *St,
10550                                 DAGCombiner *DC) {
10551   unsigned NumBytes = MaskInfo.first;
10552   unsigned ByteShift = MaskInfo.second;
10553   SelectionDAG &DAG = DC->getDAG();
10554
10555   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10556   // that uses this.  If not, this is not a replacement.
10557   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10558                                   ByteShift*8, (ByteShift+NumBytes)*8);
10559   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10560
10561   // Check that it is legal on the target to do this.  It is legal if the new
10562   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10563   // legalization.
10564   MVT VT = MVT::getIntegerVT(NumBytes*8);
10565   if (!DC->isTypeLegal(VT))
10566     return nullptr;
10567
10568   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10569   // shifted by ByteShift and truncated down to NumBytes.
10570   if (ByteShift) {
10571     SDLoc DL(IVal);
10572     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10573                        DAG.getConstant(ByteShift*8, DL,
10574                                     DC->getShiftAmountTy(IVal.getValueType())));
10575   }
10576
10577   // Figure out the offset for the store and the alignment of the access.
10578   unsigned StOffset;
10579   unsigned NewAlign = St->getAlignment();
10580
10581   if (DAG.getDataLayout().isLittleEndian())
10582     StOffset = ByteShift;
10583   else
10584     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10585
10586   SDValue Ptr = St->getBasePtr();
10587   if (StOffset) {
10588     SDLoc DL(IVal);
10589     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10590                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10591     NewAlign = MinAlign(NewAlign, StOffset);
10592   }
10593
10594   // Truncate down to the new size.
10595   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10596
10597   ++OpsNarrowed;
10598   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10599                       St->getPointerInfo().getWithOffset(StOffset),
10600                       false, false, NewAlign).getNode();
10601 }
10602
10603
10604 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10605 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10606 /// narrowing the load and store if it would end up being a win for performance
10607 /// or code size.
10608 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10609   StoreSDNode *ST  = cast<StoreSDNode>(N);
10610   if (ST->isVolatile())
10611     return SDValue();
10612
10613   SDValue Chain = ST->getChain();
10614   SDValue Value = ST->getValue();
10615   SDValue Ptr   = ST->getBasePtr();
10616   EVT VT = Value.getValueType();
10617
10618   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10619     return SDValue();
10620
10621   unsigned Opc = Value.getOpcode();
10622
10623   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10624   // is a byte mask indicating a consecutive number of bytes, check to see if
10625   // Y is known to provide just those bytes.  If so, we try to replace the
10626   // load + replace + store sequence with a single (narrower) store, which makes
10627   // the load dead.
10628   if (Opc == ISD::OR) {
10629     std::pair<unsigned, unsigned> MaskedLoad;
10630     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10631     if (MaskedLoad.first)
10632       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10633                                                   Value.getOperand(1), ST,this))
10634         return SDValue(NewST, 0);
10635
10636     // Or is commutative, so try swapping X and Y.
10637     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10638     if (MaskedLoad.first)
10639       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10640                                                   Value.getOperand(0), ST,this))
10641         return SDValue(NewST, 0);
10642   }
10643
10644   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10645       Value.getOperand(1).getOpcode() != ISD::Constant)
10646     return SDValue();
10647
10648   SDValue N0 = Value.getOperand(0);
10649   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10650       Chain == SDValue(N0.getNode(), 1)) {
10651     LoadSDNode *LD = cast<LoadSDNode>(N0);
10652     if (LD->getBasePtr() != Ptr ||
10653         LD->getPointerInfo().getAddrSpace() !=
10654         ST->getPointerInfo().getAddrSpace())
10655       return SDValue();
10656
10657     // Find the type to narrow it the load / op / store to.
10658     SDValue N1 = Value.getOperand(1);
10659     unsigned BitWidth = N1.getValueSizeInBits();
10660     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10661     if (Opc == ISD::AND)
10662       Imm ^= APInt::getAllOnesValue(BitWidth);
10663     if (Imm == 0 || Imm.isAllOnesValue())
10664       return SDValue();
10665     unsigned ShAmt = Imm.countTrailingZeros();
10666     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10667     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10668     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10669     // The narrowing should be profitable, the load/store operation should be
10670     // legal (or custom) and the store size should be equal to the NewVT width.
10671     while (NewBW < BitWidth &&
10672            (NewVT.getStoreSizeInBits() != NewBW ||
10673             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10674             !TLI.isNarrowingProfitable(VT, NewVT))) {
10675       NewBW = NextPowerOf2(NewBW);
10676       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10677     }
10678     if (NewBW >= BitWidth)
10679       return SDValue();
10680
10681     // If the lsb changed does not start at the type bitwidth boundary,
10682     // start at the previous one.
10683     if (ShAmt % NewBW)
10684       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10685     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10686                                    std::min(BitWidth, ShAmt + NewBW));
10687     if ((Imm & Mask) == Imm) {
10688       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10689       if (Opc == ISD::AND)
10690         NewImm ^= APInt::getAllOnesValue(NewBW);
10691       uint64_t PtrOff = ShAmt / 8;
10692       // For big endian targets, we need to adjust the offset to the pointer to
10693       // load the correct bytes.
10694       if (DAG.getDataLayout().isBigEndian())
10695         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10696
10697       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10698       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10699       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10700         return SDValue();
10701
10702       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10703                                    Ptr.getValueType(), Ptr,
10704                                    DAG.getConstant(PtrOff, SDLoc(LD),
10705                                                    Ptr.getValueType()));
10706       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10707                                   LD->getChain(), NewPtr,
10708                                   LD->getPointerInfo().getWithOffset(PtrOff),
10709                                   LD->isVolatile(), LD->isNonTemporal(),
10710                                   LD->isInvariant(), NewAlign,
10711                                   LD->getAAInfo());
10712       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10713                                    DAG.getConstant(NewImm, SDLoc(Value),
10714                                                    NewVT));
10715       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10716                                    NewVal, NewPtr,
10717                                    ST->getPointerInfo().getWithOffset(PtrOff),
10718                                    false, false, NewAlign);
10719
10720       AddToWorklist(NewPtr.getNode());
10721       AddToWorklist(NewLD.getNode());
10722       AddToWorklist(NewVal.getNode());
10723       WorklistRemover DeadNodes(*this);
10724       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10725       ++OpsNarrowed;
10726       return NewST;
10727     }
10728   }
10729
10730   return SDValue();
10731 }
10732
10733 /// For a given floating point load / store pair, if the load value isn't used
10734 /// by any other operations, then consider transforming the pair to integer
10735 /// load / store operations if the target deems the transformation profitable.
10736 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10737   StoreSDNode *ST  = cast<StoreSDNode>(N);
10738   SDValue Chain = ST->getChain();
10739   SDValue Value = ST->getValue();
10740   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10741       Value.hasOneUse() &&
10742       Chain == SDValue(Value.getNode(), 1)) {
10743     LoadSDNode *LD = cast<LoadSDNode>(Value);
10744     EVT VT = LD->getMemoryVT();
10745     if (!VT.isFloatingPoint() ||
10746         VT != ST->getMemoryVT() ||
10747         LD->isNonTemporal() ||
10748         ST->isNonTemporal() ||
10749         LD->getPointerInfo().getAddrSpace() != 0 ||
10750         ST->getPointerInfo().getAddrSpace() != 0)
10751       return SDValue();
10752
10753     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10754     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10755         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10756         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10757         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10758       return SDValue();
10759
10760     unsigned LDAlign = LD->getAlignment();
10761     unsigned STAlign = ST->getAlignment();
10762     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10763     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10764     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10765       return SDValue();
10766
10767     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10768                                 LD->getChain(), LD->getBasePtr(),
10769                                 LD->getPointerInfo(),
10770                                 false, false, false, LDAlign);
10771
10772     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10773                                  NewLD, ST->getBasePtr(),
10774                                  ST->getPointerInfo(),
10775                                  false, false, STAlign);
10776
10777     AddToWorklist(NewLD.getNode());
10778     AddToWorklist(NewST.getNode());
10779     WorklistRemover DeadNodes(*this);
10780     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10781     ++LdStFP2Int;
10782     return NewST;
10783   }
10784
10785   return SDValue();
10786 }
10787
10788 namespace {
10789 /// Helper struct to parse and store a memory address as base + index + offset.
10790 /// We ignore sign extensions when it is safe to do so.
10791 /// The following two expressions are not equivalent. To differentiate we need
10792 /// to store whether there was a sign extension involved in the index
10793 /// computation.
10794 ///  (load (i64 add (i64 copyfromreg %c)
10795 ///                 (i64 signextend (add (i8 load %index)
10796 ///                                      (i8 1))))
10797 /// vs
10798 ///
10799 /// (load (i64 add (i64 copyfromreg %c)
10800 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10801 ///                                         (i32 1)))))
10802 struct BaseIndexOffset {
10803   SDValue Base;
10804   SDValue Index;
10805   int64_t Offset;
10806   bool IsIndexSignExt;
10807
10808   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10809
10810   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10811                   bool IsIndexSignExt) :
10812     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10813
10814   bool equalBaseIndex(const BaseIndexOffset &Other) {
10815     return Other.Base == Base && Other.Index == Index &&
10816       Other.IsIndexSignExt == IsIndexSignExt;
10817   }
10818
10819   /// Parses tree in Ptr for base, index, offset addresses.
10820   static BaseIndexOffset match(SDValue Ptr) {
10821     bool IsIndexSignExt = false;
10822
10823     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10824     // instruction, then it could be just the BASE or everything else we don't
10825     // know how to handle. Just use Ptr as BASE and give up.
10826     if (Ptr->getOpcode() != ISD::ADD)
10827       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10828
10829     // We know that we have at least an ADD instruction. Try to pattern match
10830     // the simple case of BASE + OFFSET.
10831     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10832       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10833       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10834                               IsIndexSignExt);
10835     }
10836
10837     // Inside a loop the current BASE pointer is calculated using an ADD and a
10838     // MUL instruction. In this case Ptr is the actual BASE pointer.
10839     // (i64 add (i64 %array_ptr)
10840     //          (i64 mul (i64 %induction_var)
10841     //                   (i64 %element_size)))
10842     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10843       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10844
10845     // Look at Base + Index + Offset cases.
10846     SDValue Base = Ptr->getOperand(0);
10847     SDValue IndexOffset = Ptr->getOperand(1);
10848
10849     // Skip signextends.
10850     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10851       IndexOffset = IndexOffset->getOperand(0);
10852       IsIndexSignExt = true;
10853     }
10854
10855     // Either the case of Base + Index (no offset) or something else.
10856     if (IndexOffset->getOpcode() != ISD::ADD)
10857       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10858
10859     // Now we have the case of Base + Index + offset.
10860     SDValue Index = IndexOffset->getOperand(0);
10861     SDValue Offset = IndexOffset->getOperand(1);
10862
10863     if (!isa<ConstantSDNode>(Offset))
10864       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10865
10866     // Ignore signextends.
10867     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10868       Index = Index->getOperand(0);
10869       IsIndexSignExt = true;
10870     } else IsIndexSignExt = false;
10871
10872     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10873     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10874   }
10875 };
10876 } // namespace
10877
10878 // This is a helper function for visitMUL to check the profitability
10879 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
10880 // MulNode is the original multiply, AddNode is (add x, c1),
10881 // and ConstNode is c2.
10882 //
10883 // If the (add x, c1) has multiple uses, we could increase
10884 // the number of adds if we make this transformation.
10885 // It would only be worth doing this if we can remove a
10886 // multiply in the process. Check for that here.
10887 // To illustrate:
10888 //     (A + c1) * c3
10889 //     (A + c2) * c3
10890 // We're checking for cases where we have common "c3 * A" expressions.
10891 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
10892                                               SDValue &AddNode,
10893                                               SDValue &ConstNode) {
10894   APInt Val;
10895
10896   // If the add only has one use, this would be OK to do.
10897   if (AddNode.getNode()->hasOneUse())
10898     return true;
10899
10900   // Walk all the users of the constant with which we're multiplying.
10901   for (SDNode *Use : ConstNode->uses()) {
10902
10903     if (Use == MulNode) // This use is the one we're on right now. Skip it.
10904       continue;
10905
10906     if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
10907       SDNode *OtherOp;
10908       SDNode *MulVar = AddNode.getOperand(0).getNode();
10909
10910       // OtherOp is what we're multiplying against the constant.
10911       if (Use->getOperand(0) == ConstNode)
10912         OtherOp = Use->getOperand(1).getNode();
10913       else
10914         OtherOp = Use->getOperand(0).getNode();
10915
10916       // Check to see if multiply is with the same operand of our "add".
10917       //
10918       //     ConstNode  = CONST
10919       //     Use = ConstNode * A  <-- visiting Use. OtherOp is A.
10920       //     ...
10921       //     AddNode  = (A + c1)  <-- MulVar is A.
10922       //         = AddNode * ConstNode   <-- current visiting instruction.
10923       //
10924       // If we make this transformation, we will have a common
10925       // multiply (ConstNode * A) that we can save.
10926       if (OtherOp == MulVar)
10927         return true;
10928
10929       // Now check to see if a future expansion will give us a common
10930       // multiply.
10931       //
10932       //     ConstNode  = CONST
10933       //     AddNode    = (A + c1)
10934       //     ...   = AddNode * ConstNode <-- current visiting instruction.
10935       //     ...
10936       //     OtherOp = (A + c2)
10937       //     Use     = OtherOp * ConstNode <-- visiting Use.
10938       //
10939       // If we make this transformation, we will have a common
10940       // multiply (CONST * A) after we also do the same transformation
10941       // to the "t2" instruction.
10942       if (OtherOp->getOpcode() == ISD::ADD &&
10943           isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
10944           OtherOp->getOperand(0).getNode() == MulVar)
10945         return true;
10946     }
10947   }
10948
10949   // Didn't find a case where this would be profitable.
10950   return false;
10951 }
10952
10953 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10954                                                   SDLoc SL,
10955                                                   ArrayRef<MemOpLink> Stores,
10956                                                   SmallVectorImpl<SDValue> &Chains,
10957                                                   EVT Ty) const {
10958   SmallVector<SDValue, 8> BuildVector;
10959
10960   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10961     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10962     Chains.push_back(St->getChain());
10963     BuildVector.push_back(St->getValue());
10964   }
10965
10966   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10967 }
10968
10969 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10970                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10971                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10972   // Make sure we have something to merge.
10973   if (NumStores < 2)
10974     return false;
10975
10976   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10977   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10978   unsigned LatestNodeUsed = 0;
10979
10980   for (unsigned i=0; i < NumStores; ++i) {
10981     // Find a chain for the new wide-store operand. Notice that some
10982     // of the store nodes that we found may not be selected for inclusion
10983     // in the wide store. The chain we use needs to be the chain of the
10984     // latest store node which is *used* and replaced by the wide store.
10985     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10986       LatestNodeUsed = i;
10987   }
10988
10989   SmallVector<SDValue, 8> Chains;
10990
10991   // The latest Node in the DAG.
10992   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10993   SDLoc DL(StoreNodes[0].MemNode);
10994
10995   SDValue StoredVal;
10996   if (UseVector) {
10997     bool IsVec = MemVT.isVector();
10998     unsigned Elts = NumStores;
10999     if (IsVec) {
11000       // When merging vector stores, get the total number of elements.
11001       Elts *= MemVT.getVectorNumElements();
11002     }
11003     // Get the type for the merged vector store.
11004     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11005     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
11006
11007     if (IsConstantSrc) {
11008       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
11009     } else {
11010       SmallVector<SDValue, 8> Ops;
11011       for (unsigned i = 0; i < NumStores; ++i) {
11012         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11013         SDValue Val = St->getValue();
11014         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
11015         if (Val.getValueType() != MemVT)
11016           return false;
11017         Ops.push_back(Val);
11018         Chains.push_back(St->getChain());
11019       }
11020
11021       // Build the extracted vector elements back into a vector.
11022       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
11023                               DL, Ty, Ops);    }
11024   } else {
11025     // We should always use a vector store when merging extracted vector
11026     // elements, so this path implies a store of constants.
11027     assert(IsConstantSrc && "Merged vector elements should use vector store");
11028
11029     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
11030     APInt StoreInt(SizeInBits, 0);
11031
11032     // Construct a single integer constant which is made of the smaller
11033     // constant inputs.
11034     bool IsLE = DAG.getDataLayout().isLittleEndian();
11035     for (unsigned i = 0; i < NumStores; ++i) {
11036       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
11037       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
11038       Chains.push_back(St->getChain());
11039
11040       SDValue Val = St->getValue();
11041       StoreInt <<= ElementSizeBytes * 8;
11042       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
11043         StoreInt |= C->getAPIntValue().zext(SizeInBits);
11044       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
11045         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
11046       } else {
11047         llvm_unreachable("Invalid constant element type");
11048       }
11049     }
11050
11051     // Create the new Load and Store operations.
11052     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11053     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
11054   }
11055
11056   assert(!Chains.empty());
11057
11058   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11059   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
11060                                   FirstInChain->getBasePtr(),
11061                                   FirstInChain->getPointerInfo(),
11062                                   false, false,
11063                                   FirstInChain->getAlignment());
11064
11065   // Replace the last store with the new store
11066   CombineTo(LatestOp, NewStore);
11067   // Erase all other stores.
11068   for (unsigned i = 0; i < NumStores; ++i) {
11069     if (StoreNodes[i].MemNode == LatestOp)
11070       continue;
11071     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11072     // ReplaceAllUsesWith will replace all uses that existed when it was
11073     // called, but graph optimizations may cause new ones to appear. For
11074     // example, the case in pr14333 looks like
11075     //
11076     //  St's chain -> St -> another store -> X
11077     //
11078     // And the only difference from St to the other store is the chain.
11079     // When we change it's chain to be St's chain they become identical,
11080     // get CSEed and the net result is that X is now a use of St.
11081     // Since we know that St is redundant, just iterate.
11082     while (!St->use_empty())
11083       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
11084     deleteAndRecombine(St);
11085   }
11086
11087   return true;
11088 }
11089
11090 void DAGCombiner::getStoreMergeAndAliasCandidates(
11091     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
11092     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
11093   // This holds the base pointer, index, and the offset in bytes from the base
11094   // pointer.
11095   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
11096
11097   // We must have a base and an offset.
11098   if (!BasePtr.Base.getNode())
11099     return;
11100
11101   // Do not handle stores to undef base pointers.
11102   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
11103     return;
11104
11105   // Walk up the chain and look for nodes with offsets from the same
11106   // base pointer. Stop when reaching an instruction with a different kind
11107   // or instruction which has a different base pointer.
11108   EVT MemVT = St->getMemoryVT();
11109   unsigned Seq = 0;
11110   StoreSDNode *Index = St;
11111
11112
11113   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11114                                                   : DAG.getSubtarget().useAA();
11115
11116   if (UseAA) {
11117     // Look at other users of the same chain. Stores on the same chain do not
11118     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11119     // to be on the same chain, so don't bother looking at adjacent chains.
11120
11121     SDValue Chain = St->getChain();
11122     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11123       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11124         if (I.getOperandNo() != 0)
11125           continue;
11126
11127         if (OtherST->isVolatile() || OtherST->isIndexed())
11128           continue;
11129
11130         if (OtherST->getMemoryVT() != MemVT)
11131           continue;
11132
11133         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11134
11135         if (Ptr.equalBaseIndex(BasePtr))
11136           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11137       }
11138     }
11139
11140     return;
11141   }
11142
11143   while (Index) {
11144     // If the chain has more than one use, then we can't reorder the mem ops.
11145     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11146       break;
11147
11148     // Find the base pointer and offset for this memory node.
11149     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11150
11151     // Check that the base pointer is the same as the original one.
11152     if (!Ptr.equalBaseIndex(BasePtr))
11153       break;
11154
11155     // The memory operands must not be volatile.
11156     if (Index->isVolatile() || Index->isIndexed())
11157       break;
11158
11159     // No truncation.
11160     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11161       if (St->isTruncatingStore())
11162         break;
11163
11164     // The stored memory type must be the same.
11165     if (Index->getMemoryVT() != MemVT)
11166       break;
11167
11168     // We found a potential memory operand to merge.
11169     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11170
11171     // Find the next memory operand in the chain. If the next operand in the
11172     // chain is a store then move up and continue the scan with the next
11173     // memory operand. If the next operand is a load save it and use alias
11174     // information to check if it interferes with anything.
11175     SDNode *NextInChain = Index->getChain().getNode();
11176     while (1) {
11177       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11178         // We found a store node. Use it for the next iteration.
11179         Index = STn;
11180         break;
11181       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11182         if (Ldn->isVolatile()) {
11183           Index = nullptr;
11184           break;
11185         }
11186
11187         // Save the load node for later. Continue the scan.
11188         AliasLoadNodes.push_back(Ldn);
11189         NextInChain = Ldn->getChain().getNode();
11190         continue;
11191       } else {
11192         Index = nullptr;
11193         break;
11194       }
11195     }
11196   }
11197 }
11198
11199 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11200   if (OptLevel == CodeGenOpt::None)
11201     return false;
11202
11203   EVT MemVT = St->getMemoryVT();
11204   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11205   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11206       Attribute::NoImplicitFloat);
11207
11208   // This function cannot currently deal with non-byte-sized memory sizes.
11209   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11210     return false;
11211
11212   if (!MemVT.isSimple())
11213     return false;
11214
11215   // Perform an early exit check. Do not bother looking at stored values that
11216   // are not constants, loads, or extracted vector elements.
11217   SDValue StoredVal = St->getValue();
11218   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11219   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11220                        isa<ConstantFPSDNode>(StoredVal);
11221   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11222                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11223
11224   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11225     return false;
11226
11227   // Don't merge vectors into wider vectors if the source data comes from loads.
11228   // TODO: This restriction can be lifted by using logic similar to the
11229   // ExtractVecSrc case.
11230   if (MemVT.isVector() && IsLoadSrc)
11231     return false;
11232
11233   // Only look at ends of store sequences.
11234   SDValue Chain = SDValue(St, 0);
11235   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11236     return false;
11237
11238   // Save the LoadSDNodes that we find in the chain.
11239   // We need to make sure that these nodes do not interfere with
11240   // any of the store nodes.
11241   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11242
11243   // Save the StoreSDNodes that we find in the chain.
11244   SmallVector<MemOpLink, 8> StoreNodes;
11245
11246   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11247
11248   // Check if there is anything to merge.
11249   if (StoreNodes.size() < 2)
11250     return false;
11251
11252   // Sort the memory operands according to their distance from the base pointer.
11253   std::sort(StoreNodes.begin(), StoreNodes.end(),
11254             [](MemOpLink LHS, MemOpLink RHS) {
11255     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11256            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11257             LHS.SequenceNum > RHS.SequenceNum);
11258   });
11259
11260   // Scan the memory operations on the chain and find the first non-consecutive
11261   // store memory address.
11262   unsigned LastConsecutiveStore = 0;
11263   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11264   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11265
11266     // Check that the addresses are consecutive starting from the second
11267     // element in the list of stores.
11268     if (i > 0) {
11269       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11270       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11271         break;
11272     }
11273
11274     bool Alias = false;
11275     // Check if this store interferes with any of the loads that we found.
11276     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11277       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11278         Alias = true;
11279         break;
11280       }
11281     // We found a load that alias with this store. Stop the sequence.
11282     if (Alias)
11283       break;
11284
11285     // Mark this node as useful.
11286     LastConsecutiveStore = i;
11287   }
11288
11289   // The node with the lowest store address.
11290   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11291   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11292   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11293   LLVMContext &Context = *DAG.getContext();
11294   const DataLayout &DL = DAG.getDataLayout();
11295
11296   // Store the constants into memory as one consecutive store.
11297   if (IsConstantSrc) {
11298     unsigned LastLegalType = 0;
11299     unsigned LastLegalVectorType = 0;
11300     bool NonZero = false;
11301     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11302       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11303       SDValue StoredVal = St->getValue();
11304
11305       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11306         NonZero |= !C->isNullValue();
11307       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11308         NonZero |= !C->getConstantFPValue()->isNullValue();
11309       } else {
11310         // Non-constant.
11311         break;
11312       }
11313
11314       // Find a legal type for the constant store.
11315       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11316       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11317       bool IsFast;
11318       if (TLI.isTypeLegal(StoreTy) &&
11319           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11320                                  FirstStoreAlign, &IsFast) && IsFast) {
11321         LastLegalType = i+1;
11322       // Or check whether a truncstore is legal.
11323       } else if (TLI.getTypeAction(Context, StoreTy) ==
11324                  TargetLowering::TypePromoteInteger) {
11325         EVT LegalizedStoredValueTy =
11326           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11327         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11328             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11329                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11330             IsFast) {
11331           LastLegalType = i + 1;
11332         }
11333       }
11334
11335       // We only use vectors if the constant is known to be zero or the target
11336       // allows it and the function is not marked with the noimplicitfloat
11337       // attribute.
11338       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11339                                                         FirstStoreAS)) &&
11340           !NoVectors) {
11341         // Find a legal type for the vector store.
11342         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11343         if (TLI.isTypeLegal(Ty) &&
11344             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11345                                    FirstStoreAlign, &IsFast) && IsFast)
11346           LastLegalVectorType = i + 1;
11347       }
11348     }
11349
11350     // Check if we found a legal integer type to store.
11351     if (LastLegalType == 0 && LastLegalVectorType == 0)
11352       return false;
11353
11354     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11355     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11356
11357     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11358                                            true, UseVector);
11359   }
11360
11361   // When extracting multiple vector elements, try to store them
11362   // in one vector store rather than a sequence of scalar stores.
11363   if (IsExtractVecSrc) {
11364     unsigned NumStoresToMerge = 0;
11365     bool IsVec = MemVT.isVector();
11366     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11367       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11368       unsigned StoreValOpcode = St->getValue().getOpcode();
11369       // This restriction could be loosened.
11370       // Bail out if any stored values are not elements extracted from a vector.
11371       // It should be possible to handle mixed sources, but load sources need
11372       // more careful handling (see the block of code below that handles
11373       // consecutive loads).
11374       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11375           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11376         return false;
11377
11378       // Find a legal type for the vector store.
11379       unsigned Elts = i + 1;
11380       if (IsVec) {
11381         // When merging vector stores, get the total number of elements.
11382         Elts *= MemVT.getVectorNumElements();
11383       }
11384       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11385       bool IsFast;
11386       if (TLI.isTypeLegal(Ty) &&
11387           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11388                                  FirstStoreAlign, &IsFast) && IsFast)
11389         NumStoresToMerge = i + 1;
11390     }
11391
11392     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11393                                            false, true);
11394   }
11395
11396   // Below we handle the case of multiple consecutive stores that
11397   // come from multiple consecutive loads. We merge them into a single
11398   // wide load and a single wide store.
11399
11400   // Look for load nodes which are used by the stored values.
11401   SmallVector<MemOpLink, 8> LoadNodes;
11402
11403   // Find acceptable loads. Loads need to have the same chain (token factor),
11404   // must not be zext, volatile, indexed, and they must be consecutive.
11405   BaseIndexOffset LdBasePtr;
11406   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11407     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11408     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11409     if (!Ld) break;
11410
11411     // Loads must only have one use.
11412     if (!Ld->hasNUsesOfValue(1, 0))
11413       break;
11414
11415     // The memory operands must not be volatile.
11416     if (Ld->isVolatile() || Ld->isIndexed())
11417       break;
11418
11419     // We do not accept ext loads.
11420     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11421       break;
11422
11423     // The stored memory type must be the same.
11424     if (Ld->getMemoryVT() != MemVT)
11425       break;
11426
11427     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11428     // If this is not the first ptr that we check.
11429     if (LdBasePtr.Base.getNode()) {
11430       // The base ptr must be the same.
11431       if (!LdPtr.equalBaseIndex(LdBasePtr))
11432         break;
11433     } else {
11434       // Check that all other base pointers are the same as this one.
11435       LdBasePtr = LdPtr;
11436     }
11437
11438     // We found a potential memory operand to merge.
11439     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11440   }
11441
11442   if (LoadNodes.size() < 2)
11443     return false;
11444
11445   // If we have load/store pair instructions and we only have two values,
11446   // don't bother.
11447   unsigned RequiredAlignment;
11448   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11449       St->getAlignment() >= RequiredAlignment)
11450     return false;
11451
11452   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11453   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11454   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11455
11456   // Scan the memory operations on the chain and find the first non-consecutive
11457   // load memory address. These variables hold the index in the store node
11458   // array.
11459   unsigned LastConsecutiveLoad = 0;
11460   // This variable refers to the size and not index in the array.
11461   unsigned LastLegalVectorType = 0;
11462   unsigned LastLegalIntegerType = 0;
11463   StartAddress = LoadNodes[0].OffsetFromBase;
11464   SDValue FirstChain = FirstLoad->getChain();
11465   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11466     // All loads much share the same chain.
11467     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11468       break;
11469
11470     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11471     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11472       break;
11473     LastConsecutiveLoad = i;
11474     // Find a legal type for the vector store.
11475     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11476     bool IsFastSt, IsFastLd;
11477     if (TLI.isTypeLegal(StoreTy) &&
11478         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11479                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11480         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11481                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11482       LastLegalVectorType = i + 1;
11483     }
11484
11485     // Find a legal type for the integer store.
11486     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11487     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11488     if (TLI.isTypeLegal(StoreTy) &&
11489         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11490                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11491         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11492                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11493       LastLegalIntegerType = i + 1;
11494     // Or check whether a truncstore and extload is legal.
11495     else if (TLI.getTypeAction(Context, StoreTy) ==
11496              TargetLowering::TypePromoteInteger) {
11497       EVT LegalizedStoredValueTy =
11498         TLI.getTypeToTransformTo(Context, StoreTy);
11499       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11500           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11501           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11502           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11503           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11504                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11505           IsFastSt &&
11506           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11507                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11508           IsFastLd)
11509         LastLegalIntegerType = i+1;
11510     }
11511   }
11512
11513   // Only use vector types if the vector type is larger than the integer type.
11514   // If they are the same, use integers.
11515   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11516   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11517
11518   // We add +1 here because the LastXXX variables refer to location while
11519   // the NumElem refers to array/index size.
11520   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11521   NumElem = std::min(LastLegalType, NumElem);
11522
11523   if (NumElem < 2)
11524     return false;
11525
11526   // Collect the chains from all merged stores.
11527   SmallVector<SDValue, 8> MergeStoreChains;
11528   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11529
11530   // The latest Node in the DAG.
11531   unsigned LatestNodeUsed = 0;
11532   for (unsigned i=1; i<NumElem; ++i) {
11533     // Find a chain for the new wide-store operand. Notice that some
11534     // of the store nodes that we found may not be selected for inclusion
11535     // in the wide store. The chain we use needs to be the chain of the
11536     // latest store node which is *used* and replaced by the wide store.
11537     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11538       LatestNodeUsed = i;
11539
11540     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11541   }
11542
11543   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11544
11545   // Find if it is better to use vectors or integers to load and store
11546   // to memory.
11547   EVT JointMemOpVT;
11548   if (UseVectorTy) {
11549     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11550   } else {
11551     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11552     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11553   }
11554
11555   SDLoc LoadDL(LoadNodes[0].MemNode);
11556   SDLoc StoreDL(StoreNodes[0].MemNode);
11557
11558   // The merged loads are required to have the same chain, so using the first's
11559   // chain is acceptable.
11560   SDValue NewLoad = DAG.getLoad(
11561       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11562       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11563
11564   SDValue NewStoreChain =
11565     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11566
11567   SDValue NewStore = DAG.getStore(
11568     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11569       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11570
11571   // Replace one of the loads with the new load.
11572   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11573   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11574                                 SDValue(NewLoad.getNode(), 1));
11575
11576   // Remove the rest of the load chains.
11577   for (unsigned i = 1; i < NumElem ; ++i) {
11578     // Replace all chain users of the old load nodes with the chain of the new
11579     // load node.
11580     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11581     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11582   }
11583
11584   // Replace the last store with the new store.
11585   CombineTo(LatestOp, NewStore);
11586   // Erase all other stores.
11587   for (unsigned i = 0; i < NumElem ; ++i) {
11588     // Remove all Store nodes.
11589     if (StoreNodes[i].MemNode == LatestOp)
11590       continue;
11591     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11592     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11593     deleteAndRecombine(St);
11594   }
11595
11596   return true;
11597 }
11598
11599 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11600   SDLoc SL(ST);
11601   SDValue ReplStore;
11602
11603   // Replace the chain to avoid dependency.
11604   if (ST->isTruncatingStore()) {
11605     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11606                                   ST->getBasePtr(), ST->getMemoryVT(),
11607                                   ST->getMemOperand());
11608   } else {
11609     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11610                              ST->getMemOperand());
11611   }
11612
11613   // Create token to keep both nodes around.
11614   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11615                               MVT::Other, ST->getChain(), ReplStore);
11616
11617   // Make sure the new and old chains are cleaned up.
11618   AddToWorklist(Token.getNode());
11619
11620   // Don't add users to work list.
11621   return CombineTo(ST, Token, false);
11622 }
11623
11624 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11625   SDValue Value = ST->getValue();
11626   if (Value.getOpcode() == ISD::TargetConstantFP)
11627     return SDValue();
11628
11629   SDLoc DL(ST);
11630
11631   SDValue Chain = ST->getChain();
11632   SDValue Ptr = ST->getBasePtr();
11633
11634   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11635
11636   // NOTE: If the original store is volatile, this transform must not increase
11637   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11638   // processor operation but an i64 (which is not legal) requires two.  So the
11639   // transform should not be done in this case.
11640
11641   SDValue Tmp;
11642   switch (CFP->getSimpleValueType(0).SimpleTy) {
11643   default:
11644     llvm_unreachable("Unknown FP type");
11645   case MVT::f16:    // We don't do this for these yet.
11646   case MVT::f80:
11647   case MVT::f128:
11648   case MVT::ppcf128:
11649     return SDValue();
11650   case MVT::f32:
11651     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11652         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11653       ;
11654       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11655                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11656                             MVT::i32);
11657       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11658     }
11659
11660     return SDValue();
11661   case MVT::f64:
11662     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11663          !ST->isVolatile()) ||
11664         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11665       ;
11666       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11667                             getZExtValue(), SDLoc(CFP), MVT::i64);
11668       return DAG.getStore(Chain, DL, Tmp,
11669                           Ptr, ST->getMemOperand());
11670     }
11671
11672     if (!ST->isVolatile() &&
11673         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11674       // Many FP stores are not made apparent until after legalize, e.g. for
11675       // argument passing.  Since this is so common, custom legalize the
11676       // 64-bit integer store into two 32-bit stores.
11677       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11678       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11679       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11680       if (DAG.getDataLayout().isBigEndian())
11681         std::swap(Lo, Hi);
11682
11683       unsigned Alignment = ST->getAlignment();
11684       bool isVolatile = ST->isVolatile();
11685       bool isNonTemporal = ST->isNonTemporal();
11686       AAMDNodes AAInfo = ST->getAAInfo();
11687
11688       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11689                                  Ptr, ST->getPointerInfo(),
11690                                  isVolatile, isNonTemporal,
11691                                  ST->getAlignment(), AAInfo);
11692       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11693                         DAG.getConstant(4, DL, Ptr.getValueType()));
11694       Alignment = MinAlign(Alignment, 4U);
11695       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11696                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11697                                  isVolatile, isNonTemporal,
11698                                  Alignment, AAInfo);
11699       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11700                          St0, St1);
11701     }
11702
11703     return SDValue();
11704   }
11705 }
11706
11707 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11708   StoreSDNode *ST  = cast<StoreSDNode>(N);
11709   SDValue Chain = ST->getChain();
11710   SDValue Value = ST->getValue();
11711   SDValue Ptr   = ST->getBasePtr();
11712
11713   // If this is a store of a bit convert, store the input value if the
11714   // resultant store does not need a higher alignment than the original.
11715   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11716       ST->isUnindexed()) {
11717     unsigned OrigAlign = ST->getAlignment();
11718     EVT SVT = Value.getOperand(0).getValueType();
11719     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11720         SVT.getTypeForEVT(*DAG.getContext()));
11721     if (Align <= OrigAlign &&
11722         ((!LegalOperations && !ST->isVolatile()) ||
11723          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11724       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11725                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11726                           ST->isNonTemporal(), OrigAlign,
11727                           ST->getAAInfo());
11728   }
11729
11730   // Turn 'store undef, Ptr' -> nothing.
11731   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11732     return Chain;
11733
11734   // Try to infer better alignment information than the store already has.
11735   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11736     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11737       if (Align > ST->getAlignment()) {
11738         SDValue NewStore =
11739                DAG.getTruncStore(Chain, SDLoc(N), Value,
11740                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11741                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11742                                  ST->getAAInfo());
11743         if (NewStore.getNode() != N)
11744           return CombineTo(ST, NewStore, true);
11745       }
11746     }
11747   }
11748
11749   // Try transforming a pair floating point load / store ops to integer
11750   // load / store ops.
11751   if (SDValue NewST = TransformFPLoadStorePair(N))
11752     return NewST;
11753
11754   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11755                                                   : DAG.getSubtarget().useAA();
11756 #ifndef NDEBUG
11757   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11758       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11759     UseAA = false;
11760 #endif
11761   if (UseAA && ST->isUnindexed()) {
11762     // FIXME: We should do this even without AA enabled. AA will just allow
11763     // FindBetterChain to work in more situations. The problem with this is that
11764     // any combine that expects memory operations to be on consecutive chains
11765     // first needs to be updated to look for users of the same chain.
11766
11767     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11768     // adjacent stores.
11769     if (findBetterNeighborChains(ST)) {
11770       // replaceStoreChain uses CombineTo, which handled all of the worklist
11771       // manipulation. Return the original node to not do anything else.
11772       return SDValue(ST, 0);
11773     }
11774   }
11775
11776   // Try transforming N to an indexed store.
11777   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11778     return SDValue(N, 0);
11779
11780   // FIXME: is there such a thing as a truncating indexed store?
11781   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11782       Value.getValueType().isInteger()) {
11783     // See if we can simplify the input to this truncstore with knowledge that
11784     // only the low bits are being used.  For example:
11785     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11786     SDValue Shorter =
11787       GetDemandedBits(Value,
11788                       APInt::getLowBitsSet(
11789                         Value.getValueType().getScalarType().getSizeInBits(),
11790                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11791     AddToWorklist(Value.getNode());
11792     if (Shorter.getNode())
11793       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11794                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11795
11796     // Otherwise, see if we can simplify the operation with
11797     // SimplifyDemandedBits, which only works if the value has a single use.
11798     if (SimplifyDemandedBits(Value,
11799                         APInt::getLowBitsSet(
11800                           Value.getValueType().getScalarType().getSizeInBits(),
11801                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11802       return SDValue(N, 0);
11803   }
11804
11805   // If this is a load followed by a store to the same location, then the store
11806   // is dead/noop.
11807   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11808     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11809         ST->isUnindexed() && !ST->isVolatile() &&
11810         // There can't be any side effects between the load and store, such as
11811         // a call or store.
11812         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11813       // The store is dead, remove it.
11814       return Chain;
11815     }
11816   }
11817
11818   // If this is a store followed by a store with the same value to the same
11819   // location, then the store is dead/noop.
11820   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11821     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11822         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11823         ST1->isUnindexed() && !ST1->isVolatile()) {
11824       // The store is dead, remove it.
11825       return Chain;
11826     }
11827   }
11828
11829   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11830   // truncating store.  We can do this even if this is already a truncstore.
11831   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11832       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11833       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11834                             ST->getMemoryVT())) {
11835     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11836                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11837   }
11838
11839   // Only perform this optimization before the types are legal, because we
11840   // don't want to perform this optimization on every DAGCombine invocation.
11841   if (!LegalTypes) {
11842     bool EverChanged = false;
11843
11844     do {
11845       // There can be multiple store sequences on the same chain.
11846       // Keep trying to merge store sequences until we are unable to do so
11847       // or until we merge the last store on the chain.
11848       bool Changed = MergeConsecutiveStores(ST);
11849       EverChanged |= Changed;
11850       if (!Changed) break;
11851     } while (ST->getOpcode() != ISD::DELETED_NODE);
11852
11853     if (EverChanged)
11854       return SDValue(N, 0);
11855   }
11856
11857   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11858   //
11859   // Make sure to do this only after attempting to merge stores in order to
11860   //  avoid changing the types of some subset of stores due to visit order,
11861   //  preventing their merging.
11862   if (isa<ConstantFPSDNode>(Value)) {
11863     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11864       return NewSt;
11865   }
11866
11867   return ReduceLoadOpStoreWidth(N);
11868 }
11869
11870 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11871   SDValue InVec = N->getOperand(0);
11872   SDValue InVal = N->getOperand(1);
11873   SDValue EltNo = N->getOperand(2);
11874   SDLoc dl(N);
11875
11876   // If the inserted element is an UNDEF, just use the input vector.
11877   if (InVal.getOpcode() == ISD::UNDEF)
11878     return InVec;
11879
11880   EVT VT = InVec.getValueType();
11881
11882   // If we can't generate a legal BUILD_VECTOR, exit
11883   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11884     return SDValue();
11885
11886   // Check that we know which element is being inserted
11887   if (!isa<ConstantSDNode>(EltNo))
11888     return SDValue();
11889   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11890
11891   // Canonicalize insert_vector_elt dag nodes.
11892   // Example:
11893   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11894   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11895   //
11896   // Do this only if the child insert_vector node has one use; also
11897   // do this only if indices are both constants and Idx1 < Idx0.
11898   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11899       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11900     unsigned OtherElt =
11901       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11902     if (Elt < OtherElt) {
11903       // Swap nodes.
11904       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11905                                   InVec.getOperand(0), InVal, EltNo);
11906       AddToWorklist(NewOp.getNode());
11907       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11908                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11909     }
11910   }
11911
11912   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11913   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11914   // vector elements.
11915   SmallVector<SDValue, 8> Ops;
11916   // Do not combine these two vectors if the output vector will not replace
11917   // the input vector.
11918   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11919     Ops.append(InVec.getNode()->op_begin(),
11920                InVec.getNode()->op_end());
11921   } else if (InVec.getOpcode() == ISD::UNDEF) {
11922     unsigned NElts = VT.getVectorNumElements();
11923     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11924   } else {
11925     return SDValue();
11926   }
11927
11928   // Insert the element
11929   if (Elt < Ops.size()) {
11930     // All the operands of BUILD_VECTOR must have the same type;
11931     // we enforce that here.
11932     EVT OpVT = Ops[0].getValueType();
11933     if (InVal.getValueType() != OpVT)
11934       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11935                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11936                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11937     Ops[Elt] = InVal;
11938   }
11939
11940   // Return the new vector
11941   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11942 }
11943
11944 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11945     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11946   EVT ResultVT = EVE->getValueType(0);
11947   EVT VecEltVT = InVecVT.getVectorElementType();
11948   unsigned Align = OriginalLoad->getAlignment();
11949   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11950       VecEltVT.getTypeForEVT(*DAG.getContext()));
11951
11952   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11953     return SDValue();
11954
11955   Align = NewAlign;
11956
11957   SDValue NewPtr = OriginalLoad->getBasePtr();
11958   SDValue Offset;
11959   EVT PtrType = NewPtr.getValueType();
11960   MachinePointerInfo MPI;
11961   SDLoc DL(EVE);
11962   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11963     int Elt = ConstEltNo->getZExtValue();
11964     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11965     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11966     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11967   } else {
11968     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11969     Offset = DAG.getNode(
11970         ISD::MUL, DL, PtrType, Offset,
11971         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11972     MPI = OriginalLoad->getPointerInfo();
11973   }
11974   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11975
11976   // The replacement we need to do here is a little tricky: we need to
11977   // replace an extractelement of a load with a load.
11978   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11979   // Note that this replacement assumes that the extractvalue is the only
11980   // use of the load; that's okay because we don't want to perform this
11981   // transformation in other cases anyway.
11982   SDValue Load;
11983   SDValue Chain;
11984   if (ResultVT.bitsGT(VecEltVT)) {
11985     // If the result type of vextract is wider than the load, then issue an
11986     // extending load instead.
11987     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11988                                                   VecEltVT)
11989                                    ? ISD::ZEXTLOAD
11990                                    : ISD::EXTLOAD;
11991     Load = DAG.getExtLoad(
11992         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11993         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11994         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11995     Chain = Load.getValue(1);
11996   } else {
11997     Load = DAG.getLoad(
11998         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11999         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
12000         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
12001     Chain = Load.getValue(1);
12002     if (ResultVT.bitsLT(VecEltVT))
12003       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
12004     else
12005       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
12006   }
12007   WorklistRemover DeadNodes(*this);
12008   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
12009   SDValue To[] = { Load, Chain };
12010   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
12011   // Since we're explicitly calling ReplaceAllUses, add the new node to the
12012   // worklist explicitly as well.
12013   AddToWorklist(Load.getNode());
12014   AddUsersToWorklist(Load.getNode()); // Add users too
12015   // Make sure to revisit this node to clean it up; it will usually be dead.
12016   AddToWorklist(EVE);
12017   ++OpsNarrowed;
12018   return SDValue(EVE, 0);
12019 }
12020
12021 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
12022   // (vextract (scalar_to_vector val, 0) -> val
12023   SDValue InVec = N->getOperand(0);
12024   EVT VT = InVec.getValueType();
12025   EVT NVT = N->getValueType(0);
12026
12027   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
12028     // Check if the result type doesn't match the inserted element type. A
12029     // SCALAR_TO_VECTOR may truncate the inserted element and the
12030     // EXTRACT_VECTOR_ELT may widen the extracted vector.
12031     SDValue InOp = InVec.getOperand(0);
12032     if (InOp.getValueType() != NVT) {
12033       assert(InOp.getValueType().isInteger() && NVT.isInteger());
12034       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
12035     }
12036     return InOp;
12037   }
12038
12039   SDValue EltNo = N->getOperand(1);
12040   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
12041
12042   // extract_vector_elt (build_vector x, y), 1 -> y
12043   if (ConstEltNo &&
12044       InVec.getOpcode() == ISD::BUILD_VECTOR &&
12045       TLI.isTypeLegal(VT) &&
12046       (InVec.hasOneUse() ||
12047        TLI.aggressivelyPreferBuildVectorSources(VT))) {
12048     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
12049     EVT InEltVT = Elt.getValueType();
12050
12051     // Sometimes build_vector's scalar input types do not match result type.
12052     if (NVT == InEltVT)
12053       return Elt;
12054
12055     // TODO: It may be useful to truncate if free if the build_vector implicitly
12056     // converts.
12057   }
12058
12059   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
12060   // We only perform this optimization before the op legalization phase because
12061   // we may introduce new vector instructions which are not backed by TD
12062   // patterns. For example on AVX, extracting elements from a wide vector
12063   // without using extract_subvector. However, if we can find an underlying
12064   // scalar value, then we can always use that.
12065   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
12066     int NumElem = VT.getVectorNumElements();
12067     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
12068     // Find the new index to extract from.
12069     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
12070
12071     // Extracting an undef index is undef.
12072     if (OrigElt == -1)
12073       return DAG.getUNDEF(NVT);
12074
12075     // Select the right vector half to extract from.
12076     SDValue SVInVec;
12077     if (OrigElt < NumElem) {
12078       SVInVec = InVec->getOperand(0);
12079     } else {
12080       SVInVec = InVec->getOperand(1);
12081       OrigElt -= NumElem;
12082     }
12083
12084     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
12085       SDValue InOp = SVInVec.getOperand(OrigElt);
12086       if (InOp.getValueType() != NVT) {
12087         assert(InOp.getValueType().isInteger() && NVT.isInteger());
12088         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
12089       }
12090
12091       return InOp;
12092     }
12093
12094     // FIXME: We should handle recursing on other vector shuffles and
12095     // scalar_to_vector here as well.
12096
12097     if (!LegalOperations) {
12098       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
12099       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
12100                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
12101     }
12102   }
12103
12104   bool BCNumEltsChanged = false;
12105   EVT ExtVT = VT.getVectorElementType();
12106   EVT LVT = ExtVT;
12107
12108   // If the result of load has to be truncated, then it's not necessarily
12109   // profitable.
12110   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12111     return SDValue();
12112
12113   if (InVec.getOpcode() == ISD::BITCAST) {
12114     // Don't duplicate a load with other uses.
12115     if (!InVec.hasOneUse())
12116       return SDValue();
12117
12118     EVT BCVT = InVec.getOperand(0).getValueType();
12119     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12120       return SDValue();
12121     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12122       BCNumEltsChanged = true;
12123     InVec = InVec.getOperand(0);
12124     ExtVT = BCVT.getVectorElementType();
12125   }
12126
12127   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12128   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12129       ISD::isNormalLoad(InVec.getNode()) &&
12130       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12131     SDValue Index = N->getOperand(1);
12132     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12133       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12134                                                            OrigLoad);
12135   }
12136
12137   // Perform only after legalization to ensure build_vector / vector_shuffle
12138   // optimizations have already been done.
12139   if (!LegalOperations) return SDValue();
12140
12141   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12142   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12143   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12144
12145   if (ConstEltNo) {
12146     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12147
12148     LoadSDNode *LN0 = nullptr;
12149     const ShuffleVectorSDNode *SVN = nullptr;
12150     if (ISD::isNormalLoad(InVec.getNode())) {
12151       LN0 = cast<LoadSDNode>(InVec);
12152     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12153                InVec.getOperand(0).getValueType() == ExtVT &&
12154                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12155       // Don't duplicate a load with other uses.
12156       if (!InVec.hasOneUse())
12157         return SDValue();
12158
12159       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12160     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12161       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12162       // =>
12163       // (load $addr+1*size)
12164
12165       // Don't duplicate a load with other uses.
12166       if (!InVec.hasOneUse())
12167         return SDValue();
12168
12169       // If the bit convert changed the number of elements, it is unsafe
12170       // to examine the mask.
12171       if (BCNumEltsChanged)
12172         return SDValue();
12173
12174       // Select the input vector, guarding against out of range extract vector.
12175       unsigned NumElems = VT.getVectorNumElements();
12176       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12177       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12178
12179       if (InVec.getOpcode() == ISD::BITCAST) {
12180         // Don't duplicate a load with other uses.
12181         if (!InVec.hasOneUse())
12182           return SDValue();
12183
12184         InVec = InVec.getOperand(0);
12185       }
12186       if (ISD::isNormalLoad(InVec.getNode())) {
12187         LN0 = cast<LoadSDNode>(InVec);
12188         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12189         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12190       }
12191     }
12192
12193     // Make sure we found a non-volatile load and the extractelement is
12194     // the only use.
12195     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12196       return SDValue();
12197
12198     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12199     if (Elt == -1)
12200       return DAG.getUNDEF(LVT);
12201
12202     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12203   }
12204
12205   return SDValue();
12206 }
12207
12208 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12209 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12210   // We perform this optimization post type-legalization because
12211   // the type-legalizer often scalarizes integer-promoted vectors.
12212   // Performing this optimization before may create bit-casts which
12213   // will be type-legalized to complex code sequences.
12214   // We perform this optimization only before the operation legalizer because we
12215   // may introduce illegal operations.
12216   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12217     return SDValue();
12218
12219   unsigned NumInScalars = N->getNumOperands();
12220   SDLoc dl(N);
12221   EVT VT = N->getValueType(0);
12222
12223   // Check to see if this is a BUILD_VECTOR of a bunch of values
12224   // which come from any_extend or zero_extend nodes. If so, we can create
12225   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12226   // optimizations. We do not handle sign-extend because we can't fill the sign
12227   // using shuffles.
12228   EVT SourceType = MVT::Other;
12229   bool AllAnyExt = true;
12230
12231   for (unsigned i = 0; i != NumInScalars; ++i) {
12232     SDValue In = N->getOperand(i);
12233     // Ignore undef inputs.
12234     if (In.getOpcode() == ISD::UNDEF) continue;
12235
12236     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12237     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12238
12239     // Abort if the element is not an extension.
12240     if (!ZeroExt && !AnyExt) {
12241       SourceType = MVT::Other;
12242       break;
12243     }
12244
12245     // The input is a ZeroExt or AnyExt. Check the original type.
12246     EVT InTy = In.getOperand(0).getValueType();
12247
12248     // Check that all of the widened source types are the same.
12249     if (SourceType == MVT::Other)
12250       // First time.
12251       SourceType = InTy;
12252     else if (InTy != SourceType) {
12253       // Multiple income types. Abort.
12254       SourceType = MVT::Other;
12255       break;
12256     }
12257
12258     // Check if all of the extends are ANY_EXTENDs.
12259     AllAnyExt &= AnyExt;
12260   }
12261
12262   // In order to have valid types, all of the inputs must be extended from the
12263   // same source type and all of the inputs must be any or zero extend.
12264   // Scalar sizes must be a power of two.
12265   EVT OutScalarTy = VT.getScalarType();
12266   bool ValidTypes = SourceType != MVT::Other &&
12267                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12268                  isPowerOf2_32(SourceType.getSizeInBits());
12269
12270   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12271   // turn into a single shuffle instruction.
12272   if (!ValidTypes)
12273     return SDValue();
12274
12275   bool isLE = DAG.getDataLayout().isLittleEndian();
12276   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12277   assert(ElemRatio > 1 && "Invalid element size ratio");
12278   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12279                                DAG.getConstant(0, SDLoc(N), SourceType);
12280
12281   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12282   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12283
12284   // Populate the new build_vector
12285   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12286     SDValue Cast = N->getOperand(i);
12287     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12288             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12289             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12290     SDValue In;
12291     if (Cast.getOpcode() == ISD::UNDEF)
12292       In = DAG.getUNDEF(SourceType);
12293     else
12294       In = Cast->getOperand(0);
12295     unsigned Index = isLE ? (i * ElemRatio) :
12296                             (i * ElemRatio + (ElemRatio - 1));
12297
12298     assert(Index < Ops.size() && "Invalid index");
12299     Ops[Index] = In;
12300   }
12301
12302   // The type of the new BUILD_VECTOR node.
12303   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12304   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12305          "Invalid vector size");
12306   // Check if the new vector type is legal.
12307   if (!isTypeLegal(VecVT)) return SDValue();
12308
12309   // Make the new BUILD_VECTOR.
12310   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12311
12312   // The new BUILD_VECTOR node has the potential to be further optimized.
12313   AddToWorklist(BV.getNode());
12314   // Bitcast to the desired type.
12315   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12316 }
12317
12318 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12319   EVT VT = N->getValueType(0);
12320
12321   unsigned NumInScalars = N->getNumOperands();
12322   SDLoc dl(N);
12323
12324   EVT SrcVT = MVT::Other;
12325   unsigned Opcode = ISD::DELETED_NODE;
12326   unsigned NumDefs = 0;
12327
12328   for (unsigned i = 0; i != NumInScalars; ++i) {
12329     SDValue In = N->getOperand(i);
12330     unsigned Opc = In.getOpcode();
12331
12332     if (Opc == ISD::UNDEF)
12333       continue;
12334
12335     // If all scalar values are floats and converted from integers.
12336     if (Opcode == ISD::DELETED_NODE &&
12337         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12338       Opcode = Opc;
12339     }
12340
12341     if (Opc != Opcode)
12342       return SDValue();
12343
12344     EVT InVT = In.getOperand(0).getValueType();
12345
12346     // If all scalar values are typed differently, bail out. It's chosen to
12347     // simplify BUILD_VECTOR of integer types.
12348     if (SrcVT == MVT::Other)
12349       SrcVT = InVT;
12350     if (SrcVT != InVT)
12351       return SDValue();
12352     NumDefs++;
12353   }
12354
12355   // If the vector has just one element defined, it's not worth to fold it into
12356   // a vectorized one.
12357   if (NumDefs < 2)
12358     return SDValue();
12359
12360   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12361          && "Should only handle conversion from integer to float.");
12362   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12363
12364   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12365
12366   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12367     return SDValue();
12368
12369   // Just because the floating-point vector type is legal does not necessarily
12370   // mean that the corresponding integer vector type is.
12371   if (!isTypeLegal(NVT))
12372     return SDValue();
12373
12374   SmallVector<SDValue, 8> Opnds;
12375   for (unsigned i = 0; i != NumInScalars; ++i) {
12376     SDValue In = N->getOperand(i);
12377
12378     if (In.getOpcode() == ISD::UNDEF)
12379       Opnds.push_back(DAG.getUNDEF(SrcVT));
12380     else
12381       Opnds.push_back(In.getOperand(0));
12382   }
12383   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12384   AddToWorklist(BV.getNode());
12385
12386   return DAG.getNode(Opcode, dl, VT, BV);
12387 }
12388
12389 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12390   unsigned NumInScalars = N->getNumOperands();
12391   SDLoc dl(N);
12392   EVT VT = N->getValueType(0);
12393
12394   // A vector built entirely of undefs is undef.
12395   if (ISD::allOperandsUndef(N))
12396     return DAG.getUNDEF(VT);
12397
12398   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12399     return V;
12400
12401   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12402     return V;
12403
12404   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12405   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12406   // at most two distinct vectors, turn this into a shuffle node.
12407
12408   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12409   if (!isTypeLegal(VT))
12410     return SDValue();
12411
12412   // May only combine to shuffle after legalize if shuffle is legal.
12413   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12414     return SDValue();
12415
12416   SDValue VecIn1, VecIn2;
12417   bool UsesZeroVector = false;
12418   for (unsigned i = 0; i != NumInScalars; ++i) {
12419     SDValue Op = N->getOperand(i);
12420     // Ignore undef inputs.
12421     if (Op.getOpcode() == ISD::UNDEF) continue;
12422
12423     // See if we can combine this build_vector into a blend with a zero vector.
12424     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12425       UsesZeroVector = true;
12426       continue;
12427     }
12428
12429     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12430     // constant index, bail out.
12431     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12432         !isa<ConstantSDNode>(Op.getOperand(1))) {
12433       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12434       break;
12435     }
12436
12437     // We allow up to two distinct input vectors.
12438     SDValue ExtractedFromVec = Op.getOperand(0);
12439     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12440       continue;
12441
12442     if (!VecIn1.getNode()) {
12443       VecIn1 = ExtractedFromVec;
12444     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12445       VecIn2 = ExtractedFromVec;
12446     } else {
12447       // Too many inputs.
12448       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12449       break;
12450     }
12451   }
12452
12453   // If everything is good, we can make a shuffle operation.
12454   if (VecIn1.getNode()) {
12455     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12456     SmallVector<int, 8> Mask;
12457     for (unsigned i = 0; i != NumInScalars; ++i) {
12458       unsigned Opcode = N->getOperand(i).getOpcode();
12459       if (Opcode == ISD::UNDEF) {
12460         Mask.push_back(-1);
12461         continue;
12462       }
12463
12464       // Operands can also be zero.
12465       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12466         assert(UsesZeroVector &&
12467                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12468                "Unexpected node found!");
12469         Mask.push_back(NumInScalars+i);
12470         continue;
12471       }
12472
12473       // If extracting from the first vector, just use the index directly.
12474       SDValue Extract = N->getOperand(i);
12475       SDValue ExtVal = Extract.getOperand(1);
12476       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12477       if (Extract.getOperand(0) == VecIn1) {
12478         Mask.push_back(ExtIndex);
12479         continue;
12480       }
12481
12482       // Otherwise, use InIdx + InputVecSize
12483       Mask.push_back(InNumElements + ExtIndex);
12484     }
12485
12486     // Avoid introducing illegal shuffles with zero.
12487     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12488       return SDValue();
12489
12490     // We can't generate a shuffle node with mismatched input and output types.
12491     // Attempt to transform a single input vector to the correct type.
12492     if ((VT != VecIn1.getValueType())) {
12493       // If the input vector type has a different base type to the output
12494       // vector type, bail out.
12495       EVT VTElemType = VT.getVectorElementType();
12496       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12497           (VecIn2.getNode() &&
12498            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12499         return SDValue();
12500
12501       // If the input vector is too small, widen it.
12502       // We only support widening of vectors which are half the size of the
12503       // output registers. For example XMM->YMM widening on X86 with AVX.
12504       EVT VecInT = VecIn1.getValueType();
12505       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12506         // If we only have one small input, widen it by adding undef values.
12507         if (!VecIn2.getNode())
12508           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12509                                DAG.getUNDEF(VecIn1.getValueType()));
12510         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12511           // If we have two small inputs of the same type, try to concat them.
12512           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12513           VecIn2 = SDValue(nullptr, 0);
12514         } else
12515           return SDValue();
12516       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12517         // If the input vector is too large, try to split it.
12518         // We don't support having two input vectors that are too large.
12519         // If the zero vector was used, we can not split the vector,
12520         // since we'd need 3 inputs.
12521         if (UsesZeroVector || VecIn2.getNode())
12522           return SDValue();
12523
12524         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12525           return SDValue();
12526
12527         // Try to replace VecIn1 with two extract_subvectors
12528         // No need to update the masks, they should still be correct.
12529         VecIn2 = DAG.getNode(
12530             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12531             DAG.getConstant(VT.getVectorNumElements(), dl,
12532                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12533         VecIn1 = DAG.getNode(
12534             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12535             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12536       } else
12537         return SDValue();
12538     }
12539
12540     if (UsesZeroVector)
12541       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12542                                 DAG.getConstantFP(0.0, dl, VT);
12543     else
12544       // If VecIn2 is unused then change it to undef.
12545       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12546
12547     // Check that we were able to transform all incoming values to the same
12548     // type.
12549     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12550         VecIn1.getValueType() != VT)
12551           return SDValue();
12552
12553     // Return the new VECTOR_SHUFFLE node.
12554     SDValue Ops[2];
12555     Ops[0] = VecIn1;
12556     Ops[1] = VecIn2;
12557     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12558   }
12559
12560   return SDValue();
12561 }
12562
12563 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12564   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12565   EVT OpVT = N->getOperand(0).getValueType();
12566
12567   // If the operands are legal vectors, leave them alone.
12568   if (TLI.isTypeLegal(OpVT))
12569     return SDValue();
12570
12571   SDLoc DL(N);
12572   EVT VT = N->getValueType(0);
12573   SmallVector<SDValue, 8> Ops;
12574
12575   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12576   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12577
12578   // Keep track of what we encounter.
12579   bool AnyInteger = false;
12580   bool AnyFP = false;
12581   for (const SDValue &Op : N->ops()) {
12582     if (ISD::BITCAST == Op.getOpcode() &&
12583         !Op.getOperand(0).getValueType().isVector())
12584       Ops.push_back(Op.getOperand(0));
12585     else if (ISD::UNDEF == Op.getOpcode())
12586       Ops.push_back(ScalarUndef);
12587     else
12588       return SDValue();
12589
12590     // Note whether we encounter an integer or floating point scalar.
12591     // If it's neither, bail out, it could be something weird like x86mmx.
12592     EVT LastOpVT = Ops.back().getValueType();
12593     if (LastOpVT.isFloatingPoint())
12594       AnyFP = true;
12595     else if (LastOpVT.isInteger())
12596       AnyInteger = true;
12597     else
12598       return SDValue();
12599   }
12600
12601   // If any of the operands is a floating point scalar bitcast to a vector,
12602   // use floating point types throughout, and bitcast everything.
12603   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12604   if (AnyFP) {
12605     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12606     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12607     if (AnyInteger) {
12608       for (SDValue &Op : Ops) {
12609         if (Op.getValueType() == SVT)
12610           continue;
12611         if (Op.getOpcode() == ISD::UNDEF)
12612           Op = ScalarUndef;
12613         else
12614           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12615       }
12616     }
12617   }
12618
12619   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12620                                VT.getSizeInBits() / SVT.getSizeInBits());
12621   return DAG.getNode(ISD::BITCAST, DL, VT,
12622                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12623 }
12624
12625 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12626 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12627 // most two distinct vectors the same size as the result, attempt to turn this
12628 // into a legal shuffle.
12629 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12630   EVT VT = N->getValueType(0);
12631   EVT OpVT = N->getOperand(0).getValueType();
12632   int NumElts = VT.getVectorNumElements();
12633   int NumOpElts = OpVT.getVectorNumElements();
12634
12635   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12636   SmallVector<int, 8> Mask;
12637
12638   for (SDValue Op : N->ops()) {
12639     // Peek through any bitcast.
12640     while (Op.getOpcode() == ISD::BITCAST)
12641       Op = Op.getOperand(0);
12642
12643     // UNDEF nodes convert to UNDEF shuffle mask values.
12644     if (Op.getOpcode() == ISD::UNDEF) {
12645       Mask.append((unsigned)NumOpElts, -1);
12646       continue;
12647     }
12648
12649     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12650       return SDValue();
12651
12652     // What vector are we extracting the subvector from and at what index?
12653     SDValue ExtVec = Op.getOperand(0);
12654
12655     // We want the EVT of the original extraction to correctly scale the
12656     // extraction index.
12657     EVT ExtVT = ExtVec.getValueType();
12658
12659     // Peek through any bitcast.
12660     while (ExtVec.getOpcode() == ISD::BITCAST)
12661       ExtVec = ExtVec.getOperand(0);
12662
12663     // UNDEF nodes convert to UNDEF shuffle mask values.
12664     if (ExtVec.getOpcode() == ISD::UNDEF) {
12665       Mask.append((unsigned)NumOpElts, -1);
12666       continue;
12667     }
12668
12669     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12670       return SDValue();
12671     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12672
12673     // Ensure that we are extracting a subvector from a vector the same
12674     // size as the result.
12675     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12676       return SDValue();
12677
12678     // Scale the subvector index to account for any bitcast.
12679     int NumExtElts = ExtVT.getVectorNumElements();
12680     if (0 == (NumExtElts % NumElts))
12681       ExtIdx /= (NumExtElts / NumElts);
12682     else if (0 == (NumElts % NumExtElts))
12683       ExtIdx *= (NumElts / NumExtElts);
12684     else
12685       return SDValue();
12686
12687     // At most we can reference 2 inputs in the final shuffle.
12688     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12689       SV0 = ExtVec;
12690       for (int i = 0; i != NumOpElts; ++i)
12691         Mask.push_back(i + ExtIdx);
12692     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12693       SV1 = ExtVec;
12694       for (int i = 0; i != NumOpElts; ++i)
12695         Mask.push_back(i + ExtIdx + NumElts);
12696     } else {
12697       return SDValue();
12698     }
12699   }
12700
12701   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12702     return SDValue();
12703
12704   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12705                               DAG.getBitcast(VT, SV1), Mask);
12706 }
12707
12708 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12709   // If we only have one input vector, we don't need to do any concatenation.
12710   if (N->getNumOperands() == 1)
12711     return N->getOperand(0);
12712
12713   // Check if all of the operands are undefs.
12714   EVT VT = N->getValueType(0);
12715   if (ISD::allOperandsUndef(N))
12716     return DAG.getUNDEF(VT);
12717
12718   // Optimize concat_vectors where all but the first of the vectors are undef.
12719   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12720         return Op.getOpcode() == ISD::UNDEF;
12721       })) {
12722     SDValue In = N->getOperand(0);
12723     assert(In.getValueType().isVector() && "Must concat vectors");
12724
12725     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12726     if (In->getOpcode() == ISD::BITCAST &&
12727         !In->getOperand(0)->getValueType(0).isVector()) {
12728       SDValue Scalar = In->getOperand(0);
12729
12730       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12731       // look through the trunc so we can still do the transform:
12732       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12733       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12734           !TLI.isTypeLegal(Scalar.getValueType()) &&
12735           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12736         Scalar = Scalar->getOperand(0);
12737
12738       EVT SclTy = Scalar->getValueType(0);
12739
12740       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12741         return SDValue();
12742
12743       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12744                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12745       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12746         return SDValue();
12747
12748       SDLoc dl = SDLoc(N);
12749       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12750       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12751     }
12752   }
12753
12754   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12755   // We have already tested above for an UNDEF only concatenation.
12756   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12757   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12758   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12759     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12760   };
12761   bool AllBuildVectorsOrUndefs =
12762       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12763   if (AllBuildVectorsOrUndefs) {
12764     SmallVector<SDValue, 8> Opnds;
12765     EVT SVT = VT.getScalarType();
12766
12767     EVT MinVT = SVT;
12768     if (!SVT.isFloatingPoint()) {
12769       // If BUILD_VECTOR are from built from integer, they may have different
12770       // operand types. Get the smallest type and truncate all operands to it.
12771       bool FoundMinVT = false;
12772       for (const SDValue &Op : N->ops())
12773         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12774           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12775           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12776           FoundMinVT = true;
12777         }
12778       assert(FoundMinVT && "Concat vector type mismatch");
12779     }
12780
12781     for (const SDValue &Op : N->ops()) {
12782       EVT OpVT = Op.getValueType();
12783       unsigned NumElts = OpVT.getVectorNumElements();
12784
12785       if (ISD::UNDEF == Op.getOpcode())
12786         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12787
12788       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12789         if (SVT.isFloatingPoint()) {
12790           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12791           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12792         } else {
12793           for (unsigned i = 0; i != NumElts; ++i)
12794             Opnds.push_back(
12795                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12796         }
12797       }
12798     }
12799
12800     assert(VT.getVectorNumElements() == Opnds.size() &&
12801            "Concat vector type mismatch");
12802     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12803   }
12804
12805   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12806   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12807     return V;
12808
12809   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12810   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12811     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12812       return V;
12813
12814   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12815   // nodes often generate nop CONCAT_VECTOR nodes.
12816   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12817   // place the incoming vectors at the exact same location.
12818   SDValue SingleSource = SDValue();
12819   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12820
12821   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12822     SDValue Op = N->getOperand(i);
12823
12824     if (Op.getOpcode() == ISD::UNDEF)
12825       continue;
12826
12827     // Check if this is the identity extract:
12828     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12829       return SDValue();
12830
12831     // Find the single incoming vector for the extract_subvector.
12832     if (SingleSource.getNode()) {
12833       if (Op.getOperand(0) != SingleSource)
12834         return SDValue();
12835     } else {
12836       SingleSource = Op.getOperand(0);
12837
12838       // Check the source type is the same as the type of the result.
12839       // If not, this concat may extend the vector, so we can not
12840       // optimize it away.
12841       if (SingleSource.getValueType() != N->getValueType(0))
12842         return SDValue();
12843     }
12844
12845     unsigned IdentityIndex = i * PartNumElem;
12846     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12847     // The extract index must be constant.
12848     if (!CS)
12849       return SDValue();
12850
12851     // Check that we are reading from the identity index.
12852     if (CS->getZExtValue() != IdentityIndex)
12853       return SDValue();
12854   }
12855
12856   if (SingleSource.getNode())
12857     return SingleSource;
12858
12859   return SDValue();
12860 }
12861
12862 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12863   EVT NVT = N->getValueType(0);
12864   SDValue V = N->getOperand(0);
12865
12866   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12867     // Combine:
12868     //    (extract_subvec (concat V1, V2, ...), i)
12869     // Into:
12870     //    Vi if possible
12871     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12872     // type.
12873     if (V->getOperand(0).getValueType() != NVT)
12874       return SDValue();
12875     unsigned Idx = N->getConstantOperandVal(1);
12876     unsigned NumElems = NVT.getVectorNumElements();
12877     assert((Idx % NumElems) == 0 &&
12878            "IDX in concat is not a multiple of the result vector length.");
12879     return V->getOperand(Idx / NumElems);
12880   }
12881
12882   // Skip bitcasting
12883   if (V->getOpcode() == ISD::BITCAST)
12884     V = V.getOperand(0);
12885
12886   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12887     SDLoc dl(N);
12888     // Handle only simple case where vector being inserted and vector
12889     // being extracted are of same type, and are half size of larger vectors.
12890     EVT BigVT = V->getOperand(0).getValueType();
12891     EVT SmallVT = V->getOperand(1).getValueType();
12892     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12893       return SDValue();
12894
12895     // Only handle cases where both indexes are constants with the same type.
12896     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12897     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12898
12899     if (InsIdx && ExtIdx &&
12900         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12901         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12902       // Combine:
12903       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12904       // Into:
12905       //    indices are equal or bit offsets are equal => V1
12906       //    otherwise => (extract_subvec V1, ExtIdx)
12907       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12908           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12909         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12910       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12911                          DAG.getNode(ISD::BITCAST, dl,
12912                                      N->getOperand(0).getValueType(),
12913                                      V->getOperand(0)), N->getOperand(1));
12914     }
12915   }
12916
12917   return SDValue();
12918 }
12919
12920 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12921                                                  SDValue V, SelectionDAG &DAG) {
12922   SDLoc DL(V);
12923   EVT VT = V.getValueType();
12924
12925   switch (V.getOpcode()) {
12926   default:
12927     return V;
12928
12929   case ISD::CONCAT_VECTORS: {
12930     EVT OpVT = V->getOperand(0).getValueType();
12931     int OpSize = OpVT.getVectorNumElements();
12932     SmallBitVector OpUsedElements(OpSize, false);
12933     bool FoundSimplification = false;
12934     SmallVector<SDValue, 4> NewOps;
12935     NewOps.reserve(V->getNumOperands());
12936     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12937       SDValue Op = V->getOperand(i);
12938       bool OpUsed = false;
12939       for (int j = 0; j < OpSize; ++j)
12940         if (UsedElements[i * OpSize + j]) {
12941           OpUsedElements[j] = true;
12942           OpUsed = true;
12943         }
12944       NewOps.push_back(
12945           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12946                  : DAG.getUNDEF(OpVT));
12947       FoundSimplification |= Op == NewOps.back();
12948       OpUsedElements.reset();
12949     }
12950     if (FoundSimplification)
12951       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12952     return V;
12953   }
12954
12955   case ISD::INSERT_SUBVECTOR: {
12956     SDValue BaseV = V->getOperand(0);
12957     SDValue SubV = V->getOperand(1);
12958     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12959     if (!IdxN)
12960       return V;
12961
12962     int SubSize = SubV.getValueType().getVectorNumElements();
12963     int Idx = IdxN->getZExtValue();
12964     bool SubVectorUsed = false;
12965     SmallBitVector SubUsedElements(SubSize, false);
12966     for (int i = 0; i < SubSize; ++i)
12967       if (UsedElements[i + Idx]) {
12968         SubVectorUsed = true;
12969         SubUsedElements[i] = true;
12970         UsedElements[i + Idx] = false;
12971       }
12972
12973     // Now recurse on both the base and sub vectors.
12974     SDValue SimplifiedSubV =
12975         SubVectorUsed
12976             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12977             : DAG.getUNDEF(SubV.getValueType());
12978     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12979     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12980       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12981                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12982     return V;
12983   }
12984   }
12985 }
12986
12987 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12988                                        SDValue N1, SelectionDAG &DAG) {
12989   EVT VT = SVN->getValueType(0);
12990   int NumElts = VT.getVectorNumElements();
12991   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12992   for (int M : SVN->getMask())
12993     if (M >= 0 && M < NumElts)
12994       N0UsedElements[M] = true;
12995     else if (M >= NumElts)
12996       N1UsedElements[M - NumElts] = true;
12997
12998   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12999   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
13000   if (S0 == N0 && S1 == N1)
13001     return SDValue();
13002
13003   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
13004 }
13005
13006 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
13007 // or turn a shuffle of a single concat into simpler shuffle then concat.
13008 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
13009   EVT VT = N->getValueType(0);
13010   unsigned NumElts = VT.getVectorNumElements();
13011
13012   SDValue N0 = N->getOperand(0);
13013   SDValue N1 = N->getOperand(1);
13014   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13015
13016   SmallVector<SDValue, 4> Ops;
13017   EVT ConcatVT = N0.getOperand(0).getValueType();
13018   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
13019   unsigned NumConcats = NumElts / NumElemsPerConcat;
13020
13021   // Special case: shuffle(concat(A,B)) can be more efficiently represented
13022   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
13023   // half vector elements.
13024   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
13025       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
13026                   SVN->getMask().end(), [](int i) { return i == -1; })) {
13027     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
13028                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
13029     N1 = DAG.getUNDEF(ConcatVT);
13030     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
13031   }
13032
13033   // Look at every vector that's inserted. We're looking for exact
13034   // subvector-sized copies from a concatenated vector
13035   for (unsigned I = 0; I != NumConcats; ++I) {
13036     // Make sure we're dealing with a copy.
13037     unsigned Begin = I * NumElemsPerConcat;
13038     bool AllUndef = true, NoUndef = true;
13039     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
13040       if (SVN->getMaskElt(J) >= 0)
13041         AllUndef = false;
13042       else
13043         NoUndef = false;
13044     }
13045
13046     if (NoUndef) {
13047       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
13048         return SDValue();
13049
13050       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
13051         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
13052           return SDValue();
13053
13054       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
13055       if (FirstElt < N0.getNumOperands())
13056         Ops.push_back(N0.getOperand(FirstElt));
13057       else
13058         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
13059
13060     } else if (AllUndef) {
13061       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
13062     } else { // Mixed with general masks and undefs, can't do optimization.
13063       return SDValue();
13064     }
13065   }
13066
13067   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
13068 }
13069
13070 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
13071   EVT VT = N->getValueType(0);
13072   unsigned NumElts = VT.getVectorNumElements();
13073
13074   SDValue N0 = N->getOperand(0);
13075   SDValue N1 = N->getOperand(1);
13076
13077   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
13078
13079   // Canonicalize shuffle undef, undef -> undef
13080   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
13081     return DAG.getUNDEF(VT);
13082
13083   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13084
13085   // Canonicalize shuffle v, v -> v, undef
13086   if (N0 == N1) {
13087     SmallVector<int, 8> NewMask;
13088     for (unsigned i = 0; i != NumElts; ++i) {
13089       int Idx = SVN->getMaskElt(i);
13090       if (Idx >= (int)NumElts) Idx -= NumElts;
13091       NewMask.push_back(Idx);
13092     }
13093     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
13094                                 &NewMask[0]);
13095   }
13096
13097   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
13098   if (N0.getOpcode() == ISD::UNDEF) {
13099     SmallVector<int, 8> NewMask;
13100     for (unsigned i = 0; i != NumElts; ++i) {
13101       int Idx = SVN->getMaskElt(i);
13102       if (Idx >= 0) {
13103         if (Idx >= (int)NumElts)
13104           Idx -= NumElts;
13105         else
13106           Idx = -1; // remove reference to lhs
13107       }
13108       NewMask.push_back(Idx);
13109     }
13110     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13111                                 &NewMask[0]);
13112   }
13113
13114   // Remove references to rhs if it is undef
13115   if (N1.getOpcode() == ISD::UNDEF) {
13116     bool Changed = false;
13117     SmallVector<int, 8> NewMask;
13118     for (unsigned i = 0; i != NumElts; ++i) {
13119       int Idx = SVN->getMaskElt(i);
13120       if (Idx >= (int)NumElts) {
13121         Idx = -1;
13122         Changed = true;
13123       }
13124       NewMask.push_back(Idx);
13125     }
13126     if (Changed)
13127       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13128   }
13129
13130   // If it is a splat, check if the argument vector is another splat or a
13131   // build_vector.
13132   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13133     SDNode *V = N0.getNode();
13134
13135     // If this is a bit convert that changes the element type of the vector but
13136     // not the number of vector elements, look through it.  Be careful not to
13137     // look though conversions that change things like v4f32 to v2f64.
13138     if (V->getOpcode() == ISD::BITCAST) {
13139       SDValue ConvInput = V->getOperand(0);
13140       if (ConvInput.getValueType().isVector() &&
13141           ConvInput.getValueType().getVectorNumElements() == NumElts)
13142         V = ConvInput.getNode();
13143     }
13144
13145     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13146       assert(V->getNumOperands() == NumElts &&
13147              "BUILD_VECTOR has wrong number of operands");
13148       SDValue Base;
13149       bool AllSame = true;
13150       for (unsigned i = 0; i != NumElts; ++i) {
13151         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13152           Base = V->getOperand(i);
13153           break;
13154         }
13155       }
13156       // Splat of <u, u, u, u>, return <u, u, u, u>
13157       if (!Base.getNode())
13158         return N0;
13159       for (unsigned i = 0; i != NumElts; ++i) {
13160         if (V->getOperand(i) != Base) {
13161           AllSame = false;
13162           break;
13163         }
13164       }
13165       // Splat of <x, x, x, x>, return <x, x, x, x>
13166       if (AllSame)
13167         return N0;
13168
13169       // Canonicalize any other splat as a build_vector.
13170       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13171       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13172       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13173                                   V->getValueType(0), Ops);
13174
13175       // We may have jumped through bitcasts, so the type of the
13176       // BUILD_VECTOR may not match the type of the shuffle.
13177       if (V->getValueType(0) != VT)
13178         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13179       return NewBV;
13180     }
13181   }
13182
13183   // There are various patterns used to build up a vector from smaller vectors,
13184   // subvectors, or elements. Scan chains of these and replace unused insertions
13185   // or components with undef.
13186   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13187     return S;
13188
13189   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13190       Level < AfterLegalizeVectorOps &&
13191       (N1.getOpcode() == ISD::UNDEF ||
13192       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13193        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13194     SDValue V = partitionShuffleOfConcats(N, DAG);
13195
13196     if (V.getNode())
13197       return V;
13198   }
13199
13200   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13201   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13202   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13203     SmallVector<SDValue, 8> Ops;
13204     for (int M : SVN->getMask()) {
13205       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13206       if (M >= 0) {
13207         int Idx = M % NumElts;
13208         SDValue &S = (M < (int)NumElts ? N0 : N1);
13209         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13210           Op = S.getOperand(Idx);
13211         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13212           if (Idx == 0)
13213             Op = S.getOperand(0);
13214         } else {
13215           // Operand can't be combined - bail out.
13216           break;
13217         }
13218       }
13219       Ops.push_back(Op);
13220     }
13221     if (Ops.size() == VT.getVectorNumElements()) {
13222       // BUILD_VECTOR requires all inputs to be of the same type, find the
13223       // maximum type and extend them all.
13224       EVT SVT = VT.getScalarType();
13225       if (SVT.isInteger())
13226         for (SDValue &Op : Ops)
13227           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13228       if (SVT != VT.getScalarType())
13229         for (SDValue &Op : Ops)
13230           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13231                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13232                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13233       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13234     }
13235   }
13236
13237   // If this shuffle only has a single input that is a bitcasted shuffle,
13238   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13239   // back to their original types.
13240   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13241       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13242       TLI.isTypeLegal(VT)) {
13243
13244     // Peek through the bitcast only if there is one user.
13245     SDValue BC0 = N0;
13246     while (BC0.getOpcode() == ISD::BITCAST) {
13247       if (!BC0.hasOneUse())
13248         break;
13249       BC0 = BC0.getOperand(0);
13250     }
13251
13252     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13253       if (Scale == 1)
13254         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13255
13256       SmallVector<int, 8> NewMask;
13257       for (int M : Mask)
13258         for (int s = 0; s != Scale; ++s)
13259           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13260       return NewMask;
13261     };
13262
13263     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13264       EVT SVT = VT.getScalarType();
13265       EVT InnerVT = BC0->getValueType(0);
13266       EVT InnerSVT = InnerVT.getScalarType();
13267
13268       // Determine which shuffle works with the smaller scalar type.
13269       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13270       EVT ScaleSVT = ScaleVT.getScalarType();
13271
13272       if (TLI.isTypeLegal(ScaleVT) &&
13273           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13274           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13275
13276         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13277         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13278
13279         // Scale the shuffle masks to the smaller scalar type.
13280         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13281         SmallVector<int, 8> InnerMask =
13282             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13283         SmallVector<int, 8> OuterMask =
13284             ScaleShuffleMask(SVN->getMask(), OuterScale);
13285
13286         // Merge the shuffle masks.
13287         SmallVector<int, 8> NewMask;
13288         for (int M : OuterMask)
13289           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13290
13291         // Test for shuffle mask legality over both commutations.
13292         SDValue SV0 = BC0->getOperand(0);
13293         SDValue SV1 = BC0->getOperand(1);
13294         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13295         if (!LegalMask) {
13296           std::swap(SV0, SV1);
13297           ShuffleVectorSDNode::commuteMask(NewMask);
13298           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13299         }
13300
13301         if (LegalMask) {
13302           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13303           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13304           return DAG.getNode(
13305               ISD::BITCAST, SDLoc(N), VT,
13306               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13307         }
13308       }
13309     }
13310   }
13311
13312   // Canonicalize shuffles according to rules:
13313   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13314   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13315   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13316   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13317       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13318       TLI.isTypeLegal(VT)) {
13319     // The incoming shuffle must be of the same type as the result of the
13320     // current shuffle.
13321     assert(N1->getOperand(0).getValueType() == VT &&
13322            "Shuffle types don't match");
13323
13324     SDValue SV0 = N1->getOperand(0);
13325     SDValue SV1 = N1->getOperand(1);
13326     bool HasSameOp0 = N0 == SV0;
13327     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13328     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13329       // Commute the operands of this shuffle so that next rule
13330       // will trigger.
13331       return DAG.getCommutedVectorShuffle(*SVN);
13332   }
13333
13334   // Try to fold according to rules:
13335   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13336   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13337   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13338   // Don't try to fold shuffles with illegal type.
13339   // Only fold if this shuffle is the only user of the other shuffle.
13340   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13341       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13342     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13343
13344     // The incoming shuffle must be of the same type as the result of the
13345     // current shuffle.
13346     assert(OtherSV->getOperand(0).getValueType() == VT &&
13347            "Shuffle types don't match");
13348
13349     SDValue SV0, SV1;
13350     SmallVector<int, 4> Mask;
13351     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13352     // operand, and SV1 as the second operand.
13353     for (unsigned i = 0; i != NumElts; ++i) {
13354       int Idx = SVN->getMaskElt(i);
13355       if (Idx < 0) {
13356         // Propagate Undef.
13357         Mask.push_back(Idx);
13358         continue;
13359       }
13360
13361       SDValue CurrentVec;
13362       if (Idx < (int)NumElts) {
13363         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13364         // shuffle mask to identify which vector is actually referenced.
13365         Idx = OtherSV->getMaskElt(Idx);
13366         if (Idx < 0) {
13367           // Propagate Undef.
13368           Mask.push_back(Idx);
13369           continue;
13370         }
13371
13372         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13373                                            : OtherSV->getOperand(1);
13374       } else {
13375         // This shuffle index references an element within N1.
13376         CurrentVec = N1;
13377       }
13378
13379       // Simple case where 'CurrentVec' is UNDEF.
13380       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13381         Mask.push_back(-1);
13382         continue;
13383       }
13384
13385       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13386       // will be the first or second operand of the combined shuffle.
13387       Idx = Idx % NumElts;
13388       if (!SV0.getNode() || SV0 == CurrentVec) {
13389         // Ok. CurrentVec is the left hand side.
13390         // Update the mask accordingly.
13391         SV0 = CurrentVec;
13392         Mask.push_back(Idx);
13393         continue;
13394       }
13395
13396       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13397       if (SV1.getNode() && SV1 != CurrentVec)
13398         return SDValue();
13399
13400       // Ok. CurrentVec is the right hand side.
13401       // Update the mask accordingly.
13402       SV1 = CurrentVec;
13403       Mask.push_back(Idx + NumElts);
13404     }
13405
13406     // Check if all indices in Mask are Undef. In case, propagate Undef.
13407     bool isUndefMask = true;
13408     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13409       isUndefMask &= Mask[i] < 0;
13410
13411     if (isUndefMask)
13412       return DAG.getUNDEF(VT);
13413
13414     if (!SV0.getNode())
13415       SV0 = DAG.getUNDEF(VT);
13416     if (!SV1.getNode())
13417       SV1 = DAG.getUNDEF(VT);
13418
13419     // Avoid introducing shuffles with illegal mask.
13420     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13421       ShuffleVectorSDNode::commuteMask(Mask);
13422
13423       if (!TLI.isShuffleMaskLegal(Mask, VT))
13424         return SDValue();
13425
13426       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13427       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13428       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13429       std::swap(SV0, SV1);
13430     }
13431
13432     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13433     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13434     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13435     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13436   }
13437
13438   return SDValue();
13439 }
13440
13441 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13442   SDValue InVal = N->getOperand(0);
13443   EVT VT = N->getValueType(0);
13444
13445   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13446   // with a VECTOR_SHUFFLE.
13447   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13448     SDValue InVec = InVal->getOperand(0);
13449     SDValue EltNo = InVal->getOperand(1);
13450
13451     // FIXME: We could support implicit truncation if the shuffle can be
13452     // scaled to a smaller vector scalar type.
13453     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13454     if (C0 && VT == InVec.getValueType() &&
13455         VT.getScalarType() == InVal.getValueType()) {
13456       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13457       int Elt = C0->getZExtValue();
13458       NewMask[0] = Elt;
13459
13460       if (TLI.isShuffleMaskLegal(NewMask, VT))
13461         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13462                                     NewMask);
13463     }
13464   }
13465
13466   return SDValue();
13467 }
13468
13469 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13470   SDValue N0 = N->getOperand(0);
13471   SDValue N2 = N->getOperand(2);
13472
13473   // If the input vector is a concatenation, and the insert replaces
13474   // one of the halves, we can optimize into a single concat_vectors.
13475   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13476       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13477     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13478     EVT VT = N->getValueType(0);
13479
13480     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13481     // (concat_vectors Z, Y)
13482     if (InsIdx == 0)
13483       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13484                          N->getOperand(1), N0.getOperand(1));
13485
13486     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13487     // (concat_vectors X, Z)
13488     if (InsIdx == VT.getVectorNumElements()/2)
13489       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13490                          N0.getOperand(0), N->getOperand(1));
13491   }
13492
13493   return SDValue();
13494 }
13495
13496 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13497   SDValue N0 = N->getOperand(0);
13498
13499   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13500   if (N0->getOpcode() == ISD::FP16_TO_FP)
13501     return N0->getOperand(0);
13502
13503   return SDValue();
13504 }
13505
13506 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13507   SDValue N0 = N->getOperand(0);
13508
13509   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13510   if (N0->getOpcode() == ISD::AND) {
13511     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13512     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13513       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13514                          N0.getOperand(0));
13515     }
13516   }
13517
13518   return SDValue();
13519 }
13520
13521 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13522 /// with the destination vector and a zero vector.
13523 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13524 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13525 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13526   EVT VT = N->getValueType(0);
13527   SDValue LHS = N->getOperand(0);
13528   SDValue RHS = N->getOperand(1);
13529   SDLoc dl(N);
13530
13531   // Make sure we're not running after operation legalization where it
13532   // may have custom lowered the vector shuffles.
13533   if (LegalOperations)
13534     return SDValue();
13535
13536   if (N->getOpcode() != ISD::AND)
13537     return SDValue();
13538
13539   if (RHS.getOpcode() == ISD::BITCAST)
13540     RHS = RHS.getOperand(0);
13541
13542   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13543     return SDValue();
13544
13545   EVT RVT = RHS.getValueType();
13546   unsigned NumElts = RHS.getNumOperands();
13547
13548   // Attempt to create a valid clear mask, splitting the mask into
13549   // sub elements and checking to see if each is
13550   // all zeros or all ones - suitable for shuffle masking.
13551   auto BuildClearMask = [&](int Split) {
13552     int NumSubElts = NumElts * Split;
13553     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13554
13555     SmallVector<int, 8> Indices;
13556     for (int i = 0; i != NumSubElts; ++i) {
13557       int EltIdx = i / Split;
13558       int SubIdx = i % Split;
13559       SDValue Elt = RHS.getOperand(EltIdx);
13560       if (Elt.getOpcode() == ISD::UNDEF) {
13561         Indices.push_back(-1);
13562         continue;
13563       }
13564
13565       APInt Bits;
13566       if (isa<ConstantSDNode>(Elt))
13567         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13568       else if (isa<ConstantFPSDNode>(Elt))
13569         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13570       else
13571         return SDValue();
13572
13573       // Extract the sub element from the constant bit mask.
13574       if (DAG.getDataLayout().isBigEndian()) {
13575         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13576       } else {
13577         Bits = Bits.lshr(SubIdx * NumSubBits);
13578       }
13579
13580       if (Split > 1)
13581         Bits = Bits.trunc(NumSubBits);
13582
13583       if (Bits.isAllOnesValue())
13584         Indices.push_back(i);
13585       else if (Bits == 0)
13586         Indices.push_back(i + NumSubElts);
13587       else
13588         return SDValue();
13589     }
13590
13591     // Let's see if the target supports this vector_shuffle.
13592     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13593     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13594     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13595       return SDValue();
13596
13597     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13598     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13599                                                    DAG.getBitcast(ClearVT, LHS),
13600                                                    Zero, &Indices[0]));
13601   };
13602
13603   // Determine maximum split level (byte level masking).
13604   int MaxSplit = 1;
13605   if (RVT.getScalarSizeInBits() % 8 == 0)
13606     MaxSplit = RVT.getScalarSizeInBits() / 8;
13607
13608   for (int Split = 1; Split <= MaxSplit; ++Split)
13609     if (RVT.getScalarSizeInBits() % Split == 0)
13610       if (SDValue S = BuildClearMask(Split))
13611         return S;
13612
13613   return SDValue();
13614 }
13615
13616 /// Visit a binary vector operation, like ADD.
13617 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13618   assert(N->getValueType(0).isVector() &&
13619          "SimplifyVBinOp only works on vectors!");
13620
13621   SDValue LHS = N->getOperand(0);
13622   SDValue RHS = N->getOperand(1);
13623   SDValue Ops[] = {LHS, RHS};
13624
13625   // See if we can constant fold the vector operation.
13626   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13627           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13628     return Fold;
13629
13630   // Try to convert a constant mask AND into a shuffle clear mask.
13631   if (SDValue Shuffle = XformToShuffleWithZero(N))
13632     return Shuffle;
13633
13634   // Type legalization might introduce new shuffles in the DAG.
13635   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13636   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13637   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13638       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13639       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13640       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13641     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13642     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13643
13644     if (SVN0->getMask().equals(SVN1->getMask())) {
13645       EVT VT = N->getValueType(0);
13646       SDValue UndefVector = LHS.getOperand(1);
13647       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13648                                      LHS.getOperand(0), RHS.getOperand(0),
13649                                      N->getFlags());
13650       AddUsersToWorklist(N);
13651       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13652                                   &SVN0->getMask()[0]);
13653     }
13654   }
13655
13656   return SDValue();
13657 }
13658
13659 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13660                                     SDValue N1, SDValue N2){
13661   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13662
13663   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13664                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13665
13666   // If we got a simplified select_cc node back from SimplifySelectCC, then
13667   // break it down into a new SETCC node, and a new SELECT node, and then return
13668   // the SELECT node, since we were called with a SELECT node.
13669   if (SCC.getNode()) {
13670     // Check to see if we got a select_cc back (to turn into setcc/select).
13671     // Otherwise, just return whatever node we got back, like fabs.
13672     if (SCC.getOpcode() == ISD::SELECT_CC) {
13673       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13674                                   N0.getValueType(),
13675                                   SCC.getOperand(0), SCC.getOperand(1),
13676                                   SCC.getOperand(4));
13677       AddToWorklist(SETCC.getNode());
13678       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13679                            SCC.getOperand(2), SCC.getOperand(3));
13680     }
13681
13682     return SCC;
13683   }
13684   return SDValue();
13685 }
13686
13687 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13688 /// being selected between, see if we can simplify the select.  Callers of this
13689 /// should assume that TheSelect is deleted if this returns true.  As such, they
13690 /// should return the appropriate thing (e.g. the node) back to the top-level of
13691 /// the DAG combiner loop to avoid it being looked at.
13692 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13693                                     SDValue RHS) {
13694
13695   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13696   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13697   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13698     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13699       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13700       SDValue Sqrt = RHS;
13701       ISD::CondCode CC;
13702       SDValue CmpLHS;
13703       const ConstantFPSDNode *NegZero = nullptr;
13704
13705       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13706         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13707         CmpLHS = TheSelect->getOperand(0);
13708         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13709       } else {
13710         // SELECT or VSELECT
13711         SDValue Cmp = TheSelect->getOperand(0);
13712         if (Cmp.getOpcode() == ISD::SETCC) {
13713           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13714           CmpLHS = Cmp.getOperand(0);
13715           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13716         }
13717       }
13718       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13719           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13720           CC == ISD::SETULT || CC == ISD::SETLT)) {
13721         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13722         CombineTo(TheSelect, Sqrt);
13723         return true;
13724       }
13725     }
13726   }
13727   // Cannot simplify select with vector condition
13728   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13729
13730   // If this is a select from two identical things, try to pull the operation
13731   // through the select.
13732   if (LHS.getOpcode() != RHS.getOpcode() ||
13733       !LHS.hasOneUse() || !RHS.hasOneUse())
13734     return false;
13735
13736   // If this is a load and the token chain is identical, replace the select
13737   // of two loads with a load through a select of the address to load from.
13738   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13739   // constants have been dropped into the constant pool.
13740   if (LHS.getOpcode() == ISD::LOAD) {
13741     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13742     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13743
13744     // Token chains must be identical.
13745     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13746         // Do not let this transformation reduce the number of volatile loads.
13747         LLD->isVolatile() || RLD->isVolatile() ||
13748         // FIXME: If either is a pre/post inc/dec load,
13749         // we'd need to split out the address adjustment.
13750         LLD->isIndexed() || RLD->isIndexed() ||
13751         // If this is an EXTLOAD, the VT's must match.
13752         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13753         // If this is an EXTLOAD, the kind of extension must match.
13754         (LLD->getExtensionType() != RLD->getExtensionType() &&
13755          // The only exception is if one of the extensions is anyext.
13756          LLD->getExtensionType() != ISD::EXTLOAD &&
13757          RLD->getExtensionType() != ISD::EXTLOAD) ||
13758         // FIXME: this discards src value information.  This is
13759         // over-conservative. It would be beneficial to be able to remember
13760         // both potential memory locations.  Since we are discarding
13761         // src value info, don't do the transformation if the memory
13762         // locations are not in the default address space.
13763         LLD->getPointerInfo().getAddrSpace() != 0 ||
13764         RLD->getPointerInfo().getAddrSpace() != 0 ||
13765         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13766                                       LLD->getBasePtr().getValueType()))
13767       return false;
13768
13769     // Check that the select condition doesn't reach either load.  If so,
13770     // folding this will induce a cycle into the DAG.  If not, this is safe to
13771     // xform, so create a select of the addresses.
13772     SDValue Addr;
13773     if (TheSelect->getOpcode() == ISD::SELECT) {
13774       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13775       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13776           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13777         return false;
13778       // The loads must not depend on one another.
13779       if (LLD->isPredecessorOf(RLD) ||
13780           RLD->isPredecessorOf(LLD))
13781         return false;
13782       Addr = DAG.getSelect(SDLoc(TheSelect),
13783                            LLD->getBasePtr().getValueType(),
13784                            TheSelect->getOperand(0), LLD->getBasePtr(),
13785                            RLD->getBasePtr());
13786     } else {  // Otherwise SELECT_CC
13787       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13788       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13789
13790       if ((LLD->hasAnyUseOfValue(1) &&
13791            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13792           (RLD->hasAnyUseOfValue(1) &&
13793            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13794         return false;
13795
13796       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13797                          LLD->getBasePtr().getValueType(),
13798                          TheSelect->getOperand(0),
13799                          TheSelect->getOperand(1),
13800                          LLD->getBasePtr(), RLD->getBasePtr(),
13801                          TheSelect->getOperand(4));
13802     }
13803
13804     SDValue Load;
13805     // It is safe to replace the two loads if they have different alignments,
13806     // but the new load must be the minimum (most restrictive) alignment of the
13807     // inputs.
13808     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13809     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13810     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13811       Load = DAG.getLoad(TheSelect->getValueType(0),
13812                          SDLoc(TheSelect),
13813                          // FIXME: Discards pointer and AA info.
13814                          LLD->getChain(), Addr, MachinePointerInfo(),
13815                          LLD->isVolatile(), LLD->isNonTemporal(),
13816                          isInvariant, Alignment);
13817     } else {
13818       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13819                             RLD->getExtensionType() : LLD->getExtensionType(),
13820                             SDLoc(TheSelect),
13821                             TheSelect->getValueType(0),
13822                             // FIXME: Discards pointer and AA info.
13823                             LLD->getChain(), Addr, MachinePointerInfo(),
13824                             LLD->getMemoryVT(), LLD->isVolatile(),
13825                             LLD->isNonTemporal(), isInvariant, Alignment);
13826     }
13827
13828     // Users of the select now use the result of the load.
13829     CombineTo(TheSelect, Load);
13830
13831     // Users of the old loads now use the new load's chain.  We know the
13832     // old-load value is dead now.
13833     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13834     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13835     return true;
13836   }
13837
13838   return false;
13839 }
13840
13841 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13842 /// where 'cond' is the comparison specified by CC.
13843 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13844                                       SDValue N2, SDValue N3,
13845                                       ISD::CondCode CC, bool NotExtCompare) {
13846   // (x ? y : y) -> y.
13847   if (N2 == N3) return N2;
13848
13849   EVT VT = N2.getValueType();
13850   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13851   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13852
13853   // Determine if the condition we're dealing with is constant
13854   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13855                               N0, N1, CC, DL, false);
13856   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13857
13858   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13859     // fold select_cc true, x, y -> x
13860     // fold select_cc false, x, y -> y
13861     return !SCCC->isNullValue() ? N2 : N3;
13862   }
13863
13864   // Check to see if we can simplify the select into an fabs node
13865   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13866     // Allow either -0.0 or 0.0
13867     if (CFP->isZero()) {
13868       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13869       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13870           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13871           N2 == N3.getOperand(0))
13872         return DAG.getNode(ISD::FABS, DL, VT, N0);
13873
13874       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13875       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13876           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13877           N2.getOperand(0) == N3)
13878         return DAG.getNode(ISD::FABS, DL, VT, N3);
13879     }
13880   }
13881
13882   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13883   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13884   // in it.  This is a win when the constant is not otherwise available because
13885   // it replaces two constant pool loads with one.  We only do this if the FP
13886   // type is known to be legal, because if it isn't, then we are before legalize
13887   // types an we want the other legalization to happen first (e.g. to avoid
13888   // messing with soft float) and if the ConstantFP is not legal, because if
13889   // it is legal, we may not need to store the FP constant in a constant pool.
13890   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13891     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13892       if (TLI.isTypeLegal(N2.getValueType()) &&
13893           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13894                TargetLowering::Legal &&
13895            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13896            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13897           // If both constants have multiple uses, then we won't need to do an
13898           // extra load, they are likely around in registers for other users.
13899           (TV->hasOneUse() || FV->hasOneUse())) {
13900         Constant *Elts[] = {
13901           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13902           const_cast<ConstantFP*>(TV->getConstantFPValue())
13903         };
13904         Type *FPTy = Elts[0]->getType();
13905         const DataLayout &TD = DAG.getDataLayout();
13906
13907         // Create a ConstantArray of the two constants.
13908         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13909         SDValue CPIdx =
13910             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13911                                 TD.getPrefTypeAlignment(FPTy));
13912         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13913
13914         // Get the offsets to the 0 and 1 element of the array so that we can
13915         // select between them.
13916         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13917         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13918         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13919
13920         SDValue Cond = DAG.getSetCC(DL,
13921                                     getSetCCResultType(N0.getValueType()),
13922                                     N0, N1, CC);
13923         AddToWorklist(Cond.getNode());
13924         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13925                                           Cond, One, Zero);
13926         AddToWorklist(CstOffset.getNode());
13927         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13928                             CstOffset);
13929         AddToWorklist(CPIdx.getNode());
13930         return DAG.getLoad(
13931             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13932             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13933             false, false, false, Alignment);
13934       }
13935     }
13936
13937   // Check to see if we can perform the "gzip trick", transforming
13938   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13939   if (isNullConstant(N3) && CC == ISD::SETLT &&
13940       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13941        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13942     EVT XType = N0.getValueType();
13943     EVT AType = N2.getValueType();
13944     if (XType.bitsGE(AType)) {
13945       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13946       // single-bit constant.
13947       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13948         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13949         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13950         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13951                                        getShiftAmountTy(N0.getValueType()));
13952         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13953                                     XType, N0, ShCt);
13954         AddToWorklist(Shift.getNode());
13955
13956         if (XType.bitsGT(AType)) {
13957           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13958           AddToWorklist(Shift.getNode());
13959         }
13960
13961         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13962       }
13963
13964       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13965                                   XType, N0,
13966                                   DAG.getConstant(XType.getSizeInBits() - 1,
13967                                                   SDLoc(N0),
13968                                          getShiftAmountTy(N0.getValueType())));
13969       AddToWorklist(Shift.getNode());
13970
13971       if (XType.bitsGT(AType)) {
13972         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13973         AddToWorklist(Shift.getNode());
13974       }
13975
13976       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13977     }
13978   }
13979
13980   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13981   // where y is has a single bit set.
13982   // A plaintext description would be, we can turn the SELECT_CC into an AND
13983   // when the condition can be materialized as an all-ones register.  Any
13984   // single bit-test can be materialized as an all-ones register with
13985   // shift-left and shift-right-arith.
13986   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13987       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13988     SDValue AndLHS = N0->getOperand(0);
13989     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13990     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13991       // Shift the tested bit over the sign bit.
13992       APInt AndMask = ConstAndRHS->getAPIntValue();
13993       SDValue ShlAmt =
13994         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13995                         getShiftAmountTy(AndLHS.getValueType()));
13996       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13997
13998       // Now arithmetic right shift it all the way over, so the result is either
13999       // all-ones, or zero.
14000       SDValue ShrAmt =
14001         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
14002                         getShiftAmountTy(Shl.getValueType()));
14003       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
14004
14005       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
14006     }
14007   }
14008
14009   // fold select C, 16, 0 -> shl C, 4
14010   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
14011       TLI.getBooleanContents(N0.getValueType()) ==
14012           TargetLowering::ZeroOrOneBooleanContent) {
14013
14014     // If the caller doesn't want us to simplify this into a zext of a compare,
14015     // don't do it.
14016     if (NotExtCompare && N2C->isOne())
14017       return SDValue();
14018
14019     // Get a SetCC of the condition
14020     // NOTE: Don't create a SETCC if it's not legal on this target.
14021     if (!LegalOperations ||
14022         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
14023       SDValue Temp, SCC;
14024       // cast from setcc result type to select result type
14025       if (LegalTypes) {
14026         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
14027                             N0, N1, CC);
14028         if (N2.getValueType().bitsLT(SCC.getValueType()))
14029           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
14030                                         N2.getValueType());
14031         else
14032           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14033                              N2.getValueType(), SCC);
14034       } else {
14035         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
14036         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
14037                            N2.getValueType(), SCC);
14038       }
14039
14040       AddToWorklist(SCC.getNode());
14041       AddToWorklist(Temp.getNode());
14042
14043       if (N2C->isOne())
14044         return Temp;
14045
14046       // shl setcc result by log2 n2c
14047       return DAG.getNode(
14048           ISD::SHL, DL, N2.getValueType(), Temp,
14049           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
14050                           getShiftAmountTy(Temp.getValueType())));
14051     }
14052   }
14053
14054   // Check to see if this is an integer abs.
14055   // select_cc setg[te] X,  0,  X, -X ->
14056   // select_cc setgt    X, -1,  X, -X ->
14057   // select_cc setl[te] X,  0, -X,  X ->
14058   // select_cc setlt    X,  1, -X,  X ->
14059   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
14060   if (N1C) {
14061     ConstantSDNode *SubC = nullptr;
14062     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
14063          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
14064         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
14065       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
14066     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
14067               (N1C->isOne() && CC == ISD::SETLT)) &&
14068              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
14069       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
14070
14071     EVT XType = N0.getValueType();
14072     if (SubC && SubC->isNullValue() && XType.isInteger()) {
14073       SDLoc DL(N0);
14074       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
14075                                   N0,
14076                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
14077                                          getShiftAmountTy(N0.getValueType())));
14078       SDValue Add = DAG.getNode(ISD::ADD, DL,
14079                                 XType, N0, Shift);
14080       AddToWorklist(Shift.getNode());
14081       AddToWorklist(Add.getNode());
14082       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
14083     }
14084   }
14085
14086   return SDValue();
14087 }
14088
14089 /// This is a stub for TargetLowering::SimplifySetCC.
14090 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
14091                                    SDValue N1, ISD::CondCode Cond,
14092                                    SDLoc DL, bool foldBooleans) {
14093   TargetLowering::DAGCombinerInfo
14094     DagCombineInfo(DAG, Level, false, this);
14095   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
14096 }
14097
14098 /// Given an ISD::SDIV node expressing a divide by constant, return
14099 /// a DAG expression to select that will generate the same value by multiplying
14100 /// by a magic number.
14101 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14102 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
14103   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14104   if (!C)
14105     return SDValue();
14106
14107   // Avoid division by zero.
14108   if (C->isNullValue())
14109     return SDValue();
14110
14111   std::vector<SDNode*> Built;
14112   SDValue S =
14113       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14114
14115   for (SDNode *N : Built)
14116     AddToWorklist(N);
14117   return S;
14118 }
14119
14120 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14121 /// DAG expression that will generate the same value by right shifting.
14122 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14123   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14124   if (!C)
14125     return SDValue();
14126
14127   // Avoid division by zero.
14128   if (C->isNullValue())
14129     return SDValue();
14130
14131   std::vector<SDNode *> Built;
14132   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14133
14134   for (SDNode *N : Built)
14135     AddToWorklist(N);
14136   return S;
14137 }
14138
14139 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14140 /// expression that will generate the same value by multiplying by a magic
14141 /// number.
14142 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14143 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14144   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14145   if (!C)
14146     return SDValue();
14147
14148   // Avoid division by zero.
14149   if (C->isNullValue())
14150     return SDValue();
14151
14152   std::vector<SDNode*> Built;
14153   SDValue S =
14154       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14155
14156   for (SDNode *N : Built)
14157     AddToWorklist(N);
14158   return S;
14159 }
14160
14161 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14162   if (Level >= AfterLegalizeDAG)
14163     return SDValue();
14164
14165   // Expose the DAG combiner to the target combiner implementations.
14166   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14167
14168   unsigned Iterations = 0;
14169   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14170     if (Iterations) {
14171       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14172       // For the reciprocal, we need to find the zero of the function:
14173       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14174       //     =>
14175       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14176       //     does not require additional intermediate precision]
14177       EVT VT = Op.getValueType();
14178       SDLoc DL(Op);
14179       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14180
14181       AddToWorklist(Est.getNode());
14182
14183       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14184       for (unsigned i = 0; i < Iterations; ++i) {
14185         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14186         AddToWorklist(NewEst.getNode());
14187
14188         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14189         AddToWorklist(NewEst.getNode());
14190
14191         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14192         AddToWorklist(NewEst.getNode());
14193
14194         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14195         AddToWorklist(Est.getNode());
14196       }
14197     }
14198     return Est;
14199   }
14200
14201   return SDValue();
14202 }
14203
14204 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14205 /// For the reciprocal sqrt, we need to find the zero of the function:
14206 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14207 ///     =>
14208 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14209 /// As a result, we precompute A/2 prior to the iteration loop.
14210 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14211                                           unsigned Iterations,
14212                                           SDNodeFlags *Flags) {
14213   EVT VT = Arg.getValueType();
14214   SDLoc DL(Arg);
14215   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14216
14217   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14218   // this entire sequence requires only one FP constant.
14219   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14220   AddToWorklist(HalfArg.getNode());
14221
14222   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14223   AddToWorklist(HalfArg.getNode());
14224
14225   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14226   for (unsigned i = 0; i < Iterations; ++i) {
14227     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14228     AddToWorklist(NewEst.getNode());
14229
14230     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14231     AddToWorklist(NewEst.getNode());
14232
14233     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14234     AddToWorklist(NewEst.getNode());
14235
14236     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14237     AddToWorklist(Est.getNode());
14238   }
14239   return Est;
14240 }
14241
14242 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14243 /// For the reciprocal sqrt, we need to find the zero of the function:
14244 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14245 ///     =>
14246 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14247 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14248                                           unsigned Iterations,
14249                                           SDNodeFlags *Flags) {
14250   EVT VT = Arg.getValueType();
14251   SDLoc DL(Arg);
14252   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14253   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14254
14255   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14256   for (unsigned i = 0; i < Iterations; ++i) {
14257     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14258     AddToWorklist(HalfEst.getNode());
14259
14260     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14261     AddToWorklist(Est.getNode());
14262
14263     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14264     AddToWorklist(Est.getNode());
14265
14266     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14267     AddToWorklist(Est.getNode());
14268
14269     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14270     AddToWorklist(Est.getNode());
14271   }
14272   return Est;
14273 }
14274
14275 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14276   if (Level >= AfterLegalizeDAG)
14277     return SDValue();
14278
14279   // Expose the DAG combiner to the target combiner implementations.
14280   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14281   unsigned Iterations = 0;
14282   bool UseOneConstNR = false;
14283   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14284     AddToWorklist(Est.getNode());
14285     if (Iterations) {
14286       Est = UseOneConstNR ?
14287         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14288         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14289     }
14290     return Est;
14291   }
14292
14293   return SDValue();
14294 }
14295
14296 /// Return true if base is a frame index, which is known not to alias with
14297 /// anything but itself.  Provides base object and offset as results.
14298 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14299                            const GlobalValue *&GV, const void *&CV) {
14300   // Assume it is a primitive operation.
14301   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14302
14303   // If it's an adding a simple constant then integrate the offset.
14304   if (Base.getOpcode() == ISD::ADD) {
14305     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14306       Base = Base.getOperand(0);
14307       Offset += C->getZExtValue();
14308     }
14309   }
14310
14311   // Return the underlying GlobalValue, and update the Offset.  Return false
14312   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14313   // by multiple nodes with different offsets.
14314   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14315     GV = G->getGlobal();
14316     Offset += G->getOffset();
14317     return false;
14318   }
14319
14320   // Return the underlying Constant value, and update the Offset.  Return false
14321   // for ConstantSDNodes since the same constant pool entry may be represented
14322   // by multiple nodes with different offsets.
14323   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14324     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14325                                          : (const void *)C->getConstVal();
14326     Offset += C->getOffset();
14327     return false;
14328   }
14329   // If it's any of the following then it can't alias with anything but itself.
14330   return isa<FrameIndexSDNode>(Base);
14331 }
14332
14333 /// Return true if there is any possibility that the two addresses overlap.
14334 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14335   // If they are the same then they must be aliases.
14336   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14337
14338   // If they are both volatile then they cannot be reordered.
14339   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14340
14341   // If one operation reads from invariant memory, and the other may store, they
14342   // cannot alias. These should really be checking the equivalent of mayWrite,
14343   // but it only matters for memory nodes other than load /store.
14344   if (Op0->isInvariant() && Op1->writeMem())
14345     return false;
14346
14347   if (Op1->isInvariant() && Op0->writeMem())
14348     return false;
14349
14350   // Gather base node and offset information.
14351   SDValue Base1, Base2;
14352   int64_t Offset1, Offset2;
14353   const GlobalValue *GV1, *GV2;
14354   const void *CV1, *CV2;
14355   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14356                                       Base1, Offset1, GV1, CV1);
14357   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14358                                       Base2, Offset2, GV2, CV2);
14359
14360   // If they have a same base address then check to see if they overlap.
14361   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14362     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14363              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14364
14365   // It is possible for different frame indices to alias each other, mostly
14366   // when tail call optimization reuses return address slots for arguments.
14367   // To catch this case, look up the actual index of frame indices to compute
14368   // the real alias relationship.
14369   if (isFrameIndex1 && isFrameIndex2) {
14370     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14371     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14372     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14373     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14374              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14375   }
14376
14377   // Otherwise, if we know what the bases are, and they aren't identical, then
14378   // we know they cannot alias.
14379   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14380     return false;
14381
14382   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14383   // compared to the size and offset of the access, we may be able to prove they
14384   // do not alias.  This check is conservative for now to catch cases created by
14385   // splitting vector types.
14386   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14387       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14388       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14389        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14390       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14391     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14392     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14393
14394     // There is no overlap between these relatively aligned accesses of similar
14395     // size, return no alias.
14396     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14397         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14398       return false;
14399   }
14400
14401   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14402                    ? CombinerGlobalAA
14403                    : DAG.getSubtarget().useAA();
14404 #ifndef NDEBUG
14405   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14406       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14407     UseAA = false;
14408 #endif
14409   if (UseAA &&
14410       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14411     // Use alias analysis information.
14412     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14413                                  Op1->getSrcValueOffset());
14414     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14415         Op0->getSrcValueOffset() - MinOffset;
14416     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14417         Op1->getSrcValueOffset() - MinOffset;
14418     AliasResult AAResult =
14419         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14420                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14421                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14422                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14423     if (AAResult == NoAlias)
14424       return false;
14425   }
14426
14427   // Otherwise we have to assume they alias.
14428   return true;
14429 }
14430
14431 /// Walk up chain skipping non-aliasing memory nodes,
14432 /// looking for aliasing nodes and adding them to the Aliases vector.
14433 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14434                                    SmallVectorImpl<SDValue> &Aliases) {
14435   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14436   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14437
14438   // Get alias information for node.
14439   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14440
14441   // Starting off.
14442   Chains.push_back(OriginalChain);
14443   unsigned Depth = 0;
14444
14445   // Look at each chain and determine if it is an alias.  If so, add it to the
14446   // aliases list.  If not, then continue up the chain looking for the next
14447   // candidate.
14448   while (!Chains.empty()) {
14449     SDValue Chain = Chains.pop_back_val();
14450
14451     // For TokenFactor nodes, look at each operand and only continue up the
14452     // chain until we reach the depth limit.
14453     //
14454     // FIXME: The depth check could be made to return the last non-aliasing
14455     // chain we found before we hit a tokenfactor rather than the original
14456     // chain.
14457     if (Depth > 6) {
14458       Aliases.clear();
14459       Aliases.push_back(OriginalChain);
14460       return;
14461     }
14462
14463     // Don't bother if we've been before.
14464     if (!Visited.insert(Chain.getNode()).second)
14465       continue;
14466
14467     switch (Chain.getOpcode()) {
14468     case ISD::EntryToken:
14469       // Entry token is ideal chain operand, but handled in FindBetterChain.
14470       break;
14471
14472     case ISD::LOAD:
14473     case ISD::STORE: {
14474       // Get alias information for Chain.
14475       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14476           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14477
14478       // If chain is alias then stop here.
14479       if (!(IsLoad && IsOpLoad) &&
14480           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14481         Aliases.push_back(Chain);
14482       } else {
14483         // Look further up the chain.
14484         Chains.push_back(Chain.getOperand(0));
14485         ++Depth;
14486       }
14487       break;
14488     }
14489
14490     case ISD::TokenFactor:
14491       // We have to check each of the operands of the token factor for "small"
14492       // token factors, so we queue them up.  Adding the operands to the queue
14493       // (stack) in reverse order maintains the original order and increases the
14494       // likelihood that getNode will find a matching token factor (CSE.)
14495       if (Chain.getNumOperands() > 16) {
14496         Aliases.push_back(Chain);
14497         break;
14498       }
14499       for (unsigned n = Chain.getNumOperands(); n;)
14500         Chains.push_back(Chain.getOperand(--n));
14501       ++Depth;
14502       break;
14503
14504     default:
14505       // For all other instructions we will just have to take what we can get.
14506       Aliases.push_back(Chain);
14507       break;
14508     }
14509   }
14510
14511   // We need to be careful here to also search for aliases through the
14512   // value operand of a store, etc. Consider the following situation:
14513   //   Token1 = ...
14514   //   L1 = load Token1, %52
14515   //   S1 = store Token1, L1, %51
14516   //   L2 = load Token1, %52+8
14517   //   S2 = store Token1, L2, %51+8
14518   //   Token2 = Token(S1, S2)
14519   //   L3 = load Token2, %53
14520   //   S3 = store Token2, L3, %52
14521   //   L4 = load Token2, %53+8
14522   //   S4 = store Token2, L4, %52+8
14523   // If we search for aliases of S3 (which loads address %52), and we look
14524   // only through the chain, then we'll miss the trivial dependence on L1
14525   // (which also loads from %52). We then might change all loads and
14526   // stores to use Token1 as their chain operand, which could result in
14527   // copying %53 into %52 before copying %52 into %51 (which should
14528   // happen first).
14529   //
14530   // The problem is, however, that searching for such data dependencies
14531   // can become expensive, and the cost is not directly related to the
14532   // chain depth. Instead, we'll rule out such configurations here by
14533   // insisting that we've visited all chain users (except for users
14534   // of the original chain, which is not necessary). When doing this,
14535   // we need to look through nodes we don't care about (otherwise, things
14536   // like register copies will interfere with trivial cases).
14537
14538   SmallVector<const SDNode *, 16> Worklist;
14539   for (const SDNode *N : Visited)
14540     if (N != OriginalChain.getNode())
14541       Worklist.push_back(N);
14542
14543   while (!Worklist.empty()) {
14544     const SDNode *M = Worklist.pop_back_val();
14545
14546     // We have already visited M, and want to make sure we've visited any uses
14547     // of M that we care about. For uses that we've not visisted, and don't
14548     // care about, queue them to the worklist.
14549
14550     for (SDNode::use_iterator UI = M->use_begin(),
14551          UIE = M->use_end(); UI != UIE; ++UI)
14552       if (UI.getUse().getValueType() == MVT::Other &&
14553           Visited.insert(*UI).second) {
14554         if (isa<MemSDNode>(*UI)) {
14555           // We've not visited this use, and we care about it (it could have an
14556           // ordering dependency with the original node).
14557           Aliases.clear();
14558           Aliases.push_back(OriginalChain);
14559           return;
14560         }
14561
14562         // We've not visited this use, but we don't care about it. Mark it as
14563         // visited and enqueue it to the worklist.
14564         Worklist.push_back(*UI);
14565       }
14566   }
14567 }
14568
14569 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14570 /// (aliasing node.)
14571 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14572   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14573
14574   // Accumulate all the aliases to this node.
14575   GatherAllAliases(N, OldChain, Aliases);
14576
14577   // If no operands then chain to entry token.
14578   if (Aliases.size() == 0)
14579     return DAG.getEntryNode();
14580
14581   // If a single operand then chain to it.  We don't need to revisit it.
14582   if (Aliases.size() == 1)
14583     return Aliases[0];
14584
14585   // Construct a custom tailored token factor.
14586   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14587 }
14588
14589 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14590   // This holds the base pointer, index, and the offset in bytes from the base
14591   // pointer.
14592   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14593
14594   // We must have a base and an offset.
14595   if (!BasePtr.Base.getNode())
14596     return false;
14597
14598   // Do not handle stores to undef base pointers.
14599   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14600     return false;
14601
14602   SmallVector<StoreSDNode *, 8> ChainedStores;
14603   ChainedStores.push_back(St);
14604
14605   // Walk up the chain and look for nodes with offsets from the same
14606   // base pointer. Stop when reaching an instruction with a different kind
14607   // or instruction which has a different base pointer.
14608   StoreSDNode *Index = St;
14609   while (Index) {
14610     // If the chain has more than one use, then we can't reorder the mem ops.
14611     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14612       break;
14613
14614     if (Index->isVolatile() || Index->isIndexed())
14615       break;
14616
14617     // Find the base pointer and offset for this memory node.
14618     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14619
14620     // Check that the base pointer is the same as the original one.
14621     if (!Ptr.equalBaseIndex(BasePtr))
14622       break;
14623
14624     // Find the next memory operand in the chain. If the next operand in the
14625     // chain is a store then move up and continue the scan with the next
14626     // memory operand. If the next operand is a load save it and use alias
14627     // information to check if it interferes with anything.
14628     SDNode *NextInChain = Index->getChain().getNode();
14629     while (true) {
14630       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14631         // We found a store node. Use it for the next iteration.
14632         ChainedStores.push_back(STn);
14633         Index = STn;
14634         break;
14635       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14636         NextInChain = Ldn->getChain().getNode();
14637         continue;
14638       } else {
14639         Index = nullptr;
14640         break;
14641       }
14642     }
14643   }
14644
14645   bool MadeChange = false;
14646   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14647
14648   for (StoreSDNode *ChainedStore : ChainedStores) {
14649     SDValue Chain = ChainedStore->getChain();
14650     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14651
14652     if (Chain != BetterChain) {
14653       MadeChange = true;
14654       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14655     }
14656   }
14657
14658   // Do all replacements after finding the replacements to make to avoid making
14659   // the chains more complicated by introducing new TokenFactors.
14660   for (auto Replacement : BetterChains)
14661     replaceStoreChain(Replacement.first, Replacement.second);
14662
14663   return MadeChange;
14664 }
14665
14666 /// This is the entry point for the file.
14667 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14668                            CodeGenOpt::Level OptLevel) {
14669   /// This is the main entry point to this class.
14670   DAGCombiner(*this, AA, OptLevel).Run(Level);
14671 }