[DAGCombiner] Convert constant AND masks to shuffle clear masks down to the byte...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitBSWAP(SDNode *N);
259     SDValue visitCTLZ(SDNode *N);
260     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTTZ(SDNode *N);
262     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTPOP(SDNode *N);
264     SDValue visitSELECT(SDNode *N);
265     SDValue visitVSELECT(SDNode *N);
266     SDValue visitSELECT_CC(SDNode *N);
267     SDValue visitSETCC(SDNode *N);
268     SDValue visitSIGN_EXTEND(SDNode *N);
269     SDValue visitZERO_EXTEND(SDNode *N);
270     SDValue visitANY_EXTEND(SDNode *N);
271     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273     SDValue visitTRUNCATE(SDNode *N);
274     SDValue visitBITCAST(SDNode *N);
275     SDValue visitBUILD_PAIR(SDNode *N);
276     SDValue visitFADD(SDNode *N);
277     SDValue visitFSUB(SDNode *N);
278     SDValue visitFMUL(SDNode *N);
279     SDValue visitFMA(SDNode *N);
280     SDValue visitFDIV(SDNode *N);
281     SDValue visitFREM(SDNode *N);
282     SDValue visitFSQRT(SDNode *N);
283     SDValue visitFCOPYSIGN(SDNode *N);
284     SDValue visitSINT_TO_FP(SDNode *N);
285     SDValue visitUINT_TO_FP(SDNode *N);
286     SDValue visitFP_TO_SINT(SDNode *N);
287     SDValue visitFP_TO_UINT(SDNode *N);
288     SDValue visitFP_ROUND(SDNode *N);
289     SDValue visitFP_ROUND_INREG(SDNode *N);
290     SDValue visitFP_EXTEND(SDNode *N);
291     SDValue visitFNEG(SDNode *N);
292     SDValue visitFABS(SDNode *N);
293     SDValue visitFCEIL(SDNode *N);
294     SDValue visitFTRUNC(SDNode *N);
295     SDValue visitFFLOOR(SDNode *N);
296     SDValue visitFMINNUM(SDNode *N);
297     SDValue visitFMAXNUM(SDNode *N);
298     SDValue visitBRCOND(SDNode *N);
299     SDValue visitBR_CC(SDNode *N);
300     SDValue visitLOAD(SDNode *N);
301     SDValue visitSTORE(SDNode *N);
302     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304     SDValue visitBUILD_VECTOR(SDNode *N);
305     SDValue visitCONCAT_VECTORS(SDNode *N);
306     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307     SDValue visitVECTOR_SHUFFLE(SDNode *N);
308     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309     SDValue visitINSERT_SUBVECTOR(SDNode *N);
310     SDValue visitMLOAD(SDNode *N);
311     SDValue visitMSTORE(SDNode *N);
312     SDValue visitMGATHER(SDNode *N);
313     SDValue visitMSCATTER(SDNode *N);
314     SDValue visitFP_TO_FP16(SDNode *N);
315
316     SDValue visitFADDForFMACombine(SDNode *N);
317     SDValue visitFSUBForFMACombine(SDNode *N);
318
319     SDValue XformToShuffleWithZero(SDNode *N);
320     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
321
322     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
323
324     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328                              SDValue N3, ISD::CondCode CC,
329                              bool NotExtCompare = false);
330     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331                           SDLoc DL, bool foldBooleans = true);
332
333     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
334                            SDValue &CC) const;
335     bool isOneUseSetCC(SDValue N) const;
336
337     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
338                                          unsigned HiOp);
339     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340     SDValue CombineExtLoad(SDNode *N);
341     SDValue combineRepeatedFPDivisors(SDNode *N);
342     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
343     SDValue BuildSDIV(SDNode *N);
344     SDValue BuildSDIVPow2(SDNode *N);
345     SDValue BuildUDIV(SDNode *N);
346     SDValue BuildReciprocalEstimate(SDValue Op);
347     SDValue BuildRsqrtEstimate(SDValue Op);
348     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
349     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
350     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
351                                bool DemandHighBits = true);
352     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
353     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
354                               SDValue InnerPos, SDValue InnerNeg,
355                               unsigned PosOpcode, unsigned NegOpcode,
356                               SDLoc DL);
357     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
358     SDValue ReduceLoadWidth(SDNode *N);
359     SDValue ReduceLoadOpStoreWidth(SDNode *N);
360     SDValue TransformFPLoadStorePair(SDNode *N);
361     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
362     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
363
364     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
365
366     /// Walk up chain skipping non-aliasing memory nodes,
367     /// looking for aliasing nodes and adding them to the Aliases vector.
368     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
369                           SmallVectorImpl<SDValue> &Aliases);
370
371     /// Return true if there is any possibility that the two addresses overlap.
372     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
373
374     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
375     /// chain (aliasing node.)
376     SDValue FindBetterChain(SDNode *N, SDValue Chain);
377
378     /// Holds a pointer to an LSBaseSDNode as well as information on where it
379     /// is located in a sequence of memory operations connected by a chain.
380     struct MemOpLink {
381       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
382       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
383       // Ptr to the mem node.
384       LSBaseSDNode *MemNode;
385       // Offset from the base ptr.
386       int64_t OffsetFromBase;
387       // What is the sequence number of this mem node.
388       // Lowest mem operand in the DAG starts at zero.
389       unsigned SequenceNum;
390     };
391
392     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
393     /// constant build_vector of the stored constant values in Stores.
394     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
395                                          SDLoc SL,
396                                          ArrayRef<MemOpLink> Stores,
397                                          EVT Ty) const;
398
399     /// This is a helper function for MergeConsecutiveStores. When the source
400     /// elements of the consecutive stores are all constants or all extracted
401     /// vector elements, try to merge them into one larger store.
402     /// \return True if a merged store was created.
403     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
404                                          EVT MemVT, unsigned NumElem,
405                                          bool IsConstantSrc, bool UseVector);
406
407     /// This is a helper function for MergeConsecutiveStores.
408     /// Stores that may be merged are placed in StoreNodes.
409     /// Loads that may alias with those stores are placed in AliasLoadNodes.
410     void getStoreMergeAndAliasCandidates(
411         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
412         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
413     
414     /// Merge consecutive store operations into a wide store.
415     /// This optimization uses wide integers or vectors when possible.
416     /// \return True if some memory operations were changed.
417     bool MergeConsecutiveStores(StoreSDNode *N);
418
419     /// \brief Try to transform a truncation where C is a constant:
420     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
421     ///
422     /// \p N needs to be a truncation and its first operand an AND. Other
423     /// requirements are checked by the function (e.g. that trunc is
424     /// single-use) and if missed an empty SDValue is returned.
425     SDValue distributeTruncateThroughAnd(SDNode *N);
426
427   public:
428     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
429         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
430           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
431       auto *F = DAG.getMachineFunction().getFunction();
432       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
433                     F->hasFnAttribute(Attribute::MinSize);
434     }
435
436     /// Runs the dag combiner on all nodes in the work list
437     void Run(CombineLevel AtLevel);
438
439     SelectionDAG &getDAG() const { return DAG; }
440
441     /// Returns a type large enough to hold any valid shift amount - before type
442     /// legalization these can be huge.
443     EVT getShiftAmountTy(EVT LHSTy) {
444       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
445       if (LHSTy.isVector())
446         return LHSTy;
447       auto &DL = DAG.getDataLayout();
448       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
449                         : TLI.getPointerTy(DL);
450     }
451
452     /// This method returns true if we are running before type legalization or
453     /// if the specified VT is legal.
454     bool isTypeLegal(const EVT &VT) {
455       if (!LegalTypes) return true;
456       return TLI.isTypeLegal(VT);
457     }
458
459     /// Convenience wrapper around TargetLowering::getSetCCResultType
460     EVT getSetCCResultType(EVT VT) const {
461       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
462     }
463   };
464 }
465
466
467 namespace {
468 /// This class is a DAGUpdateListener that removes any deleted
469 /// nodes from the worklist.
470 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
471   DAGCombiner &DC;
472 public:
473   explicit WorklistRemover(DAGCombiner &dc)
474     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
475
476   void NodeDeleted(SDNode *N, SDNode *E) override {
477     DC.removeFromWorklist(N);
478   }
479 };
480 }
481
482 //===----------------------------------------------------------------------===//
483 //  TargetLowering::DAGCombinerInfo implementation
484 //===----------------------------------------------------------------------===//
485
486 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
487   ((DAGCombiner*)DC)->AddToWorklist(N);
488 }
489
490 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
491   ((DAGCombiner*)DC)->removeFromWorklist(N);
492 }
493
494 SDValue TargetLowering::DAGCombinerInfo::
495 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
496   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
497 }
498
499 SDValue TargetLowering::DAGCombinerInfo::
500 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
501   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
502 }
503
504
505 SDValue TargetLowering::DAGCombinerInfo::
506 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
507   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
508 }
509
510 void TargetLowering::DAGCombinerInfo::
511 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
512   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
513 }
514
515 //===----------------------------------------------------------------------===//
516 // Helper Functions
517 //===----------------------------------------------------------------------===//
518
519 void DAGCombiner::deleteAndRecombine(SDNode *N) {
520   removeFromWorklist(N);
521
522   // If the operands of this node are only used by the node, they will now be
523   // dead. Make sure to re-visit them and recursively delete dead nodes.
524   for (const SDValue &Op : N->ops())
525     // For an operand generating multiple values, one of the values may
526     // become dead allowing further simplification (e.g. split index
527     // arithmetic from an indexed load).
528     if (Op->hasOneUse() || Op->getNumValues() > 1)
529       AddToWorklist(Op.getNode());
530
531   DAG.DeleteNode(N);
532 }
533
534 /// Return 1 if we can compute the negated form of the specified expression for
535 /// the same cost as the expression itself, or 2 if we can compute the negated
536 /// form more cheaply than the expression itself.
537 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
538                                const TargetLowering &TLI,
539                                const TargetOptions *Options,
540                                unsigned Depth = 0) {
541   // fneg is removable even if it has multiple uses.
542   if (Op.getOpcode() == ISD::FNEG) return 2;
543
544   // Don't allow anything with multiple uses.
545   if (!Op.hasOneUse()) return 0;
546
547   // Don't recurse exponentially.
548   if (Depth > 6) return 0;
549
550   switch (Op.getOpcode()) {
551   default: return false;
552   case ISD::ConstantFP:
553     // Don't invert constant FP values after legalize.  The negated constant
554     // isn't necessarily legal.
555     return LegalOperations ? 0 : 1;
556   case ISD::FADD:
557     // FIXME: determine better conditions for this xform.
558     if (!Options->UnsafeFPMath) return 0;
559
560     // After operation legalization, it might not be legal to create new FSUBs.
561     if (LegalOperations &&
562         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
563       return 0;
564
565     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572   case ISD::FSUB:
573     // We can't turn -(A-B) into B-A when we honor signed zeros.
574     if (!Options->UnsafeFPMath) return 0;
575
576     // fold (fneg (fsub A, B)) -> (fsub B, A)
577     return 1;
578
579   case ISD::FMUL:
580   case ISD::FDIV:
581     if (Options->HonorSignDependentRoundingFPMath()) return 0;
582
583     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
584     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
585                                     Options, Depth + 1))
586       return V;
587
588     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
589                               Depth + 1);
590
591   case ISD::FP_EXTEND:
592   case ISD::FP_ROUND:
593   case ISD::FSIN:
594     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
595                               Depth + 1);
596   }
597 }
598
599 /// If isNegatibleForFree returns true, return the newly negated expression.
600 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
601                                     bool LegalOperations, unsigned Depth = 0) {
602   const TargetOptions &Options = DAG.getTarget().Options;
603   // fneg is removable even if it has multiple uses.
604   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
605
606   // Don't allow anything with multiple uses.
607   assert(Op.hasOneUse() && "Unknown reuse!");
608
609   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
610   switch (Op.getOpcode()) {
611   default: llvm_unreachable("Unknown code");
612   case ISD::ConstantFP: {
613     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
614     V.changeSign();
615     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
616   }
617   case ISD::FADD:
618     // FIXME: determine better conditions for this xform.
619     assert(Options.UnsafeFPMath);
620
621     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
622     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
623                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
624       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
625                          GetNegatedExpression(Op.getOperand(0), DAG,
626                                               LegalOperations, Depth+1),
627                          Op.getOperand(1));
628     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
629     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
630                        GetNegatedExpression(Op.getOperand(1), DAG,
631                                             LegalOperations, Depth+1),
632                        Op.getOperand(0));
633   case ISD::FSUB:
634     // We can't turn -(A-B) into B-A when we honor signed zeros.
635     assert(Options.UnsafeFPMath);
636
637     // fold (fneg (fsub 0, B)) -> B
638     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
639       if (N0CFP->isZero())
640         return Op.getOperand(1);
641
642     // fold (fneg (fsub A, B)) -> (fsub B, A)
643     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
644                        Op.getOperand(1), Op.getOperand(0));
645
646   case ISD::FMUL:
647   case ISD::FDIV:
648     assert(!Options.HonorSignDependentRoundingFPMath());
649
650     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
651     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
652                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
653       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
654                          GetNegatedExpression(Op.getOperand(0), DAG,
655                                               LegalOperations, Depth+1),
656                          Op.getOperand(1));
657
658     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
659     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
660                        Op.getOperand(0),
661                        GetNegatedExpression(Op.getOperand(1), DAG,
662                                             LegalOperations, Depth+1));
663
664   case ISD::FP_EXTEND:
665   case ISD::FSIN:
666     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
667                        GetNegatedExpression(Op.getOperand(0), DAG,
668                                             LegalOperations, Depth+1));
669   case ISD::FP_ROUND:
670       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
671                          GetNegatedExpression(Op.getOperand(0), DAG,
672                                               LegalOperations, Depth+1),
673                          Op.getOperand(1));
674   }
675 }
676
677 // Return true if this node is a setcc, or is a select_cc
678 // that selects between the target values used for true and false, making it
679 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
680 // the appropriate nodes based on the type of node we are checking. This
681 // simplifies life a bit for the callers.
682 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
683                                     SDValue &CC) const {
684   if (N.getOpcode() == ISD::SETCC) {
685     LHS = N.getOperand(0);
686     RHS = N.getOperand(1);
687     CC  = N.getOperand(2);
688     return true;
689   }
690
691   if (N.getOpcode() != ISD::SELECT_CC ||
692       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
693       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
694     return false;
695
696   if (TLI.getBooleanContents(N.getValueType()) ==
697       TargetLowering::UndefinedBooleanContent)
698     return false;
699
700   LHS = N.getOperand(0);
701   RHS = N.getOperand(1);
702   CC  = N.getOperand(4);
703   return true;
704 }
705
706 /// Return true if this is a SetCC-equivalent operation with only one use.
707 /// If this is true, it allows the users to invert the operation for free when
708 /// it is profitable to do so.
709 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
710   SDValue N0, N1, N2;
711   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
712     return true;
713   return false;
714 }
715
716 /// Returns true if N is a BUILD_VECTOR node whose
717 /// elements are all the same constant or undefined.
718 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
719   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
720   if (!C)
721     return false;
722
723   APInt SplatUndef;
724   unsigned SplatBitSize;
725   bool HasAnyUndefs;
726   EVT EltVT = N->getValueType(0).getVectorElementType();
727   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
728                              HasAnyUndefs) &&
729           EltVT.getSizeInBits() >= SplatBitSize);
730 }
731
732 // \brief Returns the SDNode if it is a constant integer BuildVector
733 // or constant integer.
734 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
735   if (isa<ConstantSDNode>(N))
736     return N.getNode();
737   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
738     return N.getNode();
739   return nullptr;
740 }
741
742 // \brief Returns the SDNode if it is a constant float BuildVector
743 // or constant float.
744 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
745   if (isa<ConstantFPSDNode>(N))
746     return N.getNode();
747   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
748     return N.getNode();
749   return nullptr;
750 }
751
752 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
753 // int.
754 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
755   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
756     return CN;
757
758   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
759     BitVector UndefElements;
760     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
761
762     // BuildVectors can truncate their operands. Ignore that case here.
763     // FIXME: We blindly ignore splats which include undef which is overly
764     // pessimistic.
765     if (CN && UndefElements.none() &&
766         CN->getValueType(0) == N.getValueType().getScalarType())
767       return CN;
768   }
769
770   return nullptr;
771 }
772
773 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
774 // float.
775 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
776   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
777     return CN;
778
779   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
780     BitVector UndefElements;
781     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
782
783     if (CN && UndefElements.none())
784       return CN;
785   }
786
787   return nullptr;
788 }
789
790 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
791                                     SDValue N0, SDValue N1) {
792   EVT VT = N0.getValueType();
793   if (N0.getOpcode() == Opc) {
794     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
795       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
796         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
797         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
798           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
799         return SDValue();
800       }
801       if (N0.hasOneUse()) {
802         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
803         // use
804         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
805         if (!OpNode.getNode())
806           return SDValue();
807         AddToWorklist(OpNode.getNode());
808         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
809       }
810     }
811   }
812
813   if (N1.getOpcode() == Opc) {
814     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
815       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
816         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
817         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
818           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
819         return SDValue();
820       }
821       if (N1.hasOneUse()) {
822         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
823         // use
824         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
825         if (!OpNode.getNode())
826           return SDValue();
827         AddToWorklist(OpNode.getNode());
828         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
829       }
830     }
831   }
832
833   return SDValue();
834 }
835
836 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
837                                bool AddTo) {
838   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
839   ++NodesCombined;
840   DEBUG(dbgs() << "\nReplacing.1 ";
841         N->dump(&DAG);
842         dbgs() << "\nWith: ";
843         To[0].getNode()->dump(&DAG);
844         dbgs() << " and " << NumTo-1 << " other values\n");
845   for (unsigned i = 0, e = NumTo; i != e; ++i)
846     assert((!To[i].getNode() ||
847             N->getValueType(i) == To[i].getValueType()) &&
848            "Cannot combine value to value of different type!");
849
850   WorklistRemover DeadNodes(*this);
851   DAG.ReplaceAllUsesWith(N, To);
852   if (AddTo) {
853     // Push the new nodes and any users onto the worklist
854     for (unsigned i = 0, e = NumTo; i != e; ++i) {
855       if (To[i].getNode()) {
856         AddToWorklist(To[i].getNode());
857         AddUsersToWorklist(To[i].getNode());
858       }
859     }
860   }
861
862   // Finally, if the node is now dead, remove it from the graph.  The node
863   // may not be dead if the replacement process recursively simplified to
864   // something else needing this node.
865   if (N->use_empty())
866     deleteAndRecombine(N);
867   return SDValue(N, 0);
868 }
869
870 void DAGCombiner::
871 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
872   // Replace all uses.  If any nodes become isomorphic to other nodes and
873   // are deleted, make sure to remove them from our worklist.
874   WorklistRemover DeadNodes(*this);
875   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
876
877   // Push the new node and any (possibly new) users onto the worklist.
878   AddToWorklist(TLO.New.getNode());
879   AddUsersToWorklist(TLO.New.getNode());
880
881   // Finally, if the node is now dead, remove it from the graph.  The node
882   // may not be dead if the replacement process recursively simplified to
883   // something else needing this node.
884   if (TLO.Old.getNode()->use_empty())
885     deleteAndRecombine(TLO.Old.getNode());
886 }
887
888 /// Check the specified integer node value to see if it can be simplified or if
889 /// things it uses can be simplified by bit propagation. If so, return true.
890 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
891   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
892   APInt KnownZero, KnownOne;
893   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
894     return false;
895
896   // Revisit the node.
897   AddToWorklist(Op.getNode());
898
899   // Replace the old value with the new one.
900   ++NodesCombined;
901   DEBUG(dbgs() << "\nReplacing.2 ";
902         TLO.Old.getNode()->dump(&DAG);
903         dbgs() << "\nWith: ";
904         TLO.New.getNode()->dump(&DAG);
905         dbgs() << '\n');
906
907   CommitTargetLoweringOpt(TLO);
908   return true;
909 }
910
911 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
912   SDLoc dl(Load);
913   EVT VT = Load->getValueType(0);
914   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
915
916   DEBUG(dbgs() << "\nReplacing.9 ";
917         Load->dump(&DAG);
918         dbgs() << "\nWith: ";
919         Trunc.getNode()->dump(&DAG);
920         dbgs() << '\n');
921   WorklistRemover DeadNodes(*this);
922   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
923   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
924   deleteAndRecombine(Load);
925   AddToWorklist(Trunc.getNode());
926 }
927
928 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
929   Replace = false;
930   SDLoc dl(Op);
931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
932     EVT MemVT = LD->getMemoryVT();
933     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
934       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
935                                                        : ISD::EXTLOAD)
936       : LD->getExtensionType();
937     Replace = true;
938     return DAG.getExtLoad(ExtType, dl, PVT,
939                           LD->getChain(), LD->getBasePtr(),
940                           MemVT, LD->getMemOperand());
941   }
942
943   unsigned Opc = Op.getOpcode();
944   switch (Opc) {
945   default: break;
946   case ISD::AssertSext:
947     return DAG.getNode(ISD::AssertSext, dl, PVT,
948                        SExtPromoteOperand(Op.getOperand(0), PVT),
949                        Op.getOperand(1));
950   case ISD::AssertZext:
951     return DAG.getNode(ISD::AssertZext, dl, PVT,
952                        ZExtPromoteOperand(Op.getOperand(0), PVT),
953                        Op.getOperand(1));
954   case ISD::Constant: {
955     unsigned ExtOpc =
956       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
957     return DAG.getNode(ExtOpc, dl, PVT, Op);
958   }
959   }
960
961   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
962     return SDValue();
963   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
964 }
965
966 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
967   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
968     return SDValue();
969   EVT OldVT = Op.getValueType();
970   SDLoc dl(Op);
971   bool Replace = false;
972   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
973   if (!NewOp.getNode())
974     return SDValue();
975   AddToWorklist(NewOp.getNode());
976
977   if (Replace)
978     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
979   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
980                      DAG.getValueType(OldVT));
981 }
982
983 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
984   EVT OldVT = Op.getValueType();
985   SDLoc dl(Op);
986   bool Replace = false;
987   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
988   if (!NewOp.getNode())
989     return SDValue();
990   AddToWorklist(NewOp.getNode());
991
992   if (Replace)
993     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
994   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
995 }
996
997 /// Promote the specified integer binary operation if the target indicates it is
998 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
999 /// i32 since i16 instructions are longer.
1000 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1001   if (!LegalOperations)
1002     return SDValue();
1003
1004   EVT VT = Op.getValueType();
1005   if (VT.isVector() || !VT.isInteger())
1006     return SDValue();
1007
1008   // If operation type is 'undesirable', e.g. i16 on x86, consider
1009   // promoting it.
1010   unsigned Opc = Op.getOpcode();
1011   if (TLI.isTypeDesirableForOp(Opc, VT))
1012     return SDValue();
1013
1014   EVT PVT = VT;
1015   // Consult target whether it is a good idea to promote this operation and
1016   // what's the right type to promote it to.
1017   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1018     assert(PVT != VT && "Don't know what type to promote to!");
1019
1020     bool Replace0 = false;
1021     SDValue N0 = Op.getOperand(0);
1022     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1023     if (!NN0.getNode())
1024       return SDValue();
1025
1026     bool Replace1 = false;
1027     SDValue N1 = Op.getOperand(1);
1028     SDValue NN1;
1029     if (N0 == N1)
1030       NN1 = NN0;
1031     else {
1032       NN1 = PromoteOperand(N1, PVT, Replace1);
1033       if (!NN1.getNode())
1034         return SDValue();
1035     }
1036
1037     AddToWorklist(NN0.getNode());
1038     if (NN1.getNode())
1039       AddToWorklist(NN1.getNode());
1040
1041     if (Replace0)
1042       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1043     if (Replace1)
1044       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1045
1046     DEBUG(dbgs() << "\nPromoting ";
1047           Op.getNode()->dump(&DAG));
1048     SDLoc dl(Op);
1049     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1050                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1051   }
1052   return SDValue();
1053 }
1054
1055 /// Promote the specified integer shift operation if the target indicates it is
1056 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1057 /// i32 since i16 instructions are longer.
1058 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1059   if (!LegalOperations)
1060     return SDValue();
1061
1062   EVT VT = Op.getValueType();
1063   if (VT.isVector() || !VT.isInteger())
1064     return SDValue();
1065
1066   // If operation type is 'undesirable', e.g. i16 on x86, consider
1067   // promoting it.
1068   unsigned Opc = Op.getOpcode();
1069   if (TLI.isTypeDesirableForOp(Opc, VT))
1070     return SDValue();
1071
1072   EVT PVT = VT;
1073   // Consult target whether it is a good idea to promote this operation and
1074   // what's the right type to promote it to.
1075   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1076     assert(PVT != VT && "Don't know what type to promote to!");
1077
1078     bool Replace = false;
1079     SDValue N0 = Op.getOperand(0);
1080     if (Opc == ISD::SRA)
1081       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1082     else if (Opc == ISD::SRL)
1083       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1084     else
1085       N0 = PromoteOperand(N0, PVT, Replace);
1086     if (!N0.getNode())
1087       return SDValue();
1088
1089     AddToWorklist(N0.getNode());
1090     if (Replace)
1091       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1092
1093     DEBUG(dbgs() << "\nPromoting ";
1094           Op.getNode()->dump(&DAG));
1095     SDLoc dl(Op);
1096     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1097                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1098   }
1099   return SDValue();
1100 }
1101
1102 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1103   if (!LegalOperations)
1104     return SDValue();
1105
1106   EVT VT = Op.getValueType();
1107   if (VT.isVector() || !VT.isInteger())
1108     return SDValue();
1109
1110   // If operation type is 'undesirable', e.g. i16 on x86, consider
1111   // promoting it.
1112   unsigned Opc = Op.getOpcode();
1113   if (TLI.isTypeDesirableForOp(Opc, VT))
1114     return SDValue();
1115
1116   EVT PVT = VT;
1117   // Consult target whether it is a good idea to promote this operation and
1118   // what's the right type to promote it to.
1119   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1120     assert(PVT != VT && "Don't know what type to promote to!");
1121     // fold (aext (aext x)) -> (aext x)
1122     // fold (aext (zext x)) -> (zext x)
1123     // fold (aext (sext x)) -> (sext x)
1124     DEBUG(dbgs() << "\nPromoting ";
1125           Op.getNode()->dump(&DAG));
1126     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1127   }
1128   return SDValue();
1129 }
1130
1131 bool DAGCombiner::PromoteLoad(SDValue Op) {
1132   if (!LegalOperations)
1133     return false;
1134
1135   EVT VT = Op.getValueType();
1136   if (VT.isVector() || !VT.isInteger())
1137     return false;
1138
1139   // If operation type is 'undesirable', e.g. i16 on x86, consider
1140   // promoting it.
1141   unsigned Opc = Op.getOpcode();
1142   if (TLI.isTypeDesirableForOp(Opc, VT))
1143     return false;
1144
1145   EVT PVT = VT;
1146   // Consult target whether it is a good idea to promote this operation and
1147   // what's the right type to promote it to.
1148   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1149     assert(PVT != VT && "Don't know what type to promote to!");
1150
1151     SDLoc dl(Op);
1152     SDNode *N = Op.getNode();
1153     LoadSDNode *LD = cast<LoadSDNode>(N);
1154     EVT MemVT = LD->getMemoryVT();
1155     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1156       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1157                                                        : ISD::EXTLOAD)
1158       : LD->getExtensionType();
1159     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1160                                    LD->getChain(), LD->getBasePtr(),
1161                                    MemVT, LD->getMemOperand());
1162     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1163
1164     DEBUG(dbgs() << "\nPromoting ";
1165           N->dump(&DAG);
1166           dbgs() << "\nTo: ";
1167           Result.getNode()->dump(&DAG);
1168           dbgs() << '\n');
1169     WorklistRemover DeadNodes(*this);
1170     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1171     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1172     deleteAndRecombine(N);
1173     AddToWorklist(Result.getNode());
1174     return true;
1175   }
1176   return false;
1177 }
1178
1179 /// \brief Recursively delete a node which has no uses and any operands for
1180 /// which it is the only use.
1181 ///
1182 /// Note that this both deletes the nodes and removes them from the worklist.
1183 /// It also adds any nodes who have had a user deleted to the worklist as they
1184 /// may now have only one use and subject to other combines.
1185 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1186   if (!N->use_empty())
1187     return false;
1188
1189   SmallSetVector<SDNode *, 16> Nodes;
1190   Nodes.insert(N);
1191   do {
1192     N = Nodes.pop_back_val();
1193     if (!N)
1194       continue;
1195
1196     if (N->use_empty()) {
1197       for (const SDValue &ChildN : N->op_values())
1198         Nodes.insert(ChildN.getNode());
1199
1200       removeFromWorklist(N);
1201       DAG.DeleteNode(N);
1202     } else {
1203       AddToWorklist(N);
1204     }
1205   } while (!Nodes.empty());
1206   return true;
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 //  Main DAG Combiner implementation
1211 //===----------------------------------------------------------------------===//
1212
1213 void DAGCombiner::Run(CombineLevel AtLevel) {
1214   // set the instance variables, so that the various visit routines may use it.
1215   Level = AtLevel;
1216   LegalOperations = Level >= AfterLegalizeVectorOps;
1217   LegalTypes = Level >= AfterLegalizeTypes;
1218
1219   // Add all the dag nodes to the worklist.
1220   for (SDNode &Node : DAG.allnodes())
1221     AddToWorklist(&Node);
1222
1223   // Create a dummy node (which is not added to allnodes), that adds a reference
1224   // to the root node, preventing it from being deleted, and tracking any
1225   // changes of the root.
1226   HandleSDNode Dummy(DAG.getRoot());
1227
1228   // while the worklist isn't empty, find a node and
1229   // try and combine it.
1230   while (!WorklistMap.empty()) {
1231     SDNode *N;
1232     // The Worklist holds the SDNodes in order, but it may contain null entries.
1233     do {
1234       N = Worklist.pop_back_val();
1235     } while (!N);
1236
1237     bool GoodWorklistEntry = WorklistMap.erase(N);
1238     (void)GoodWorklistEntry;
1239     assert(GoodWorklistEntry &&
1240            "Found a worklist entry without a corresponding map entry!");
1241
1242     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1243     // N is deleted from the DAG, since they too may now be dead or may have a
1244     // reduced number of uses, allowing other xforms.
1245     if (recursivelyDeleteUnusedNodes(N))
1246       continue;
1247
1248     WorklistRemover DeadNodes(*this);
1249
1250     // If this combine is running after legalizing the DAG, re-legalize any
1251     // nodes pulled off the worklist.
1252     if (Level == AfterLegalizeDAG) {
1253       SmallSetVector<SDNode *, 16> UpdatedNodes;
1254       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1255
1256       for (SDNode *LN : UpdatedNodes) {
1257         AddToWorklist(LN);
1258         AddUsersToWorklist(LN);
1259       }
1260       if (!NIsValid)
1261         continue;
1262     }
1263
1264     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1265
1266     // Add any operands of the new node which have not yet been combined to the
1267     // worklist as well. Because the worklist uniques things already, this
1268     // won't repeatedly process the same operand.
1269     CombinedNodes.insert(N);
1270     for (const SDValue &ChildN : N->op_values())
1271       if (!CombinedNodes.count(ChildN.getNode()))
1272         AddToWorklist(ChildN.getNode());
1273
1274     SDValue RV = combine(N);
1275
1276     if (!RV.getNode())
1277       continue;
1278
1279     ++NodesCombined;
1280
1281     // If we get back the same node we passed in, rather than a new node or
1282     // zero, we know that the node must have defined multiple values and
1283     // CombineTo was used.  Since CombineTo takes care of the worklist
1284     // mechanics for us, we have no work to do in this case.
1285     if (RV.getNode() == N)
1286       continue;
1287
1288     assert(N->getOpcode() != ISD::DELETED_NODE &&
1289            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1290            "Node was deleted but visit returned new node!");
1291
1292     DEBUG(dbgs() << " ... into: ";
1293           RV.getNode()->dump(&DAG));
1294
1295     // Transfer debug value.
1296     DAG.TransferDbgValues(SDValue(N, 0), RV);
1297     if (N->getNumValues() == RV.getNode()->getNumValues())
1298       DAG.ReplaceAllUsesWith(N, RV.getNode());
1299     else {
1300       assert(N->getValueType(0) == RV.getValueType() &&
1301              N->getNumValues() == 1 && "Type mismatch");
1302       SDValue OpV = RV;
1303       DAG.ReplaceAllUsesWith(N, &OpV);
1304     }
1305
1306     // Push the new node and any users onto the worklist
1307     AddToWorklist(RV.getNode());
1308     AddUsersToWorklist(RV.getNode());
1309
1310     // Finally, if the node is now dead, remove it from the graph.  The node
1311     // may not be dead if the replacement process recursively simplified to
1312     // something else needing this node. This will also take care of adding any
1313     // operands which have lost a user to the worklist.
1314     recursivelyDeleteUnusedNodes(N);
1315   }
1316
1317   // If the root changed (e.g. it was a dead load, update the root).
1318   DAG.setRoot(Dummy.getValue());
1319   DAG.RemoveDeadNodes();
1320 }
1321
1322 SDValue DAGCombiner::visit(SDNode *N) {
1323   switch (N->getOpcode()) {
1324   default: break;
1325   case ISD::TokenFactor:        return visitTokenFactor(N);
1326   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1327   case ISD::ADD:                return visitADD(N);
1328   case ISD::SUB:                return visitSUB(N);
1329   case ISD::ADDC:               return visitADDC(N);
1330   case ISD::SUBC:               return visitSUBC(N);
1331   case ISD::ADDE:               return visitADDE(N);
1332   case ISD::SUBE:               return visitSUBE(N);
1333   case ISD::MUL:                return visitMUL(N);
1334   case ISD::SDIV:               return visitSDIV(N);
1335   case ISD::UDIV:               return visitUDIV(N);
1336   case ISD::SREM:               return visitSREM(N);
1337   case ISD::UREM:               return visitUREM(N);
1338   case ISD::MULHU:              return visitMULHU(N);
1339   case ISD::MULHS:              return visitMULHS(N);
1340   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1341   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1342   case ISD::SMULO:              return visitSMULO(N);
1343   case ISD::UMULO:              return visitUMULO(N);
1344   case ISD::SDIVREM:            return visitSDIVREM(N);
1345   case ISD::UDIVREM:            return visitUDIVREM(N);
1346   case ISD::AND:                return visitAND(N);
1347   case ISD::OR:                 return visitOR(N);
1348   case ISD::XOR:                return visitXOR(N);
1349   case ISD::SHL:                return visitSHL(N);
1350   case ISD::SRA:                return visitSRA(N);
1351   case ISD::SRL:                return visitSRL(N);
1352   case ISD::ROTR:
1353   case ISD::ROTL:               return visitRotate(N);
1354   case ISD::BSWAP:              return visitBSWAP(N);
1355   case ISD::CTLZ:               return visitCTLZ(N);
1356   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1357   case ISD::CTTZ:               return visitCTTZ(N);
1358   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1359   case ISD::CTPOP:              return visitCTPOP(N);
1360   case ISD::SELECT:             return visitSELECT(N);
1361   case ISD::VSELECT:            return visitVSELECT(N);
1362   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1363   case ISD::SETCC:              return visitSETCC(N);
1364   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1365   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1366   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1367   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1368   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1369   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1370   case ISD::BITCAST:            return visitBITCAST(N);
1371   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1372   case ISD::FADD:               return visitFADD(N);
1373   case ISD::FSUB:               return visitFSUB(N);
1374   case ISD::FMUL:               return visitFMUL(N);
1375   case ISD::FMA:                return visitFMA(N);
1376   case ISD::FDIV:               return visitFDIV(N);
1377   case ISD::FREM:               return visitFREM(N);
1378   case ISD::FSQRT:              return visitFSQRT(N);
1379   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1380   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1381   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1382   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1383   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1384   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1385   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1386   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1387   case ISD::FNEG:               return visitFNEG(N);
1388   case ISD::FABS:               return visitFABS(N);
1389   case ISD::FFLOOR:             return visitFFLOOR(N);
1390   case ISD::FMINNUM:            return visitFMINNUM(N);
1391   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1392   case ISD::FCEIL:              return visitFCEIL(N);
1393   case ISD::FTRUNC:             return visitFTRUNC(N);
1394   case ISD::BRCOND:             return visitBRCOND(N);
1395   case ISD::BR_CC:              return visitBR_CC(N);
1396   case ISD::LOAD:               return visitLOAD(N);
1397   case ISD::STORE:              return visitSTORE(N);
1398   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1399   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1400   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1401   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1402   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1403   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1404   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1405   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1406   case ISD::MGATHER:            return visitMGATHER(N);
1407   case ISD::MLOAD:              return visitMLOAD(N);
1408   case ISD::MSCATTER:           return visitMSCATTER(N);
1409   case ISD::MSTORE:             return visitMSTORE(N);
1410   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1411   }
1412   return SDValue();
1413 }
1414
1415 SDValue DAGCombiner::combine(SDNode *N) {
1416   SDValue RV = visit(N);
1417
1418   // If nothing happened, try a target-specific DAG combine.
1419   if (!RV.getNode()) {
1420     assert(N->getOpcode() != ISD::DELETED_NODE &&
1421            "Node was deleted but visit returned NULL!");
1422
1423     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1424         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1425
1426       // Expose the DAG combiner to the target combiner impls.
1427       TargetLowering::DAGCombinerInfo
1428         DagCombineInfo(DAG, Level, false, this);
1429
1430       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1431     }
1432   }
1433
1434   // If nothing happened still, try promoting the operation.
1435   if (!RV.getNode()) {
1436     switch (N->getOpcode()) {
1437     default: break;
1438     case ISD::ADD:
1439     case ISD::SUB:
1440     case ISD::MUL:
1441     case ISD::AND:
1442     case ISD::OR:
1443     case ISD::XOR:
1444       RV = PromoteIntBinOp(SDValue(N, 0));
1445       break;
1446     case ISD::SHL:
1447     case ISD::SRA:
1448     case ISD::SRL:
1449       RV = PromoteIntShiftOp(SDValue(N, 0));
1450       break;
1451     case ISD::SIGN_EXTEND:
1452     case ISD::ZERO_EXTEND:
1453     case ISD::ANY_EXTEND:
1454       RV = PromoteExtend(SDValue(N, 0));
1455       break;
1456     case ISD::LOAD:
1457       if (PromoteLoad(SDValue(N, 0)))
1458         RV = SDValue(N, 0);
1459       break;
1460     }
1461   }
1462
1463   // If N is a commutative binary node, try commuting it to enable more
1464   // sdisel CSE.
1465   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1466       N->getNumValues() == 1) {
1467     SDValue N0 = N->getOperand(0);
1468     SDValue N1 = N->getOperand(1);
1469
1470     // Constant operands are canonicalized to RHS.
1471     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1472       SDValue Ops[] = {N1, N0};
1473       SDNode *CSENode;
1474       if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1475         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1476                                       &BinNode->Flags);
1477       } else {
1478         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1479       }
1480       if (CSENode)
1481         return SDValue(CSENode, 0);
1482     }
1483   }
1484
1485   return RV;
1486 }
1487
1488 /// Given a node, return its input chain if it has one, otherwise return a null
1489 /// sd operand.
1490 static SDValue getInputChainForNode(SDNode *N) {
1491   if (unsigned NumOps = N->getNumOperands()) {
1492     if (N->getOperand(0).getValueType() == MVT::Other)
1493       return N->getOperand(0);
1494     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1495       return N->getOperand(NumOps-1);
1496     for (unsigned i = 1; i < NumOps-1; ++i)
1497       if (N->getOperand(i).getValueType() == MVT::Other)
1498         return N->getOperand(i);
1499   }
1500   return SDValue();
1501 }
1502
1503 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1504   // If N has two operands, where one has an input chain equal to the other,
1505   // the 'other' chain is redundant.
1506   if (N->getNumOperands() == 2) {
1507     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1508       return N->getOperand(0);
1509     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1510       return N->getOperand(1);
1511   }
1512
1513   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1514   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1515   SmallPtrSet<SDNode*, 16> SeenOps;
1516   bool Changed = false;             // If we should replace this token factor.
1517
1518   // Start out with this token factor.
1519   TFs.push_back(N);
1520
1521   // Iterate through token factors.  The TFs grows when new token factors are
1522   // encountered.
1523   for (unsigned i = 0; i < TFs.size(); ++i) {
1524     SDNode *TF = TFs[i];
1525
1526     // Check each of the operands.
1527     for (const SDValue &Op : TF->op_values()) {
1528
1529       switch (Op.getOpcode()) {
1530       case ISD::EntryToken:
1531         // Entry tokens don't need to be added to the list. They are
1532         // redundant.
1533         Changed = true;
1534         break;
1535
1536       case ISD::TokenFactor:
1537         if (Op.hasOneUse() &&
1538             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1539           // Queue up for processing.
1540           TFs.push_back(Op.getNode());
1541           // Clean up in case the token factor is removed.
1542           AddToWorklist(Op.getNode());
1543           Changed = true;
1544           break;
1545         }
1546         // Fall thru
1547
1548       default:
1549         // Only add if it isn't already in the list.
1550         if (SeenOps.insert(Op.getNode()).second)
1551           Ops.push_back(Op);
1552         else
1553           Changed = true;
1554         break;
1555       }
1556     }
1557   }
1558
1559   SDValue Result;
1560
1561   // If we've changed things around then replace token factor.
1562   if (Changed) {
1563     if (Ops.empty()) {
1564       // The entry token is the only possible outcome.
1565       Result = DAG.getEntryNode();
1566     } else {
1567       // New and improved token factor.
1568       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1569     }
1570
1571     // Add users to worklist if AA is enabled, since it may introduce
1572     // a lot of new chained token factors while removing memory deps.
1573     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1574       : DAG.getSubtarget().useAA();
1575     return CombineTo(N, Result, UseAA /*add to worklist*/);
1576   }
1577
1578   return Result;
1579 }
1580
1581 /// MERGE_VALUES can always be eliminated.
1582 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1583   WorklistRemover DeadNodes(*this);
1584   // Replacing results may cause a different MERGE_VALUES to suddenly
1585   // be CSE'd with N, and carry its uses with it. Iterate until no
1586   // uses remain, to ensure that the node can be safely deleted.
1587   // First add the users of this node to the work list so that they
1588   // can be tried again once they have new operands.
1589   AddUsersToWorklist(N);
1590   do {
1591     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1592       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1593   } while (!N->use_empty());
1594   deleteAndRecombine(N);
1595   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1596 }
1597
1598 static bool isNullConstant(SDValue V) {
1599   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1600   return Const != nullptr && Const->isNullValue();
1601 }
1602
1603 static bool isNullFPConstant(SDValue V) {
1604   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1605   return Const != nullptr && Const->isZero() && !Const->isNegative();
1606 }
1607
1608 static bool isAllOnesConstant(SDValue V) {
1609   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1610   return Const != nullptr && Const->isAllOnesValue();
1611 }
1612
1613 static bool isOneConstant(SDValue V) {
1614   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1615   return Const != nullptr && Const->isOne();
1616 }
1617
1618 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1619 /// ContantSDNode pointer else nullptr.
1620 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1621   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1622   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1623 }
1624
1625 SDValue DAGCombiner::visitADD(SDNode *N) {
1626   SDValue N0 = N->getOperand(0);
1627   SDValue N1 = N->getOperand(1);
1628   EVT VT = N0.getValueType();
1629
1630   // fold vector ops
1631   if (VT.isVector()) {
1632     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1633       return FoldedVOp;
1634
1635     // fold (add x, 0) -> x, vector edition
1636     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1637       return N0;
1638     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1639       return N1;
1640   }
1641
1642   // fold (add x, undef) -> undef
1643   if (N0.getOpcode() == ISD::UNDEF)
1644     return N0;
1645   if (N1.getOpcode() == ISD::UNDEF)
1646     return N1;
1647   // fold (add c1, c2) -> c1+c2
1648   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1649   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1650   if (N0C && N1C)
1651     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1652   // canonicalize constant to RHS
1653   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1654      !isConstantIntBuildVectorOrConstantInt(N1))
1655     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1656   // fold (add x, 0) -> x
1657   if (isNullConstant(N1))
1658     return N0;
1659   // fold (add Sym, c) -> Sym+c
1660   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1661     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1662         GA->getOpcode() == ISD::GlobalAddress)
1663       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1664                                   GA->getOffset() +
1665                                     (uint64_t)N1C->getSExtValue());
1666   // fold ((c1-A)+c2) -> (c1+c2)-A
1667   if (N1C && N0.getOpcode() == ISD::SUB)
1668     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1669       SDLoc DL(N);
1670       return DAG.getNode(ISD::SUB, DL, VT,
1671                          DAG.getConstant(N1C->getAPIntValue()+
1672                                          N0C->getAPIntValue(), DL, VT),
1673                          N0.getOperand(1));
1674     }
1675   // reassociate add
1676   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1677     return RADD;
1678   // fold ((0-A) + B) -> B-A
1679   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1680     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1681   // fold (A + (0-B)) -> A-B
1682   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1683     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1684   // fold (A+(B-A)) -> B
1685   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1686     return N1.getOperand(0);
1687   // fold ((B-A)+A) -> B
1688   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1689     return N0.getOperand(0);
1690   // fold (A+(B-(A+C))) to (B-C)
1691   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1692       N0 == N1.getOperand(1).getOperand(0))
1693     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1694                        N1.getOperand(1).getOperand(1));
1695   // fold (A+(B-(C+A))) to (B-C)
1696   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1697       N0 == N1.getOperand(1).getOperand(1))
1698     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1699                        N1.getOperand(1).getOperand(0));
1700   // fold (A+((B-A)+or-C)) to (B+or-C)
1701   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1702       N1.getOperand(0).getOpcode() == ISD::SUB &&
1703       N0 == N1.getOperand(0).getOperand(1))
1704     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1705                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1706
1707   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1708   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1709     SDValue N00 = N0.getOperand(0);
1710     SDValue N01 = N0.getOperand(1);
1711     SDValue N10 = N1.getOperand(0);
1712     SDValue N11 = N1.getOperand(1);
1713
1714     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1715       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1716                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1717                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1718   }
1719
1720   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1721     return SDValue(N, 0);
1722
1723   // fold (a+b) -> (a|b) iff a and b share no bits.
1724   if (VT.isInteger() && !VT.isVector()) {
1725     APInt LHSZero, LHSOne;
1726     APInt RHSZero, RHSOne;
1727     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1728
1729     if (LHSZero.getBoolValue()) {
1730       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1731
1732       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1733       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1734       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1735         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1736           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1737       }
1738     }
1739   }
1740
1741   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1742   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1743       isNullConstant(N1.getOperand(0).getOperand(0)))
1744     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1745                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1746                                    N1.getOperand(0).getOperand(1),
1747                                    N1.getOperand(1)));
1748   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1749       isNullConstant(N0.getOperand(0).getOperand(0)))
1750     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1751                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1752                                    N0.getOperand(0).getOperand(1),
1753                                    N0.getOperand(1)));
1754
1755   if (N1.getOpcode() == ISD::AND) {
1756     SDValue AndOp0 = N1.getOperand(0);
1757     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1758     unsigned DestBits = VT.getScalarType().getSizeInBits();
1759
1760     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1761     // and similar xforms where the inner op is either ~0 or 0.
1762     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1763       SDLoc DL(N);
1764       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1765     }
1766   }
1767
1768   // add (sext i1), X -> sub X, (zext i1)
1769   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1770       N0.getOperand(0).getValueType() == MVT::i1 &&
1771       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1772     SDLoc DL(N);
1773     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1774     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1775   }
1776
1777   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1778   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1779     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1780     if (TN->getVT() == MVT::i1) {
1781       SDLoc DL(N);
1782       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1783                                  DAG.getConstant(1, DL, VT));
1784       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1785     }
1786   }
1787
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitADDC(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   EVT VT = N0.getValueType();
1795
1796   // If the flag result is dead, turn this into an ADD.
1797   if (!N->hasAnyUseOfValue(1))
1798     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1799                      DAG.getNode(ISD::CARRY_FALSE,
1800                                  SDLoc(N), MVT::Glue));
1801
1802   // canonicalize constant to RHS.
1803   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1804   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805   if (N0C && !N1C)
1806     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1807
1808   // fold (addc x, 0) -> x + no carry out
1809   if (isNullConstant(N1))
1810     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1811                                         SDLoc(N), MVT::Glue));
1812
1813   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1814   APInt LHSZero, LHSOne;
1815   APInt RHSZero, RHSOne;
1816   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1817
1818   if (LHSZero.getBoolValue()) {
1819     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1820
1821     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1822     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1823     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1824       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1825                        DAG.getNode(ISD::CARRY_FALSE,
1826                                    SDLoc(N), MVT::Glue));
1827   }
1828
1829   return SDValue();
1830 }
1831
1832 SDValue DAGCombiner::visitADDE(SDNode *N) {
1833   SDValue N0 = N->getOperand(0);
1834   SDValue N1 = N->getOperand(1);
1835   SDValue CarryIn = N->getOperand(2);
1836
1837   // canonicalize constant to RHS
1838   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1839   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1840   if (N0C && !N1C)
1841     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1842                        N1, N0, CarryIn);
1843
1844   // fold (adde x, y, false) -> (addc x, y)
1845   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1846     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1847
1848   return SDValue();
1849 }
1850
1851 // Since it may not be valid to emit a fold to zero for vector initializers
1852 // check if we can before folding.
1853 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1854                              SelectionDAG &DAG,
1855                              bool LegalOperations, bool LegalTypes) {
1856   if (!VT.isVector())
1857     return DAG.getConstant(0, DL, VT);
1858   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1859     return DAG.getConstant(0, DL, VT);
1860   return SDValue();
1861 }
1862
1863 SDValue DAGCombiner::visitSUB(SDNode *N) {
1864   SDValue N0 = N->getOperand(0);
1865   SDValue N1 = N->getOperand(1);
1866   EVT VT = N0.getValueType();
1867
1868   // fold vector ops
1869   if (VT.isVector()) {
1870     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1871       return FoldedVOp;
1872
1873     // fold (sub x, 0) -> x, vector edition
1874     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1875       return N0;
1876   }
1877
1878   // fold (sub x, x) -> 0
1879   // FIXME: Refactor this and xor and other similar operations together.
1880   if (N0 == N1)
1881     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1882   // fold (sub c1, c2) -> c1-c2
1883   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1884   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1885   if (N0C && N1C)
1886     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1887   // fold (sub x, c) -> (add x, -c)
1888   if (N1C) {
1889     SDLoc DL(N);
1890     return DAG.getNode(ISD::ADD, DL, VT, N0,
1891                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1892   }
1893   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1894   if (isAllOnesConstant(N0))
1895     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1896   // fold A-(A-B) -> B
1897   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1898     return N1.getOperand(1);
1899   // fold (A+B)-A -> B
1900   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1901     return N0.getOperand(1);
1902   // fold (A+B)-B -> A
1903   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1904     return N0.getOperand(0);
1905   // fold C2-(A+C1) -> (C2-C1)-A
1906   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1907     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1908   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1909     SDLoc DL(N);
1910     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1911                                    DL, VT);
1912     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1913                        N1.getOperand(0));
1914   }
1915   // fold ((A+(B+or-C))-B) -> A+or-C
1916   if (N0.getOpcode() == ISD::ADD &&
1917       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1918        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1919       N0.getOperand(1).getOperand(0) == N1)
1920     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1921                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1922   // fold ((A+(C+B))-B) -> A+C
1923   if (N0.getOpcode() == ISD::ADD &&
1924       N0.getOperand(1).getOpcode() == ISD::ADD &&
1925       N0.getOperand(1).getOperand(1) == N1)
1926     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1927                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1928   // fold ((A-(B-C))-C) -> A-B
1929   if (N0.getOpcode() == ISD::SUB &&
1930       N0.getOperand(1).getOpcode() == ISD::SUB &&
1931       N0.getOperand(1).getOperand(1) == N1)
1932     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1933                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1934
1935   // If either operand of a sub is undef, the result is undef
1936   if (N0.getOpcode() == ISD::UNDEF)
1937     return N0;
1938   if (N1.getOpcode() == ISD::UNDEF)
1939     return N1;
1940
1941   // If the relocation model supports it, consider symbol offsets.
1942   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1943     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1944       // fold (sub Sym, c) -> Sym-c
1945       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1946         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1947                                     GA->getOffset() -
1948                                       (uint64_t)N1C->getSExtValue());
1949       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1950       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1951         if (GA->getGlobal() == GB->getGlobal())
1952           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1953                                  SDLoc(N), VT);
1954     }
1955
1956   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1957   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1958     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1959     if (TN->getVT() == MVT::i1) {
1960       SDLoc DL(N);
1961       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1962                                  DAG.getConstant(1, DL, VT));
1963       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1964     }
1965   }
1966
1967   return SDValue();
1968 }
1969
1970 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1971   SDValue N0 = N->getOperand(0);
1972   SDValue N1 = N->getOperand(1);
1973   EVT VT = N0.getValueType();
1974
1975   // If the flag result is dead, turn this into an SUB.
1976   if (!N->hasAnyUseOfValue(1))
1977     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1978                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1979                                  MVT::Glue));
1980
1981   // fold (subc x, x) -> 0 + no borrow
1982   if (N0 == N1) {
1983     SDLoc DL(N);
1984     return CombineTo(N, DAG.getConstant(0, DL, VT),
1985                      DAG.getNode(ISD::CARRY_FALSE, DL,
1986                                  MVT::Glue));
1987   }
1988
1989   // fold (subc x, 0) -> x + no borrow
1990   if (isNullConstant(N1))
1991     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1992                                         MVT::Glue));
1993
1994   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1995   if (isAllOnesConstant(N0))
1996     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1997                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1998                                  MVT::Glue));
1999
2000   return SDValue();
2001 }
2002
2003 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2004   SDValue N0 = N->getOperand(0);
2005   SDValue N1 = N->getOperand(1);
2006   SDValue CarryIn = N->getOperand(2);
2007
2008   // fold (sube x, y, false) -> (subc x, y)
2009   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2010     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2011
2012   return SDValue();
2013 }
2014
2015 SDValue DAGCombiner::visitMUL(SDNode *N) {
2016   SDValue N0 = N->getOperand(0);
2017   SDValue N1 = N->getOperand(1);
2018   EVT VT = N0.getValueType();
2019
2020   // fold (mul x, undef) -> 0
2021   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2022     return DAG.getConstant(0, SDLoc(N), VT);
2023
2024   bool N0IsConst = false;
2025   bool N1IsConst = false;
2026   bool N1IsOpaqueConst = false;
2027   bool N0IsOpaqueConst = false;
2028   APInt ConstValue0, ConstValue1;
2029   // fold vector ops
2030   if (VT.isVector()) {
2031     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2032       return FoldedVOp;
2033
2034     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2035     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2036   } else {
2037     N0IsConst = isa<ConstantSDNode>(N0);
2038     if (N0IsConst) {
2039       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2040       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2041     }
2042     N1IsConst = isa<ConstantSDNode>(N1);
2043     if (N1IsConst) {
2044       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2045       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2046     }
2047   }
2048
2049   // fold (mul c1, c2) -> c1*c2
2050   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2051     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2052                                       N0.getNode(), N1.getNode());
2053
2054   // canonicalize constant to RHS (vector doesn't have to splat)
2055   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2056      !isConstantIntBuildVectorOrConstantInt(N1))
2057     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2058   // fold (mul x, 0) -> 0
2059   if (N1IsConst && ConstValue1 == 0)
2060     return N1;
2061   // We require a splat of the entire scalar bit width for non-contiguous
2062   // bit patterns.
2063   bool IsFullSplat =
2064     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2065   // fold (mul x, 1) -> x
2066   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2067     return N0;
2068   // fold (mul x, -1) -> 0-x
2069   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2070     SDLoc DL(N);
2071     return DAG.getNode(ISD::SUB, DL, VT,
2072                        DAG.getConstant(0, DL, VT), N0);
2073   }
2074   // fold (mul x, (1 << c)) -> x << c
2075   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2076       IsFullSplat) {
2077     SDLoc DL(N);
2078     return DAG.getNode(ISD::SHL, DL, VT, N0,
2079                        DAG.getConstant(ConstValue1.logBase2(), DL,
2080                                        getShiftAmountTy(N0.getValueType())));
2081   }
2082   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2083   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2084       IsFullSplat) {
2085     unsigned Log2Val = (-ConstValue1).logBase2();
2086     SDLoc DL(N);
2087     // FIXME: If the input is something that is easily negated (e.g. a
2088     // single-use add), we should put the negate there.
2089     return DAG.getNode(ISD::SUB, DL, VT,
2090                        DAG.getConstant(0, DL, VT),
2091                        DAG.getNode(ISD::SHL, DL, VT, N0,
2092                             DAG.getConstant(Log2Val, DL,
2093                                       getShiftAmountTy(N0.getValueType()))));
2094   }
2095
2096   APInt Val;
2097   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2098   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2099       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2100                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2101     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2102                              N1, N0.getOperand(1));
2103     AddToWorklist(C3.getNode());
2104     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2105                        N0.getOperand(0), C3);
2106   }
2107
2108   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2109   // use.
2110   {
2111     SDValue Sh(nullptr,0), Y(nullptr,0);
2112     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2113     if (N0.getOpcode() == ISD::SHL &&
2114         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2115                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2116         N0.getNode()->hasOneUse()) {
2117       Sh = N0; Y = N1;
2118     } else if (N1.getOpcode() == ISD::SHL &&
2119                isa<ConstantSDNode>(N1.getOperand(1)) &&
2120                N1.getNode()->hasOneUse()) {
2121       Sh = N1; Y = N0;
2122     }
2123
2124     if (Sh.getNode()) {
2125       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2126                                 Sh.getOperand(0), Y);
2127       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2128                          Mul, Sh.getOperand(1));
2129     }
2130   }
2131
2132   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2133   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2134       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2135                      isa<ConstantSDNode>(N0.getOperand(1))))
2136     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2137                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2138                                    N0.getOperand(0), N1),
2139                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2140                                    N0.getOperand(1), N1));
2141
2142   // reassociate mul
2143   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2144     return RMUL;
2145
2146   return SDValue();
2147 }
2148
2149 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2150   SDValue N0 = N->getOperand(0);
2151   SDValue N1 = N->getOperand(1);
2152   EVT VT = N->getValueType(0);
2153
2154   // fold vector ops
2155   if (VT.isVector())
2156     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2157       return FoldedVOp;
2158
2159   // fold (sdiv c1, c2) -> c1/c2
2160   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2162   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2163     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2164   // fold (sdiv X, 1) -> X
2165   if (N1C && N1C->isOne())
2166     return N0;
2167   // fold (sdiv X, -1) -> 0-X
2168   if (N1C && N1C->isAllOnesValue()) {
2169     SDLoc DL(N);
2170     return DAG.getNode(ISD::SUB, DL, VT,
2171                        DAG.getConstant(0, DL, VT), N0);
2172   }
2173   // If we know the sign bits of both operands are zero, strength reduce to a
2174   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2175   if (!VT.isVector()) {
2176     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2177       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2178                          N0, N1);
2179   }
2180
2181   // fold (sdiv X, pow2) -> simple ops after legalize
2182   // FIXME: We check for the exact bit here because the generic lowering gives
2183   // better results in that case. The target-specific lowering should learn how
2184   // to handle exact sdivs efficiently.
2185   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2186       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2187       (N1C->getAPIntValue().isPowerOf2() ||
2188        (-N1C->getAPIntValue()).isPowerOf2())) {
2189     // If dividing by powers of two is cheap, then don't perform the following
2190     // fold.
2191     if (TLI.isPow2SDivCheap())
2192       return SDValue();
2193
2194     // Target-specific implementation of sdiv x, pow2.
2195     if (SDValue Res = BuildSDIVPow2(N))
2196       return Res;
2197
2198     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2199     SDLoc DL(N);
2200
2201     // Splat the sign bit into the register
2202     SDValue SGN =
2203         DAG.getNode(ISD::SRA, DL, VT, N0,
2204                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2205                                     getShiftAmountTy(N0.getValueType())));
2206     AddToWorklist(SGN.getNode());
2207
2208     // Add (N0 < 0) ? abs2 - 1 : 0;
2209     SDValue SRL =
2210         DAG.getNode(ISD::SRL, DL, VT, SGN,
2211                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2212                                     getShiftAmountTy(SGN.getValueType())));
2213     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2214     AddToWorklist(SRL.getNode());
2215     AddToWorklist(ADD.getNode());    // Divide by pow2
2216     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2217                   DAG.getConstant(lg2, DL,
2218                                   getShiftAmountTy(ADD.getValueType())));
2219
2220     // If we're dividing by a positive value, we're done.  Otherwise, we must
2221     // negate the result.
2222     if (N1C->getAPIntValue().isNonNegative())
2223       return SRA;
2224
2225     AddToWorklist(SRA.getNode());
2226     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2227   }
2228
2229   // If integer divide is expensive and we satisfy the requirements, emit an
2230   // alternate sequence.
2231   if (N1C && !TLI.isIntDivCheap())
2232     if (SDValue Op = BuildSDIV(N))
2233       return Op;
2234
2235   // undef / X -> 0
2236   if (N0.getOpcode() == ISD::UNDEF)
2237     return DAG.getConstant(0, SDLoc(N), VT);
2238   // X / undef -> undef
2239   if (N1.getOpcode() == ISD::UNDEF)
2240     return N1;
2241
2242   return SDValue();
2243 }
2244
2245 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2246   SDValue N0 = N->getOperand(0);
2247   SDValue N1 = N->getOperand(1);
2248   EVT VT = N->getValueType(0);
2249
2250   // fold vector ops
2251   if (VT.isVector())
2252     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2253       return FoldedVOp;
2254
2255   // fold (udiv c1, c2) -> c1/c2
2256   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2257   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2258   if (N0C && N1C)
2259     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2260                                                     N0C, N1C))
2261       return Folded;
2262   // fold (udiv x, (1 << c)) -> x >>u c
2263   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2264     SDLoc DL(N);
2265     return DAG.getNode(ISD::SRL, DL, VT, N0,
2266                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2267                                        getShiftAmountTy(N0.getValueType())));
2268   }
2269   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2270   if (N1.getOpcode() == ISD::SHL) {
2271     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2272       if (SHC->getAPIntValue().isPowerOf2()) {
2273         EVT ADDVT = N1.getOperand(1).getValueType();
2274         SDLoc DL(N);
2275         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2276                                   N1.getOperand(1),
2277                                   DAG.getConstant(SHC->getAPIntValue()
2278                                                                   .logBase2(),
2279                                                   DL, ADDVT));
2280         AddToWorklist(Add.getNode());
2281         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2282       }
2283     }
2284   }
2285   // fold (udiv x, c) -> alternate
2286   if (N1C && !TLI.isIntDivCheap())
2287     if (SDValue Op = BuildUDIV(N))
2288       return Op;
2289
2290   // undef / X -> 0
2291   if (N0.getOpcode() == ISD::UNDEF)
2292     return DAG.getConstant(0, SDLoc(N), VT);
2293   // X / undef -> undef
2294   if (N1.getOpcode() == ISD::UNDEF)
2295     return N1;
2296
2297   return SDValue();
2298 }
2299
2300 SDValue DAGCombiner::visitSREM(SDNode *N) {
2301   SDValue N0 = N->getOperand(0);
2302   SDValue N1 = N->getOperand(1);
2303   EVT VT = N->getValueType(0);
2304
2305   // fold (srem c1, c2) -> c1%c2
2306   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2307   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2308   if (N0C && N1C)
2309     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2310                                                     N0C, N1C))
2311       return Folded;
2312   // If we know the sign bits of both operands are zero, strength reduce to a
2313   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2314   if (!VT.isVector()) {
2315     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2316       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2317   }
2318
2319   // If X/C can be simplified by the division-by-constant logic, lower
2320   // X%C to the equivalent of X-X/C*C.
2321   if (N1C && !N1C->isNullValue()) {
2322     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2323     AddToWorklist(Div.getNode());
2324     SDValue OptimizedDiv = combine(Div.getNode());
2325     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2326       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2327                                 OptimizedDiv, N1);
2328       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2329       AddToWorklist(Mul.getNode());
2330       return Sub;
2331     }
2332   }
2333
2334   // undef % X -> 0
2335   if (N0.getOpcode() == ISD::UNDEF)
2336     return DAG.getConstant(0, SDLoc(N), VT);
2337   // X % undef -> undef
2338   if (N1.getOpcode() == ISD::UNDEF)
2339     return N1;
2340
2341   return SDValue();
2342 }
2343
2344 SDValue DAGCombiner::visitUREM(SDNode *N) {
2345   SDValue N0 = N->getOperand(0);
2346   SDValue N1 = N->getOperand(1);
2347   EVT VT = N->getValueType(0);
2348
2349   // fold (urem c1, c2) -> c1%c2
2350   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2351   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2352   if (N0C && N1C)
2353     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2354                                                     N0C, N1C))
2355       return Folded;
2356   // fold (urem x, pow2) -> (and x, pow2-1)
2357   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2358       N1C->getAPIntValue().isPowerOf2()) {
2359     SDLoc DL(N);
2360     return DAG.getNode(ISD::AND, DL, VT, N0,
2361                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2362   }
2363   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2364   if (N1.getOpcode() == ISD::SHL) {
2365     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2366       if (SHC->getAPIntValue().isPowerOf2()) {
2367         SDLoc DL(N);
2368         SDValue Add =
2369           DAG.getNode(ISD::ADD, DL, VT, N1,
2370                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2371                                  VT));
2372         AddToWorklist(Add.getNode());
2373         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2374       }
2375     }
2376   }
2377
2378   // If X/C can be simplified by the division-by-constant logic, lower
2379   // X%C to the equivalent of X-X/C*C.
2380   if (N1C && !N1C->isNullValue()) {
2381     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2382     AddToWorklist(Div.getNode());
2383     SDValue OptimizedDiv = combine(Div.getNode());
2384     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2385       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2386                                 OptimizedDiv, N1);
2387       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2388       AddToWorklist(Mul.getNode());
2389       return Sub;
2390     }
2391   }
2392
2393   // undef % X -> 0
2394   if (N0.getOpcode() == ISD::UNDEF)
2395     return DAG.getConstant(0, SDLoc(N), VT);
2396   // X % undef -> undef
2397   if (N1.getOpcode() == ISD::UNDEF)
2398     return N1;
2399
2400   return SDValue();
2401 }
2402
2403 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2404   SDValue N0 = N->getOperand(0);
2405   SDValue N1 = N->getOperand(1);
2406   EVT VT = N->getValueType(0);
2407   SDLoc DL(N);
2408
2409   // fold (mulhs x, 0) -> 0
2410   if (isNullConstant(N1))
2411     return N1;
2412   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2413   if (isOneConstant(N1)) {
2414     SDLoc DL(N);
2415     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2416                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2417                                        DL,
2418                                        getShiftAmountTy(N0.getValueType())));
2419   }
2420   // fold (mulhs x, undef) -> 0
2421   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2422     return DAG.getConstant(0, SDLoc(N), VT);
2423
2424   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2425   // plus a shift.
2426   if (VT.isSimple() && !VT.isVector()) {
2427     MVT Simple = VT.getSimpleVT();
2428     unsigned SimpleSize = Simple.getSizeInBits();
2429     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2430     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2431       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2432       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2433       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2434       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2435             DAG.getConstant(SimpleSize, DL,
2436                             getShiftAmountTy(N1.getValueType())));
2437       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2438     }
2439   }
2440
2441   return SDValue();
2442 }
2443
2444 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2445   SDValue N0 = N->getOperand(0);
2446   SDValue N1 = N->getOperand(1);
2447   EVT VT = N->getValueType(0);
2448   SDLoc DL(N);
2449
2450   // fold (mulhu x, 0) -> 0
2451   if (isNullConstant(N1))
2452     return N1;
2453   // fold (mulhu x, 1) -> 0
2454   if (isOneConstant(N1))
2455     return DAG.getConstant(0, DL, N0.getValueType());
2456   // fold (mulhu x, undef) -> 0
2457   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2458     return DAG.getConstant(0, DL, VT);
2459
2460   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2461   // plus a shift.
2462   if (VT.isSimple() && !VT.isVector()) {
2463     MVT Simple = VT.getSimpleVT();
2464     unsigned SimpleSize = Simple.getSizeInBits();
2465     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2466     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2467       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2468       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2469       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2470       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2471             DAG.getConstant(SimpleSize, DL,
2472                             getShiftAmountTy(N1.getValueType())));
2473       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2474     }
2475   }
2476
2477   return SDValue();
2478 }
2479
2480 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2481 /// give the opcodes for the two computations that are being performed. Return
2482 /// true if a simplification was made.
2483 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2484                                                 unsigned HiOp) {
2485   // If the high half is not needed, just compute the low half.
2486   bool HiExists = N->hasAnyUseOfValue(1);
2487   if (!HiExists &&
2488       (!LegalOperations ||
2489        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2490     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2491     return CombineTo(N, Res, Res);
2492   }
2493
2494   // If the low half is not needed, just compute the high half.
2495   bool LoExists = N->hasAnyUseOfValue(0);
2496   if (!LoExists &&
2497       (!LegalOperations ||
2498        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2499     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2500     return CombineTo(N, Res, Res);
2501   }
2502
2503   // If both halves are used, return as it is.
2504   if (LoExists && HiExists)
2505     return SDValue();
2506
2507   // If the two computed results can be simplified separately, separate them.
2508   if (LoExists) {
2509     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2510     AddToWorklist(Lo.getNode());
2511     SDValue LoOpt = combine(Lo.getNode());
2512     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2513         (!LegalOperations ||
2514          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2515       return CombineTo(N, LoOpt, LoOpt);
2516   }
2517
2518   if (HiExists) {
2519     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2520     AddToWorklist(Hi.getNode());
2521     SDValue HiOpt = combine(Hi.getNode());
2522     if (HiOpt.getNode() && HiOpt != Hi &&
2523         (!LegalOperations ||
2524          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2525       return CombineTo(N, HiOpt, HiOpt);
2526   }
2527
2528   return SDValue();
2529 }
2530
2531 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2532   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2533     return Res;
2534
2535   EVT VT = N->getValueType(0);
2536   SDLoc DL(N);
2537
2538   // If the type is twice as wide is legal, transform the mulhu to a wider
2539   // multiply plus a shift.
2540   if (VT.isSimple() && !VT.isVector()) {
2541     MVT Simple = VT.getSimpleVT();
2542     unsigned SimpleSize = Simple.getSizeInBits();
2543     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2544     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2545       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2546       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2547       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2548       // Compute the high part as N1.
2549       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2550             DAG.getConstant(SimpleSize, DL,
2551                             getShiftAmountTy(Lo.getValueType())));
2552       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2553       // Compute the low part as N0.
2554       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2555       return CombineTo(N, Lo, Hi);
2556     }
2557   }
2558
2559   return SDValue();
2560 }
2561
2562 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2563   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2564     return Res;
2565
2566   EVT VT = N->getValueType(0);
2567   SDLoc DL(N);
2568
2569   // If the type is twice as wide is legal, transform the mulhu to a wider
2570   // multiply plus a shift.
2571   if (VT.isSimple() && !VT.isVector()) {
2572     MVT Simple = VT.getSimpleVT();
2573     unsigned SimpleSize = Simple.getSizeInBits();
2574     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2575     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2576       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2577       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2578       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2579       // Compute the high part as N1.
2580       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2581             DAG.getConstant(SimpleSize, DL,
2582                             getShiftAmountTy(Lo.getValueType())));
2583       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2584       // Compute the low part as N0.
2585       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2586       return CombineTo(N, Lo, Hi);
2587     }
2588   }
2589
2590   return SDValue();
2591 }
2592
2593 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2594   // (smulo x, 2) -> (saddo x, x)
2595   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2596     if (C2->getAPIntValue() == 2)
2597       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2598                          N->getOperand(0), N->getOperand(0));
2599
2600   return SDValue();
2601 }
2602
2603 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2604   // (umulo x, 2) -> (uaddo x, x)
2605   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2606     if (C2->getAPIntValue() == 2)
2607       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2608                          N->getOperand(0), N->getOperand(0));
2609
2610   return SDValue();
2611 }
2612
2613 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2614   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
2615     return Res;
2616
2617   return SDValue();
2618 }
2619
2620 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2621   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
2622     return Res;
2623
2624   return SDValue();
2625 }
2626
2627 /// If this is a binary operator with two operands of the same opcode, try to
2628 /// simplify it.
2629 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2630   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2631   EVT VT = N0.getValueType();
2632   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2633
2634   // Bail early if none of these transforms apply.
2635   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2636
2637   // For each of OP in AND/OR/XOR:
2638   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2639   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2640   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2641   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2642   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2643   //
2644   // do not sink logical op inside of a vector extend, since it may combine
2645   // into a vsetcc.
2646   EVT Op0VT = N0.getOperand(0).getValueType();
2647   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2648        N0.getOpcode() == ISD::SIGN_EXTEND ||
2649        N0.getOpcode() == ISD::BSWAP ||
2650        // Avoid infinite looping with PromoteIntBinOp.
2651        (N0.getOpcode() == ISD::ANY_EXTEND &&
2652         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2653        (N0.getOpcode() == ISD::TRUNCATE &&
2654         (!TLI.isZExtFree(VT, Op0VT) ||
2655          !TLI.isTruncateFree(Op0VT, VT)) &&
2656         TLI.isTypeLegal(Op0VT))) &&
2657       !VT.isVector() &&
2658       Op0VT == N1.getOperand(0).getValueType() &&
2659       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2660     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2661                                  N0.getOperand(0).getValueType(),
2662                                  N0.getOperand(0), N1.getOperand(0));
2663     AddToWorklist(ORNode.getNode());
2664     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2665   }
2666
2667   // For each of OP in SHL/SRL/SRA/AND...
2668   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2669   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2670   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2671   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2672        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2673       N0.getOperand(1) == N1.getOperand(1)) {
2674     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2675                                  N0.getOperand(0).getValueType(),
2676                                  N0.getOperand(0), N1.getOperand(0));
2677     AddToWorklist(ORNode.getNode());
2678     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2679                        ORNode, N0.getOperand(1));
2680   }
2681
2682   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2683   // Only perform this optimization after type legalization and before
2684   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2685   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2686   // we don't want to undo this promotion.
2687   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2688   // on scalars.
2689   if ((N0.getOpcode() == ISD::BITCAST ||
2690        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2691       Level == AfterLegalizeTypes) {
2692     SDValue In0 = N0.getOperand(0);
2693     SDValue In1 = N1.getOperand(0);
2694     EVT In0Ty = In0.getValueType();
2695     EVT In1Ty = In1.getValueType();
2696     SDLoc DL(N);
2697     // If both incoming values are integers, and the original types are the
2698     // same.
2699     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2700       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2701       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2702       AddToWorklist(Op.getNode());
2703       return BC;
2704     }
2705   }
2706
2707   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2708   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2709   // If both shuffles use the same mask, and both shuffle within a single
2710   // vector, then it is worthwhile to move the swizzle after the operation.
2711   // The type-legalizer generates this pattern when loading illegal
2712   // vector types from memory. In many cases this allows additional shuffle
2713   // optimizations.
2714   // There are other cases where moving the shuffle after the xor/and/or
2715   // is profitable even if shuffles don't perform a swizzle.
2716   // If both shuffles use the same mask, and both shuffles have the same first
2717   // or second operand, then it might still be profitable to move the shuffle
2718   // after the xor/and/or operation.
2719   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2720     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2721     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2722
2723     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2724            "Inputs to shuffles are not the same type");
2725
2726     // Check that both shuffles use the same mask. The masks are known to be of
2727     // the same length because the result vector type is the same.
2728     // Check also that shuffles have only one use to avoid introducing extra
2729     // instructions.
2730     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2731         SVN0->getMask().equals(SVN1->getMask())) {
2732       SDValue ShOp = N0->getOperand(1);
2733
2734       // Don't try to fold this node if it requires introducing a
2735       // build vector of all zeros that might be illegal at this stage.
2736       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2737         if (!LegalTypes)
2738           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2739         else
2740           ShOp = SDValue();
2741       }
2742
2743       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2744       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2745       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2746       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2747         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2748                                       N0->getOperand(0), N1->getOperand(0));
2749         AddToWorklist(NewNode.getNode());
2750         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2751                                     &SVN0->getMask()[0]);
2752       }
2753
2754       // Don't try to fold this node if it requires introducing a
2755       // build vector of all zeros that might be illegal at this stage.
2756       ShOp = N0->getOperand(0);
2757       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2758         if (!LegalTypes)
2759           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2760         else
2761           ShOp = SDValue();
2762       }
2763
2764       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2765       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2766       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2767       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2768         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2769                                       N0->getOperand(1), N1->getOperand(1));
2770         AddToWorklist(NewNode.getNode());
2771         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2772                                     &SVN0->getMask()[0]);
2773       }
2774     }
2775   }
2776
2777   return SDValue();
2778 }
2779
2780 /// This contains all DAGCombine rules which reduce two values combined by
2781 /// an And operation to a single value. This makes them reusable in the context
2782 /// of visitSELECT(). Rules involving constants are not included as
2783 /// visitSELECT() already handles those cases.
2784 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2785                                   SDNode *LocReference) {
2786   EVT VT = N1.getValueType();
2787
2788   // fold (and x, undef) -> 0
2789   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2790     return DAG.getConstant(0, SDLoc(LocReference), VT);
2791   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2792   SDValue LL, LR, RL, RR, CC0, CC1;
2793   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2794     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2795     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2796
2797     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2798         LL.getValueType().isInteger()) {
2799       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2800       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2801         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2802                                      LR.getValueType(), LL, RL);
2803         AddToWorklist(ORNode.getNode());
2804         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2805       }
2806       if (isAllOnesConstant(LR)) {
2807         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2808         if (Op1 == ISD::SETEQ) {
2809           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2810                                         LR.getValueType(), LL, RL);
2811           AddToWorklist(ANDNode.getNode());
2812           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2813         }
2814         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2815         if (Op1 == ISD::SETGT) {
2816           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2817                                        LR.getValueType(), LL, RL);
2818           AddToWorklist(ORNode.getNode());
2819           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2820         }
2821       }
2822     }
2823     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2824     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2825         Op0 == Op1 && LL.getValueType().isInteger() &&
2826       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2827                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2828       SDLoc DL(N0);
2829       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2830                                     LL, DAG.getConstant(1, DL,
2831                                                         LL.getValueType()));
2832       AddToWorklist(ADDNode.getNode());
2833       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2834                           DAG.getConstant(2, DL, LL.getValueType()),
2835                           ISD::SETUGE);
2836     }
2837     // canonicalize equivalent to ll == rl
2838     if (LL == RR && LR == RL) {
2839       Op1 = ISD::getSetCCSwappedOperands(Op1);
2840       std::swap(RL, RR);
2841     }
2842     if (LL == RL && LR == RR) {
2843       bool isInteger = LL.getValueType().isInteger();
2844       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2845       if (Result != ISD::SETCC_INVALID &&
2846           (!LegalOperations ||
2847            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2848             TLI.isOperationLegal(ISD::SETCC,
2849                             getSetCCResultType(N0.getSimpleValueType())))))
2850         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2851                             LL, LR, Result);
2852     }
2853   }
2854
2855   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2856       VT.getSizeInBits() <= 64) {
2857     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2858       APInt ADDC = ADDI->getAPIntValue();
2859       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2860         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2861         // immediate for an add, but it is legal if its top c2 bits are set,
2862         // transform the ADD so the immediate doesn't need to be materialized
2863         // in a register.
2864         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2865           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2866                                              SRLI->getZExtValue());
2867           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2868             ADDC |= Mask;
2869             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2870               SDLoc DL(N0);
2871               SDValue NewAdd =
2872                 DAG.getNode(ISD::ADD, DL, VT,
2873                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2874               CombineTo(N0.getNode(), NewAdd);
2875               // Return N so it doesn't get rechecked!
2876               return SDValue(LocReference, 0);
2877             }
2878           }
2879         }
2880       }
2881     }
2882   }
2883
2884   return SDValue();
2885 }
2886
2887 SDValue DAGCombiner::visitAND(SDNode *N) {
2888   SDValue N0 = N->getOperand(0);
2889   SDValue N1 = N->getOperand(1);
2890   EVT VT = N1.getValueType();
2891
2892   // fold vector ops
2893   if (VT.isVector()) {
2894     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2895       return FoldedVOp;
2896
2897     // fold (and x, 0) -> 0, vector edition
2898     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2899       // do not return N0, because undef node may exist in N0
2900       return DAG.getConstant(
2901           APInt::getNullValue(
2902               N0.getValueType().getScalarType().getSizeInBits()),
2903           SDLoc(N), N0.getValueType());
2904     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2905       // do not return N1, because undef node may exist in N1
2906       return DAG.getConstant(
2907           APInt::getNullValue(
2908               N1.getValueType().getScalarType().getSizeInBits()),
2909           SDLoc(N), N1.getValueType());
2910
2911     // fold (and x, -1) -> x, vector edition
2912     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2913       return N1;
2914     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2915       return N0;
2916   }
2917
2918   // fold (and c1, c2) -> c1&c2
2919   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2920   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2921   if (N0C && N1C && !N1C->isOpaque())
2922     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2923   // canonicalize constant to RHS
2924   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2925      !isConstantIntBuildVectorOrConstantInt(N1))
2926     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2927   // fold (and x, -1) -> x
2928   if (isAllOnesConstant(N1))
2929     return N0;
2930   // if (and x, c) is known to be zero, return 0
2931   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2932   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2933                                    APInt::getAllOnesValue(BitWidth)))
2934     return DAG.getConstant(0, SDLoc(N), VT);
2935   // reassociate and
2936   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2937     return RAND;
2938   // fold (and (or x, C), D) -> D if (C & D) == D
2939   if (N1C && N0.getOpcode() == ISD::OR)
2940     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2941       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2942         return N1;
2943   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2944   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2945     SDValue N0Op0 = N0.getOperand(0);
2946     APInt Mask = ~N1C->getAPIntValue();
2947     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2948     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2949       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2950                                  N0.getValueType(), N0Op0);
2951
2952       // Replace uses of the AND with uses of the Zero extend node.
2953       CombineTo(N, Zext);
2954
2955       // We actually want to replace all uses of the any_extend with the
2956       // zero_extend, to avoid duplicating things.  This will later cause this
2957       // AND to be folded.
2958       CombineTo(N0.getNode(), Zext);
2959       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2960     }
2961   }
2962   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2963   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2964   // already be zero by virtue of the width of the base type of the load.
2965   //
2966   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2967   // more cases.
2968   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2969        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2970       N0.getOpcode() == ISD::LOAD) {
2971     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2972                                          N0 : N0.getOperand(0) );
2973
2974     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2975     // This can be a pure constant or a vector splat, in which case we treat the
2976     // vector as a scalar and use the splat value.
2977     APInt Constant = APInt::getNullValue(1);
2978     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2979       Constant = C->getAPIntValue();
2980     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2981       APInt SplatValue, SplatUndef;
2982       unsigned SplatBitSize;
2983       bool HasAnyUndefs;
2984       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2985                                              SplatBitSize, HasAnyUndefs);
2986       if (IsSplat) {
2987         // Undef bits can contribute to a possible optimisation if set, so
2988         // set them.
2989         SplatValue |= SplatUndef;
2990
2991         // The splat value may be something like "0x00FFFFFF", which means 0 for
2992         // the first vector value and FF for the rest, repeating. We need a mask
2993         // that will apply equally to all members of the vector, so AND all the
2994         // lanes of the constant together.
2995         EVT VT = Vector->getValueType(0);
2996         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2997
2998         // If the splat value has been compressed to a bitlength lower
2999         // than the size of the vector lane, we need to re-expand it to
3000         // the lane size.
3001         if (BitWidth > SplatBitSize)
3002           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3003                SplatBitSize < BitWidth;
3004                SplatBitSize = SplatBitSize * 2)
3005             SplatValue |= SplatValue.shl(SplatBitSize);
3006
3007         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3008         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3009         if (SplatBitSize % BitWidth == 0) {
3010           Constant = APInt::getAllOnesValue(BitWidth);
3011           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3012             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3013         }
3014       }
3015     }
3016
3017     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3018     // actually legal and isn't going to get expanded, else this is a false
3019     // optimisation.
3020     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3021                                                     Load->getValueType(0),
3022                                                     Load->getMemoryVT());
3023
3024     // Resize the constant to the same size as the original memory access before
3025     // extension. If it is still the AllOnesValue then this AND is completely
3026     // unneeded.
3027     Constant =
3028       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3029
3030     bool B;
3031     switch (Load->getExtensionType()) {
3032     default: B = false; break;
3033     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3034     case ISD::ZEXTLOAD:
3035     case ISD::NON_EXTLOAD: B = true; break;
3036     }
3037
3038     if (B && Constant.isAllOnesValue()) {
3039       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3040       // preserve semantics once we get rid of the AND.
3041       SDValue NewLoad(Load, 0);
3042       if (Load->getExtensionType() == ISD::EXTLOAD) {
3043         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3044                               Load->getValueType(0), SDLoc(Load),
3045                               Load->getChain(), Load->getBasePtr(),
3046                               Load->getOffset(), Load->getMemoryVT(),
3047                               Load->getMemOperand());
3048         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3049         if (Load->getNumValues() == 3) {
3050           // PRE/POST_INC loads have 3 values.
3051           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3052                            NewLoad.getValue(2) };
3053           CombineTo(Load, To, 3, true);
3054         } else {
3055           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3056         }
3057       }
3058
3059       // Fold the AND away, taking care not to fold to the old load node if we
3060       // replaced it.
3061       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3062
3063       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3064     }
3065   }
3066
3067   // fold (and (load x), 255) -> (zextload x, i8)
3068   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3069   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3070   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3071               (N0.getOpcode() == ISD::ANY_EXTEND &&
3072                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3073     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3074     LoadSDNode *LN0 = HasAnyExt
3075       ? cast<LoadSDNode>(N0.getOperand(0))
3076       : cast<LoadSDNode>(N0);
3077     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3078         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3079       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3080       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3081         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3082         EVT LoadedVT = LN0->getMemoryVT();
3083         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3084
3085         if (ExtVT == LoadedVT &&
3086             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3087                                                     ExtVT))) {
3088
3089           SDValue NewLoad =
3090             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3091                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3092                            LN0->getMemOperand());
3093           AddToWorklist(N);
3094           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3095           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3096         }
3097
3098         // Do not change the width of a volatile load.
3099         // Do not generate loads of non-round integer types since these can
3100         // be expensive (and would be wrong if the type is not byte sized).
3101         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3102             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3103                                                     ExtVT))) {
3104           EVT PtrType = LN0->getOperand(1).getValueType();
3105
3106           unsigned Alignment = LN0->getAlignment();
3107           SDValue NewPtr = LN0->getBasePtr();
3108
3109           // For big endian targets, we need to add an offset to the pointer
3110           // to load the correct bytes.  For little endian systems, we merely
3111           // need to read fewer bytes from the same pointer.
3112           if (DAG.getDataLayout().isBigEndian()) {
3113             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3114             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3115             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3116             SDLoc DL(LN0);
3117             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3118                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3119             Alignment = MinAlign(Alignment, PtrOff);
3120           }
3121
3122           AddToWorklist(NewPtr.getNode());
3123
3124           SDValue Load =
3125             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3126                            LN0->getChain(), NewPtr,
3127                            LN0->getPointerInfo(),
3128                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3129                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3130           AddToWorklist(N);
3131           CombineTo(LN0, Load, Load.getValue(1));
3132           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3133         }
3134       }
3135     }
3136   }
3137
3138   if (SDValue Combined = visitANDLike(N0, N1, N))
3139     return Combined;
3140
3141   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3142   if (N0.getOpcode() == N1.getOpcode())
3143     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3144       return Tmp;
3145
3146   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3147   // fold (and (sra)) -> (and (srl)) when possible.
3148   if (!VT.isVector() &&
3149       SimplifyDemandedBits(SDValue(N, 0)))
3150     return SDValue(N, 0);
3151
3152   // fold (zext_inreg (extload x)) -> (zextload x)
3153   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3154     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3155     EVT MemVT = LN0->getMemoryVT();
3156     // If we zero all the possible extended bits, then we can turn this into
3157     // a zextload if we are running before legalize or the operation is legal.
3158     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3159     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3160                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3161         ((!LegalOperations && !LN0->isVolatile()) ||
3162          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3163       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3164                                        LN0->getChain(), LN0->getBasePtr(),
3165                                        MemVT, LN0->getMemOperand());
3166       AddToWorklist(N);
3167       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3168       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3169     }
3170   }
3171   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3172   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3173       N0.hasOneUse()) {
3174     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3175     EVT MemVT = LN0->getMemoryVT();
3176     // If we zero all the possible extended bits, then we can turn this into
3177     // a zextload if we are running before legalize or the operation is legal.
3178     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3179     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3180                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3181         ((!LegalOperations && !LN0->isVolatile()) ||
3182          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3183       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3184                                        LN0->getChain(), LN0->getBasePtr(),
3185                                        MemVT, LN0->getMemOperand());
3186       AddToWorklist(N);
3187       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3188       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3189     }
3190   }
3191   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3192   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3193     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3194                                        N0.getOperand(1), false);
3195     if (BSwap.getNode())
3196       return BSwap;
3197   }
3198
3199   return SDValue();
3200 }
3201
3202 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3203 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3204                                         bool DemandHighBits) {
3205   if (!LegalOperations)
3206     return SDValue();
3207
3208   EVT VT = N->getValueType(0);
3209   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3210     return SDValue();
3211   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3212     return SDValue();
3213
3214   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3215   bool LookPassAnd0 = false;
3216   bool LookPassAnd1 = false;
3217   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3218       std::swap(N0, N1);
3219   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3220       std::swap(N0, N1);
3221   if (N0.getOpcode() == ISD::AND) {
3222     if (!N0.getNode()->hasOneUse())
3223       return SDValue();
3224     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3225     if (!N01C || N01C->getZExtValue() != 0xFF00)
3226       return SDValue();
3227     N0 = N0.getOperand(0);
3228     LookPassAnd0 = true;
3229   }
3230
3231   if (N1.getOpcode() == ISD::AND) {
3232     if (!N1.getNode()->hasOneUse())
3233       return SDValue();
3234     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3235     if (!N11C || N11C->getZExtValue() != 0xFF)
3236       return SDValue();
3237     N1 = N1.getOperand(0);
3238     LookPassAnd1 = true;
3239   }
3240
3241   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3242     std::swap(N0, N1);
3243   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3244     return SDValue();
3245   if (!N0.getNode()->hasOneUse() ||
3246       !N1.getNode()->hasOneUse())
3247     return SDValue();
3248
3249   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3250   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3251   if (!N01C || !N11C)
3252     return SDValue();
3253   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3254     return SDValue();
3255
3256   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3257   SDValue N00 = N0->getOperand(0);
3258   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3259     if (!N00.getNode()->hasOneUse())
3260       return SDValue();
3261     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3262     if (!N001C || N001C->getZExtValue() != 0xFF)
3263       return SDValue();
3264     N00 = N00.getOperand(0);
3265     LookPassAnd0 = true;
3266   }
3267
3268   SDValue N10 = N1->getOperand(0);
3269   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3270     if (!N10.getNode()->hasOneUse())
3271       return SDValue();
3272     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3273     if (!N101C || N101C->getZExtValue() != 0xFF00)
3274       return SDValue();
3275     N10 = N10.getOperand(0);
3276     LookPassAnd1 = true;
3277   }
3278
3279   if (N00 != N10)
3280     return SDValue();
3281
3282   // Make sure everything beyond the low halfword gets set to zero since the SRL
3283   // 16 will clear the top bits.
3284   unsigned OpSizeInBits = VT.getSizeInBits();
3285   if (DemandHighBits && OpSizeInBits > 16) {
3286     // If the left-shift isn't masked out then the only way this is a bswap is
3287     // if all bits beyond the low 8 are 0. In that case the entire pattern
3288     // reduces to a left shift anyway: leave it for other parts of the combiner.
3289     if (!LookPassAnd0)
3290       return SDValue();
3291
3292     // However, if the right shift isn't masked out then it might be because
3293     // it's not needed. See if we can spot that too.
3294     if (!LookPassAnd1 &&
3295         !DAG.MaskedValueIsZero(
3296             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3297       return SDValue();
3298   }
3299
3300   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3301   if (OpSizeInBits > 16) {
3302     SDLoc DL(N);
3303     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3304                       DAG.getConstant(OpSizeInBits - 16, DL,
3305                                       getShiftAmountTy(VT)));
3306   }
3307   return Res;
3308 }
3309
3310 /// Return true if the specified node is an element that makes up a 32-bit
3311 /// packed halfword byteswap.
3312 /// ((x & 0x000000ff) << 8) |
3313 /// ((x & 0x0000ff00) >> 8) |
3314 /// ((x & 0x00ff0000) << 8) |
3315 /// ((x & 0xff000000) >> 8)
3316 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3317   if (!N.getNode()->hasOneUse())
3318     return false;
3319
3320   unsigned Opc = N.getOpcode();
3321   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3322     return false;
3323
3324   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3325   if (!N1C)
3326     return false;
3327
3328   unsigned Num;
3329   switch (N1C->getZExtValue()) {
3330   default:
3331     return false;
3332   case 0xFF:       Num = 0; break;
3333   case 0xFF00:     Num = 1; break;
3334   case 0xFF0000:   Num = 2; break;
3335   case 0xFF000000: Num = 3; break;
3336   }
3337
3338   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3339   SDValue N0 = N.getOperand(0);
3340   if (Opc == ISD::AND) {
3341     if (Num == 0 || Num == 2) {
3342       // (x >> 8) & 0xff
3343       // (x >> 8) & 0xff0000
3344       if (N0.getOpcode() != ISD::SRL)
3345         return false;
3346       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3347       if (!C || C->getZExtValue() != 8)
3348         return false;
3349     } else {
3350       // (x << 8) & 0xff00
3351       // (x << 8) & 0xff000000
3352       if (N0.getOpcode() != ISD::SHL)
3353         return false;
3354       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3355       if (!C || C->getZExtValue() != 8)
3356         return false;
3357     }
3358   } else if (Opc == ISD::SHL) {
3359     // (x & 0xff) << 8
3360     // (x & 0xff0000) << 8
3361     if (Num != 0 && Num != 2)
3362       return false;
3363     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3364     if (!C || C->getZExtValue() != 8)
3365       return false;
3366   } else { // Opc == ISD::SRL
3367     // (x & 0xff00) >> 8
3368     // (x & 0xff000000) >> 8
3369     if (Num != 1 && Num != 3)
3370       return false;
3371     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3372     if (!C || C->getZExtValue() != 8)
3373       return false;
3374   }
3375
3376   if (Parts[Num])
3377     return false;
3378
3379   Parts[Num] = N0.getOperand(0).getNode();
3380   return true;
3381 }
3382
3383 /// Match a 32-bit packed halfword bswap. That is
3384 /// ((x & 0x000000ff) << 8) |
3385 /// ((x & 0x0000ff00) >> 8) |
3386 /// ((x & 0x00ff0000) << 8) |
3387 /// ((x & 0xff000000) >> 8)
3388 /// => (rotl (bswap x), 16)
3389 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3390   if (!LegalOperations)
3391     return SDValue();
3392
3393   EVT VT = N->getValueType(0);
3394   if (VT != MVT::i32)
3395     return SDValue();
3396   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3397     return SDValue();
3398
3399   // Look for either
3400   // (or (or (and), (and)), (or (and), (and)))
3401   // (or (or (or (and), (and)), (and)), (and))
3402   if (N0.getOpcode() != ISD::OR)
3403     return SDValue();
3404   SDValue N00 = N0.getOperand(0);
3405   SDValue N01 = N0.getOperand(1);
3406   SDNode *Parts[4] = {};
3407
3408   if (N1.getOpcode() == ISD::OR &&
3409       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3410     // (or (or (and), (and)), (or (and), (and)))
3411     SDValue N000 = N00.getOperand(0);
3412     if (!isBSwapHWordElement(N000, Parts))
3413       return SDValue();
3414
3415     SDValue N001 = N00.getOperand(1);
3416     if (!isBSwapHWordElement(N001, Parts))
3417       return SDValue();
3418     SDValue N010 = N01.getOperand(0);
3419     if (!isBSwapHWordElement(N010, Parts))
3420       return SDValue();
3421     SDValue N011 = N01.getOperand(1);
3422     if (!isBSwapHWordElement(N011, Parts))
3423       return SDValue();
3424   } else {
3425     // (or (or (or (and), (and)), (and)), (and))
3426     if (!isBSwapHWordElement(N1, Parts))
3427       return SDValue();
3428     if (!isBSwapHWordElement(N01, Parts))
3429       return SDValue();
3430     if (N00.getOpcode() != ISD::OR)
3431       return SDValue();
3432     SDValue N000 = N00.getOperand(0);
3433     if (!isBSwapHWordElement(N000, Parts))
3434       return SDValue();
3435     SDValue N001 = N00.getOperand(1);
3436     if (!isBSwapHWordElement(N001, Parts))
3437       return SDValue();
3438   }
3439
3440   // Make sure the parts are all coming from the same node.
3441   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3442     return SDValue();
3443
3444   SDLoc DL(N);
3445   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3446                               SDValue(Parts[0], 0));
3447
3448   // Result of the bswap should be rotated by 16. If it's not legal, then
3449   // do  (x << 16) | (x >> 16).
3450   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3451   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3452     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3453   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3454     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3455   return DAG.getNode(ISD::OR, DL, VT,
3456                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3457                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3458 }
3459
3460 /// This contains all DAGCombine rules which reduce two values combined by
3461 /// an Or operation to a single value \see visitANDLike().
3462 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3463   EVT VT = N1.getValueType();
3464   // fold (or x, undef) -> -1
3465   if (!LegalOperations &&
3466       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3467     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3468     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3469                            SDLoc(LocReference), VT);
3470   }
3471   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3472   SDValue LL, LR, RL, RR, CC0, CC1;
3473   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3474     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3475     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3476
3477     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3478       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3479       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3480       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3481         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3482                                      LR.getValueType(), LL, RL);
3483         AddToWorklist(ORNode.getNode());
3484         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3485       }
3486       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3487       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3488       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3489         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3490                                       LR.getValueType(), LL, RL);
3491         AddToWorklist(ANDNode.getNode());
3492         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3493       }
3494     }
3495     // canonicalize equivalent to ll == rl
3496     if (LL == RR && LR == RL) {
3497       Op1 = ISD::getSetCCSwappedOperands(Op1);
3498       std::swap(RL, RR);
3499     }
3500     if (LL == RL && LR == RR) {
3501       bool isInteger = LL.getValueType().isInteger();
3502       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3503       if (Result != ISD::SETCC_INVALID &&
3504           (!LegalOperations ||
3505            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3506             TLI.isOperationLegal(ISD::SETCC,
3507               getSetCCResultType(N0.getValueType())))))
3508         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3509                             LL, LR, Result);
3510     }
3511   }
3512
3513   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3514   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3515       // Don't increase # computations.
3516       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3517     // We can only do this xform if we know that bits from X that are set in C2
3518     // but not in C1 are already zero.  Likewise for Y.
3519     if (const ConstantSDNode *N0O1C =
3520         getAsNonOpaqueConstant(N0.getOperand(1))) {
3521       if (const ConstantSDNode *N1O1C =
3522           getAsNonOpaqueConstant(N1.getOperand(1))) {
3523         // We can only do this xform if we know that bits from X that are set in
3524         // C2 but not in C1 are already zero.  Likewise for Y.
3525         const APInt &LHSMask = N0O1C->getAPIntValue();
3526         const APInt &RHSMask = N1O1C->getAPIntValue();
3527
3528         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3529             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3530           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3531                                   N0.getOperand(0), N1.getOperand(0));
3532           SDLoc DL(LocReference);
3533           return DAG.getNode(ISD::AND, DL, VT, X,
3534                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3535         }
3536       }
3537     }
3538   }
3539
3540   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3541   if (N0.getOpcode() == ISD::AND &&
3542       N1.getOpcode() == ISD::AND &&
3543       N0.getOperand(0) == N1.getOperand(0) &&
3544       // Don't increase # computations.
3545       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3546     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3547                             N0.getOperand(1), N1.getOperand(1));
3548     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3549   }
3550
3551   return SDValue();
3552 }
3553
3554 SDValue DAGCombiner::visitOR(SDNode *N) {
3555   SDValue N0 = N->getOperand(0);
3556   SDValue N1 = N->getOperand(1);
3557   EVT VT = N1.getValueType();
3558
3559   // fold vector ops
3560   if (VT.isVector()) {
3561     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3562       return FoldedVOp;
3563
3564     // fold (or x, 0) -> x, vector edition
3565     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3566       return N1;
3567     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3568       return N0;
3569
3570     // fold (or x, -1) -> -1, vector edition
3571     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3572       // do not return N0, because undef node may exist in N0
3573       return DAG.getConstant(
3574           APInt::getAllOnesValue(
3575               N0.getValueType().getScalarType().getSizeInBits()),
3576           SDLoc(N), N0.getValueType());
3577     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3578       // do not return N1, because undef node may exist in N1
3579       return DAG.getConstant(
3580           APInt::getAllOnesValue(
3581               N1.getValueType().getScalarType().getSizeInBits()),
3582           SDLoc(N), N1.getValueType());
3583
3584     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3585     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3586     // Do this only if the resulting shuffle is legal.
3587     if (isa<ShuffleVectorSDNode>(N0) &&
3588         isa<ShuffleVectorSDNode>(N1) &&
3589         // Avoid folding a node with illegal type.
3590         TLI.isTypeLegal(VT) &&
3591         N0->getOperand(1) == N1->getOperand(1) &&
3592         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3593       bool CanFold = true;
3594       unsigned NumElts = VT.getVectorNumElements();
3595       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3596       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3597       // We construct two shuffle masks:
3598       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3599       // and N1 as the second operand.
3600       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3601       // and N0 as the second operand.
3602       // We do this because OR is commutable and therefore there might be
3603       // two ways to fold this node into a shuffle.
3604       SmallVector<int,4> Mask1;
3605       SmallVector<int,4> Mask2;
3606
3607       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3608         int M0 = SV0->getMaskElt(i);
3609         int M1 = SV1->getMaskElt(i);
3610
3611         // Both shuffle indexes are undef. Propagate Undef.
3612         if (M0 < 0 && M1 < 0) {
3613           Mask1.push_back(M0);
3614           Mask2.push_back(M0);
3615           continue;
3616         }
3617
3618         if (M0 < 0 || M1 < 0 ||
3619             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3620             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3621           CanFold = false;
3622           break;
3623         }
3624
3625         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3626         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3627       }
3628
3629       if (CanFold) {
3630         // Fold this sequence only if the resulting shuffle is 'legal'.
3631         if (TLI.isShuffleMaskLegal(Mask1, VT))
3632           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3633                                       N1->getOperand(0), &Mask1[0]);
3634         if (TLI.isShuffleMaskLegal(Mask2, VT))
3635           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3636                                       N0->getOperand(0), &Mask2[0]);
3637       }
3638     }
3639   }
3640
3641   // fold (or c1, c2) -> c1|c2
3642   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3643   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3644   if (N0C && N1C && !N1C->isOpaque())
3645     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3646   // canonicalize constant to RHS
3647   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3648      !isConstantIntBuildVectorOrConstantInt(N1))
3649     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3650   // fold (or x, 0) -> x
3651   if (isNullConstant(N1))
3652     return N0;
3653   // fold (or x, -1) -> -1
3654   if (isAllOnesConstant(N1))
3655     return N1;
3656   // fold (or x, c) -> c iff (x & ~c) == 0
3657   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3658     return N1;
3659
3660   if (SDValue Combined = visitORLike(N0, N1, N))
3661     return Combined;
3662
3663   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3664   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3665     return BSwap;
3666   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3667     return BSwap;
3668
3669   // reassociate or
3670   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3671     return ROR;
3672   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3673   // iff (c1 & c2) == 0.
3674   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3675              isa<ConstantSDNode>(N0.getOperand(1))) {
3676     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3677     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3678       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3679                                                    N1C, C1))
3680         return DAG.getNode(
3681             ISD::AND, SDLoc(N), VT,
3682             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3683       return SDValue();
3684     }
3685   }
3686   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3687   if (N0.getOpcode() == N1.getOpcode())
3688     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3689       return Tmp;
3690
3691   // See if this is some rotate idiom.
3692   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3693     return SDValue(Rot, 0);
3694
3695   // Simplify the operands using demanded-bits information.
3696   if (!VT.isVector() &&
3697       SimplifyDemandedBits(SDValue(N, 0)))
3698     return SDValue(N, 0);
3699
3700   return SDValue();
3701 }
3702
3703 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3704 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3705   if (Op.getOpcode() == ISD::AND) {
3706     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3707       Mask = Op.getOperand(1);
3708       Op = Op.getOperand(0);
3709     } else {
3710       return false;
3711     }
3712   }
3713
3714   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3715     Shift = Op;
3716     return true;
3717   }
3718
3719   return false;
3720 }
3721
3722 // Return true if we can prove that, whenever Neg and Pos are both in the
3723 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3724 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3725 //
3726 //     (or (shift1 X, Neg), (shift2 X, Pos))
3727 //
3728 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3729 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3730 // to consider shift amounts with defined behavior.
3731 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3732   // If OpSize is a power of 2 then:
3733   //
3734   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3735   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3736   //
3737   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3738   // for the stronger condition:
3739   //
3740   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3741   //
3742   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3743   // we can just replace Neg with Neg' for the rest of the function.
3744   //
3745   // In other cases we check for the even stronger condition:
3746   //
3747   //     Neg == OpSize - Pos                                    [B]
3748   //
3749   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3750   // behavior if Pos == 0 (and consequently Neg == OpSize).
3751   //
3752   // We could actually use [A] whenever OpSize is a power of 2, but the
3753   // only extra cases that it would match are those uninteresting ones
3754   // where Neg and Pos are never in range at the same time.  E.g. for
3755   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3756   // as well as (sub 32, Pos), but:
3757   //
3758   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3759   //
3760   // always invokes undefined behavior for 32-bit X.
3761   //
3762   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3763   unsigned MaskLoBits = 0;
3764   if (Neg.getOpcode() == ISD::AND &&
3765       isPowerOf2_64(OpSize) &&
3766       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3767       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3768     Neg = Neg.getOperand(0);
3769     MaskLoBits = Log2_64(OpSize);
3770   }
3771
3772   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3773   if (Neg.getOpcode() != ISD::SUB)
3774     return 0;
3775   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3776   if (!NegC)
3777     return 0;
3778   SDValue NegOp1 = Neg.getOperand(1);
3779
3780   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3781   // Pos'.  The truncation is redundant for the purpose of the equality.
3782   if (MaskLoBits &&
3783       Pos.getOpcode() == ISD::AND &&
3784       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3785       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3786     Pos = Pos.getOperand(0);
3787
3788   // The condition we need is now:
3789   //
3790   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3791   //
3792   // If NegOp1 == Pos then we need:
3793   //
3794   //              OpSize & Mask == NegC & Mask
3795   //
3796   // (because "x & Mask" is a truncation and distributes through subtraction).
3797   APInt Width;
3798   if (Pos == NegOp1)
3799     Width = NegC->getAPIntValue();
3800   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3801   // Then the condition we want to prove becomes:
3802   //
3803   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3804   //
3805   // which, again because "x & Mask" is a truncation, becomes:
3806   //
3807   //                NegC & Mask == (OpSize - PosC) & Mask
3808   //              OpSize & Mask == (NegC + PosC) & Mask
3809   else if (Pos.getOpcode() == ISD::ADD &&
3810            Pos.getOperand(0) == NegOp1 &&
3811            Pos.getOperand(1).getOpcode() == ISD::Constant)
3812     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3813              NegC->getAPIntValue());
3814   else
3815     return false;
3816
3817   // Now we just need to check that OpSize & Mask == Width & Mask.
3818   if (MaskLoBits)
3819     // Opsize & Mask is 0 since Mask is Opsize - 1.
3820     return Width.getLoBits(MaskLoBits) == 0;
3821   return Width == OpSize;
3822 }
3823
3824 // A subroutine of MatchRotate used once we have found an OR of two opposite
3825 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3826 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3827 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3828 // Neg with outer conversions stripped away.
3829 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3830                                        SDValue Neg, SDValue InnerPos,
3831                                        SDValue InnerNeg, unsigned PosOpcode,
3832                                        unsigned NegOpcode, SDLoc DL) {
3833   // fold (or (shl x, (*ext y)),
3834   //          (srl x, (*ext (sub 32, y)))) ->
3835   //   (rotl x, y) or (rotr x, (sub 32, y))
3836   //
3837   // fold (or (shl x, (*ext (sub 32, y))),
3838   //          (srl x, (*ext y))) ->
3839   //   (rotr x, y) or (rotl x, (sub 32, y))
3840   EVT VT = Shifted.getValueType();
3841   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3842     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3843     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3844                        HasPos ? Pos : Neg).getNode();
3845   }
3846
3847   return nullptr;
3848 }
3849
3850 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3851 // idioms for rotate, and if the target supports rotation instructions, generate
3852 // a rot[lr].
3853 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3854   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3855   EVT VT = LHS.getValueType();
3856   if (!TLI.isTypeLegal(VT)) return nullptr;
3857
3858   // The target must have at least one rotate flavor.
3859   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3860   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3861   if (!HasROTL && !HasROTR) return nullptr;
3862
3863   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3864   SDValue LHSShift;   // The shift.
3865   SDValue LHSMask;    // AND value if any.
3866   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3867     return nullptr; // Not part of a rotate.
3868
3869   SDValue RHSShift;   // The shift.
3870   SDValue RHSMask;    // AND value if any.
3871   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3872     return nullptr; // Not part of a rotate.
3873
3874   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3875     return nullptr;   // Not shifting the same value.
3876
3877   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3878     return nullptr;   // Shifts must disagree.
3879
3880   // Canonicalize shl to left side in a shl/srl pair.
3881   if (RHSShift.getOpcode() == ISD::SHL) {
3882     std::swap(LHS, RHS);
3883     std::swap(LHSShift, RHSShift);
3884     std::swap(LHSMask , RHSMask );
3885   }
3886
3887   unsigned OpSizeInBits = VT.getSizeInBits();
3888   SDValue LHSShiftArg = LHSShift.getOperand(0);
3889   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3890   SDValue RHSShiftArg = RHSShift.getOperand(0);
3891   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3892
3893   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3894   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3895   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3896       RHSShiftAmt.getOpcode() == ISD::Constant) {
3897     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3898     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3899     if ((LShVal + RShVal) != OpSizeInBits)
3900       return nullptr;
3901
3902     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3903                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3904
3905     // If there is an AND of either shifted operand, apply it to the result.
3906     if (LHSMask.getNode() || RHSMask.getNode()) {
3907       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3908
3909       if (LHSMask.getNode()) {
3910         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3911         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3912       }
3913       if (RHSMask.getNode()) {
3914         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3915         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3916       }
3917
3918       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3919     }
3920
3921     return Rot.getNode();
3922   }
3923
3924   // If there is a mask here, and we have a variable shift, we can't be sure
3925   // that we're masking out the right stuff.
3926   if (LHSMask.getNode() || RHSMask.getNode())
3927     return nullptr;
3928
3929   // If the shift amount is sign/zext/any-extended just peel it off.
3930   SDValue LExtOp0 = LHSShiftAmt;
3931   SDValue RExtOp0 = RHSShiftAmt;
3932   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3933        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3934        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3935        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3936       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3937        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3938        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3939        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3940     LExtOp0 = LHSShiftAmt.getOperand(0);
3941     RExtOp0 = RHSShiftAmt.getOperand(0);
3942   }
3943
3944   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3945                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3946   if (TryL)
3947     return TryL;
3948
3949   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3950                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3951   if (TryR)
3952     return TryR;
3953
3954   return nullptr;
3955 }
3956
3957 SDValue DAGCombiner::visitXOR(SDNode *N) {
3958   SDValue N0 = N->getOperand(0);
3959   SDValue N1 = N->getOperand(1);
3960   EVT VT = N0.getValueType();
3961
3962   // fold vector ops
3963   if (VT.isVector()) {
3964     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3965       return FoldedVOp;
3966
3967     // fold (xor x, 0) -> x, vector edition
3968     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3969       return N1;
3970     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3971       return N0;
3972   }
3973
3974   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3975   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3976     return DAG.getConstant(0, SDLoc(N), VT);
3977   // fold (xor x, undef) -> undef
3978   if (N0.getOpcode() == ISD::UNDEF)
3979     return N0;
3980   if (N1.getOpcode() == ISD::UNDEF)
3981     return N1;
3982   // fold (xor c1, c2) -> c1^c2
3983   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3984   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3985   if (N0C && N1C)
3986     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3987   // canonicalize constant to RHS
3988   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3989      !isConstantIntBuildVectorOrConstantInt(N1))
3990     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3991   // fold (xor x, 0) -> x
3992   if (isNullConstant(N1))
3993     return N0;
3994   // reassociate xor
3995   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3996     return RXOR;
3997
3998   // fold !(x cc y) -> (x !cc y)
3999   SDValue LHS, RHS, CC;
4000   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4001     bool isInt = LHS.getValueType().isInteger();
4002     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4003                                                isInt);
4004
4005     if (!LegalOperations ||
4006         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4007       switch (N0.getOpcode()) {
4008       default:
4009         llvm_unreachable("Unhandled SetCC Equivalent!");
4010       case ISD::SETCC:
4011         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4012       case ISD::SELECT_CC:
4013         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4014                                N0.getOperand(3), NotCC);
4015       }
4016     }
4017   }
4018
4019   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4020   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4021       N0.getNode()->hasOneUse() &&
4022       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4023     SDValue V = N0.getOperand(0);
4024     SDLoc DL(N0);
4025     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4026                     DAG.getConstant(1, DL, V.getValueType()));
4027     AddToWorklist(V.getNode());
4028     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4029   }
4030
4031   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4032   if (isOneConstant(N1) && VT == MVT::i1 &&
4033       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4034     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4035     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4036       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4037       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4038       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4039       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4040       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4041     }
4042   }
4043   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4044   if (isAllOnesConstant(N1) &&
4045       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4046     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4047     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4048       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4049       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4050       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4051       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4052       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4053     }
4054   }
4055   // fold (xor (and x, y), y) -> (and (not x), y)
4056   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4057       N0->getOperand(1) == N1) {
4058     SDValue X = N0->getOperand(0);
4059     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4060     AddToWorklist(NotX.getNode());
4061     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4062   }
4063   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4064   if (N1C && N0.getOpcode() == ISD::XOR) {
4065     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4066       SDLoc DL(N);
4067       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4068                          DAG.getConstant(N1C->getAPIntValue() ^
4069                                          N00C->getAPIntValue(), DL, VT));
4070     }
4071     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4072       SDLoc DL(N);
4073       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4074                          DAG.getConstant(N1C->getAPIntValue() ^
4075                                          N01C->getAPIntValue(), DL, VT));
4076     }
4077   }
4078   // fold (xor x, x) -> 0
4079   if (N0 == N1)
4080     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4081
4082   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4083   // Here is a concrete example of this equivalence:
4084   // i16   x ==  14
4085   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4086   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4087   //
4088   // =>
4089   //
4090   // i16     ~1      == 0b1111111111111110
4091   // i16 rol(~1, 14) == 0b1011111111111111
4092   //
4093   // Some additional tips to help conceptualize this transform:
4094   // - Try to see the operation as placing a single zero in a value of all ones.
4095   // - There exists no value for x which would allow the result to contain zero.
4096   // - Values of x larger than the bitwidth are undefined and do not require a
4097   //   consistent result.
4098   // - Pushing the zero left requires shifting one bits in from the right.
4099   // A rotate left of ~1 is a nice way of achieving the desired result.
4100   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4101       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4102     SDLoc DL(N);
4103     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4104                        N0.getOperand(1));
4105   }
4106
4107   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4108   if (N0.getOpcode() == N1.getOpcode())
4109     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4110       return Tmp;
4111
4112   // Simplify the expression using non-local knowledge.
4113   if (!VT.isVector() &&
4114       SimplifyDemandedBits(SDValue(N, 0)))
4115     return SDValue(N, 0);
4116
4117   return SDValue();
4118 }
4119
4120 /// Handle transforms common to the three shifts, when the shift amount is a
4121 /// constant.
4122 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4123   SDNode *LHS = N->getOperand(0).getNode();
4124   if (!LHS->hasOneUse()) return SDValue();
4125
4126   // We want to pull some binops through shifts, so that we have (and (shift))
4127   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4128   // thing happens with address calculations, so it's important to canonicalize
4129   // it.
4130   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4131
4132   switch (LHS->getOpcode()) {
4133   default: return SDValue();
4134   case ISD::OR:
4135   case ISD::XOR:
4136     HighBitSet = false; // We can only transform sra if the high bit is clear.
4137     break;
4138   case ISD::AND:
4139     HighBitSet = true;  // We can only transform sra if the high bit is set.
4140     break;
4141   case ISD::ADD:
4142     if (N->getOpcode() != ISD::SHL)
4143       return SDValue(); // only shl(add) not sr[al](add).
4144     HighBitSet = false; // We can only transform sra if the high bit is clear.
4145     break;
4146   }
4147
4148   // We require the RHS of the binop to be a constant and not opaque as well.
4149   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4150   if (!BinOpCst) return SDValue();
4151
4152   // FIXME: disable this unless the input to the binop is a shift by a constant.
4153   // If it is not a shift, it pessimizes some common cases like:
4154   //
4155   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4156   //    int bar(int *X, int i) { return X[i & 255]; }
4157   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4158   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4159        BinOpLHSVal->getOpcode() != ISD::SRA &&
4160        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4161       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4162     return SDValue();
4163
4164   EVT VT = N->getValueType(0);
4165
4166   // If this is a signed shift right, and the high bit is modified by the
4167   // logical operation, do not perform the transformation. The highBitSet
4168   // boolean indicates the value of the high bit of the constant which would
4169   // cause it to be modified for this operation.
4170   if (N->getOpcode() == ISD::SRA) {
4171     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4172     if (BinOpRHSSignSet != HighBitSet)
4173       return SDValue();
4174   }
4175
4176   if (!TLI.isDesirableToCommuteWithShift(LHS))
4177     return SDValue();
4178
4179   // Fold the constants, shifting the binop RHS by the shift amount.
4180   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4181                                N->getValueType(0),
4182                                LHS->getOperand(1), N->getOperand(1));
4183   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4184
4185   // Create the new shift.
4186   SDValue NewShift = DAG.getNode(N->getOpcode(),
4187                                  SDLoc(LHS->getOperand(0)),
4188                                  VT, LHS->getOperand(0), N->getOperand(1));
4189
4190   // Create the new binop.
4191   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4192 }
4193
4194 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4195   assert(N->getOpcode() == ISD::TRUNCATE);
4196   assert(N->getOperand(0).getOpcode() == ISD::AND);
4197
4198   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4199   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4200     SDValue N01 = N->getOperand(0).getOperand(1);
4201
4202     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4203       if (!N01C->isOpaque()) {
4204         EVT TruncVT = N->getValueType(0);
4205         SDValue N00 = N->getOperand(0).getOperand(0);
4206         APInt TruncC = N01C->getAPIntValue();
4207         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4208         SDLoc DL(N);
4209
4210         return DAG.getNode(ISD::AND, DL, TruncVT,
4211                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4212                            DAG.getConstant(TruncC, DL, TruncVT));
4213       }
4214     }
4215   }
4216
4217   return SDValue();
4218 }
4219
4220 SDValue DAGCombiner::visitRotate(SDNode *N) {
4221   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4222   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4223       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4224     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4225     if (NewOp1.getNode())
4226       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4227                          N->getOperand(0), NewOp1);
4228   }
4229   return SDValue();
4230 }
4231
4232 SDValue DAGCombiner::visitSHL(SDNode *N) {
4233   SDValue N0 = N->getOperand(0);
4234   SDValue N1 = N->getOperand(1);
4235   EVT VT = N0.getValueType();
4236   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4237
4238   // fold vector ops
4239   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4240   if (VT.isVector()) {
4241     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4242       return FoldedVOp;
4243
4244     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4245     // If setcc produces all-one true value then:
4246     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4247     if (N1CV && N1CV->isConstant()) {
4248       if (N0.getOpcode() == ISD::AND) {
4249         SDValue N00 = N0->getOperand(0);
4250         SDValue N01 = N0->getOperand(1);
4251         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4252
4253         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4254             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4255                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4256           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4257                                                      N01CV, N1CV))
4258             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4259         }
4260       } else {
4261         N1C = isConstOrConstSplat(N1);
4262       }
4263     }
4264   }
4265
4266   // fold (shl c1, c2) -> c1<<c2
4267   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4268   if (N0C && N1C && !N1C->isOpaque())
4269     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4270   // fold (shl 0, x) -> 0
4271   if (isNullConstant(N0))
4272     return N0;
4273   // fold (shl x, c >= size(x)) -> undef
4274   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4275     return DAG.getUNDEF(VT);
4276   // fold (shl x, 0) -> x
4277   if (N1C && N1C->isNullValue())
4278     return N0;
4279   // fold (shl undef, x) -> 0
4280   if (N0.getOpcode() == ISD::UNDEF)
4281     return DAG.getConstant(0, SDLoc(N), VT);
4282   // if (shl x, c) is known to be zero, return 0
4283   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4284                             APInt::getAllOnesValue(OpSizeInBits)))
4285     return DAG.getConstant(0, SDLoc(N), VT);
4286   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4287   if (N1.getOpcode() == ISD::TRUNCATE &&
4288       N1.getOperand(0).getOpcode() == ISD::AND) {
4289     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4290     if (NewOp1.getNode())
4291       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4292   }
4293
4294   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4295     return SDValue(N, 0);
4296
4297   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4298   if (N1C && N0.getOpcode() == ISD::SHL) {
4299     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4300       uint64_t c1 = N0C1->getZExtValue();
4301       uint64_t c2 = N1C->getZExtValue();
4302       SDLoc DL(N);
4303       if (c1 + c2 >= OpSizeInBits)
4304         return DAG.getConstant(0, DL, VT);
4305       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4306                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4307     }
4308   }
4309
4310   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4311   // For this to be valid, the second form must not preserve any of the bits
4312   // that are shifted out by the inner shift in the first form.  This means
4313   // the outer shift size must be >= the number of bits added by the ext.
4314   // As a corollary, we don't care what kind of ext it is.
4315   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4316               N0.getOpcode() == ISD::ANY_EXTEND ||
4317               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4318       N0.getOperand(0).getOpcode() == ISD::SHL) {
4319     SDValue N0Op0 = N0.getOperand(0);
4320     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4321       uint64_t c1 = N0Op0C1->getZExtValue();
4322       uint64_t c2 = N1C->getZExtValue();
4323       EVT InnerShiftVT = N0Op0.getValueType();
4324       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4325       if (c2 >= OpSizeInBits - InnerShiftSize) {
4326         SDLoc DL(N0);
4327         if (c1 + c2 >= OpSizeInBits)
4328           return DAG.getConstant(0, DL, VT);
4329         return DAG.getNode(ISD::SHL, DL, VT,
4330                            DAG.getNode(N0.getOpcode(), DL, VT,
4331                                        N0Op0->getOperand(0)),
4332                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4333       }
4334     }
4335   }
4336
4337   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4338   // Only fold this if the inner zext has no other uses to avoid increasing
4339   // the total number of instructions.
4340   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4341       N0.getOperand(0).getOpcode() == ISD::SRL) {
4342     SDValue N0Op0 = N0.getOperand(0);
4343     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4344       uint64_t c1 = N0Op0C1->getZExtValue();
4345       if (c1 < VT.getScalarSizeInBits()) {
4346         uint64_t c2 = N1C->getZExtValue();
4347         if (c1 == c2) {
4348           SDValue NewOp0 = N0.getOperand(0);
4349           EVT CountVT = NewOp0.getOperand(1).getValueType();
4350           SDLoc DL(N);
4351           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4352                                        NewOp0,
4353                                        DAG.getConstant(c2, DL, CountVT));
4354           AddToWorklist(NewSHL.getNode());
4355           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4356         }
4357       }
4358     }
4359   }
4360
4361   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4362   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4363   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4364       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4365     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4366       uint64_t C1 = N0C1->getZExtValue();
4367       uint64_t C2 = N1C->getZExtValue();
4368       SDLoc DL(N);
4369       if (C1 <= C2)
4370         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4371                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4372       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4373                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4374     }
4375   }
4376
4377   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4378   //                               (and (srl x, (sub c1, c2), MASK)
4379   // Only fold this if the inner shift has no other uses -- if it does, folding
4380   // this will increase the total number of instructions.
4381   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4382     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4383       uint64_t c1 = N0C1->getZExtValue();
4384       if (c1 < OpSizeInBits) {
4385         uint64_t c2 = N1C->getZExtValue();
4386         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4387         SDValue Shift;
4388         if (c2 > c1) {
4389           Mask = Mask.shl(c2 - c1);
4390           SDLoc DL(N);
4391           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4392                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4393         } else {
4394           Mask = Mask.lshr(c1 - c2);
4395           SDLoc DL(N);
4396           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4397                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4398         }
4399         SDLoc DL(N0);
4400         return DAG.getNode(ISD::AND, DL, VT, Shift,
4401                            DAG.getConstant(Mask, DL, VT));
4402       }
4403     }
4404   }
4405   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4406   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4407     unsigned BitSize = VT.getScalarSizeInBits();
4408     SDLoc DL(N);
4409     SDValue HiBitsMask =
4410       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4411                                             BitSize - N1C->getZExtValue()),
4412                       DL, VT);
4413     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4414                        HiBitsMask);
4415   }
4416
4417   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4418   // Variant of version done on multiply, except mul by a power of 2 is turned
4419   // into a shift.
4420   APInt Val;
4421   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4422       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4423        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4424     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4425     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4426     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4427   }
4428
4429   if (N1C && !N1C->isOpaque())
4430     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4431       return NewSHL;
4432
4433   return SDValue();
4434 }
4435
4436 SDValue DAGCombiner::visitSRA(SDNode *N) {
4437   SDValue N0 = N->getOperand(0);
4438   SDValue N1 = N->getOperand(1);
4439   EVT VT = N0.getValueType();
4440   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4441
4442   // fold vector ops
4443   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4444   if (VT.isVector()) {
4445     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4446       return FoldedVOp;
4447
4448     N1C = isConstOrConstSplat(N1);
4449   }
4450
4451   // fold (sra c1, c2) -> (sra c1, c2)
4452   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4453   if (N0C && N1C && !N1C->isOpaque())
4454     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4455   // fold (sra 0, x) -> 0
4456   if (isNullConstant(N0))
4457     return N0;
4458   // fold (sra -1, x) -> -1
4459   if (isAllOnesConstant(N0))
4460     return N0;
4461   // fold (sra x, (setge c, size(x))) -> undef
4462   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4463     return DAG.getUNDEF(VT);
4464   // fold (sra x, 0) -> x
4465   if (N1C && N1C->isNullValue())
4466     return N0;
4467   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4468   // sext_inreg.
4469   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4470     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4471     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4472     if (VT.isVector())
4473       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4474                                ExtVT, VT.getVectorNumElements());
4475     if ((!LegalOperations ||
4476          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4477       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4478                          N0.getOperand(0), DAG.getValueType(ExtVT));
4479   }
4480
4481   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4482   if (N1C && N0.getOpcode() == ISD::SRA) {
4483     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4484       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4485       if (Sum >= OpSizeInBits)
4486         Sum = OpSizeInBits - 1;
4487       SDLoc DL(N);
4488       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4489                          DAG.getConstant(Sum, DL, N1.getValueType()));
4490     }
4491   }
4492
4493   // fold (sra (shl X, m), (sub result_size, n))
4494   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4495   // result_size - n != m.
4496   // If truncate is free for the target sext(shl) is likely to result in better
4497   // code.
4498   if (N0.getOpcode() == ISD::SHL && N1C) {
4499     // Get the two constanst of the shifts, CN0 = m, CN = n.
4500     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4501     if (N01C) {
4502       LLVMContext &Ctx = *DAG.getContext();
4503       // Determine what the truncate's result bitsize and type would be.
4504       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4505
4506       if (VT.isVector())
4507         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4508
4509       // Determine the residual right-shift amount.
4510       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4511
4512       // If the shift is not a no-op (in which case this should be just a sign
4513       // extend already), the truncated to type is legal, sign_extend is legal
4514       // on that type, and the truncate to that type is both legal and free,
4515       // perform the transform.
4516       if ((ShiftAmt > 0) &&
4517           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4518           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4519           TLI.isTruncateFree(VT, TruncVT)) {
4520
4521         SDLoc DL(N);
4522         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4523             getShiftAmountTy(N0.getOperand(0).getValueType()));
4524         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4525                                     N0.getOperand(0), Amt);
4526         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4527                                     Shift);
4528         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4529                            N->getValueType(0), Trunc);
4530       }
4531     }
4532   }
4533
4534   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4535   if (N1.getOpcode() == ISD::TRUNCATE &&
4536       N1.getOperand(0).getOpcode() == ISD::AND) {
4537     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4538     if (NewOp1.getNode())
4539       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4540   }
4541
4542   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4543   //      if c1 is equal to the number of bits the trunc removes
4544   if (N0.getOpcode() == ISD::TRUNCATE &&
4545       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4546        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4547       N0.getOperand(0).hasOneUse() &&
4548       N0.getOperand(0).getOperand(1).hasOneUse() &&
4549       N1C) {
4550     SDValue N0Op0 = N0.getOperand(0);
4551     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4552       unsigned LargeShiftVal = LargeShift->getZExtValue();
4553       EVT LargeVT = N0Op0.getValueType();
4554
4555       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4556         SDLoc DL(N);
4557         SDValue Amt =
4558           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4559                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4560         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4561                                   N0Op0.getOperand(0), Amt);
4562         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4563       }
4564     }
4565   }
4566
4567   // Simplify, based on bits shifted out of the LHS.
4568   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4569     return SDValue(N, 0);
4570
4571
4572   // If the sign bit is known to be zero, switch this to a SRL.
4573   if (DAG.SignBitIsZero(N0))
4574     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4575
4576   if (N1C && !N1C->isOpaque())
4577     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4578       return NewSRA;
4579
4580   return SDValue();
4581 }
4582
4583 SDValue DAGCombiner::visitSRL(SDNode *N) {
4584   SDValue N0 = N->getOperand(0);
4585   SDValue N1 = N->getOperand(1);
4586   EVT VT = N0.getValueType();
4587   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4588
4589   // fold vector ops
4590   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4591   if (VT.isVector()) {
4592     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4593       return FoldedVOp;
4594
4595     N1C = isConstOrConstSplat(N1);
4596   }
4597
4598   // fold (srl c1, c2) -> c1 >>u c2
4599   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4600   if (N0C && N1C && !N1C->isOpaque())
4601     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4602   // fold (srl 0, x) -> 0
4603   if (isNullConstant(N0))
4604     return N0;
4605   // fold (srl x, c >= size(x)) -> undef
4606   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4607     return DAG.getUNDEF(VT);
4608   // fold (srl x, 0) -> x
4609   if (N1C && N1C->isNullValue())
4610     return N0;
4611   // if (srl x, c) is known to be zero, return 0
4612   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4613                                    APInt::getAllOnesValue(OpSizeInBits)))
4614     return DAG.getConstant(0, SDLoc(N), VT);
4615
4616   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4617   if (N1C && N0.getOpcode() == ISD::SRL) {
4618     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4619       uint64_t c1 = N01C->getZExtValue();
4620       uint64_t c2 = N1C->getZExtValue();
4621       SDLoc DL(N);
4622       if (c1 + c2 >= OpSizeInBits)
4623         return DAG.getConstant(0, DL, VT);
4624       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4625                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4626     }
4627   }
4628
4629   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4630   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4631       N0.getOperand(0).getOpcode() == ISD::SRL &&
4632       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4633     uint64_t c1 =
4634       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4635     uint64_t c2 = N1C->getZExtValue();
4636     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4637     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4638     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4639     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4640     if (c1 + OpSizeInBits == InnerShiftSize) {
4641       SDLoc DL(N0);
4642       if (c1 + c2 >= InnerShiftSize)
4643         return DAG.getConstant(0, DL, VT);
4644       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4645                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4646                                      N0.getOperand(0)->getOperand(0),
4647                                      DAG.getConstant(c1 + c2, DL,
4648                                                      ShiftCountVT)));
4649     }
4650   }
4651
4652   // fold (srl (shl x, c), c) -> (and x, cst2)
4653   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4654     unsigned BitSize = N0.getScalarValueSizeInBits();
4655     if (BitSize <= 64) {
4656       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4657       SDLoc DL(N);
4658       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4659                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4660     }
4661   }
4662
4663   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4664   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4665     // Shifting in all undef bits?
4666     EVT SmallVT = N0.getOperand(0).getValueType();
4667     unsigned BitSize = SmallVT.getScalarSizeInBits();
4668     if (N1C->getZExtValue() >= BitSize)
4669       return DAG.getUNDEF(VT);
4670
4671     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4672       uint64_t ShiftAmt = N1C->getZExtValue();
4673       SDLoc DL0(N0);
4674       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4675                                        N0.getOperand(0),
4676                           DAG.getConstant(ShiftAmt, DL0,
4677                                           getShiftAmountTy(SmallVT)));
4678       AddToWorklist(SmallShift.getNode());
4679       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4680       SDLoc DL(N);
4681       return DAG.getNode(ISD::AND, DL, VT,
4682                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4683                          DAG.getConstant(Mask, DL, VT));
4684     }
4685   }
4686
4687   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4688   // bit, which is unmodified by sra.
4689   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4690     if (N0.getOpcode() == ISD::SRA)
4691       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4692   }
4693
4694   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4695   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4696       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4697     APInt KnownZero, KnownOne;
4698     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4699
4700     // If any of the input bits are KnownOne, then the input couldn't be all
4701     // zeros, thus the result of the srl will always be zero.
4702     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4703
4704     // If all of the bits input the to ctlz node are known to be zero, then
4705     // the result of the ctlz is "32" and the result of the shift is one.
4706     APInt UnknownBits = ~KnownZero;
4707     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4708
4709     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4710     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4711       // Okay, we know that only that the single bit specified by UnknownBits
4712       // could be set on input to the CTLZ node. If this bit is set, the SRL
4713       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4714       // to an SRL/XOR pair, which is likely to simplify more.
4715       unsigned ShAmt = UnknownBits.countTrailingZeros();
4716       SDValue Op = N0.getOperand(0);
4717
4718       if (ShAmt) {
4719         SDLoc DL(N0);
4720         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4721                   DAG.getConstant(ShAmt, DL,
4722                                   getShiftAmountTy(Op.getValueType())));
4723         AddToWorklist(Op.getNode());
4724       }
4725
4726       SDLoc DL(N);
4727       return DAG.getNode(ISD::XOR, DL, VT,
4728                          Op, DAG.getConstant(1, DL, VT));
4729     }
4730   }
4731
4732   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4733   if (N1.getOpcode() == ISD::TRUNCATE &&
4734       N1.getOperand(0).getOpcode() == ISD::AND) {
4735     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4736     if (NewOp1.getNode())
4737       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4738   }
4739
4740   // fold operands of srl based on knowledge that the low bits are not
4741   // demanded.
4742   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4743     return SDValue(N, 0);
4744
4745   if (N1C && !N1C->isOpaque()) {
4746     SDValue NewSRL = visitShiftByConstant(N, N1C);
4747     if (NewSRL.getNode())
4748       return NewSRL;
4749   }
4750
4751   // Attempt to convert a srl of a load into a narrower zero-extending load.
4752   SDValue NarrowLoad = ReduceLoadWidth(N);
4753   if (NarrowLoad.getNode())
4754     return NarrowLoad;
4755
4756   // Here is a common situation. We want to optimize:
4757   //
4758   //   %a = ...
4759   //   %b = and i32 %a, 2
4760   //   %c = srl i32 %b, 1
4761   //   brcond i32 %c ...
4762   //
4763   // into
4764   //
4765   //   %a = ...
4766   //   %b = and %a, 2
4767   //   %c = setcc eq %b, 0
4768   //   brcond %c ...
4769   //
4770   // However when after the source operand of SRL is optimized into AND, the SRL
4771   // itself may not be optimized further. Look for it and add the BRCOND into
4772   // the worklist.
4773   if (N->hasOneUse()) {
4774     SDNode *Use = *N->use_begin();
4775     if (Use->getOpcode() == ISD::BRCOND)
4776       AddToWorklist(Use);
4777     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4778       // Also look pass the truncate.
4779       Use = *Use->use_begin();
4780       if (Use->getOpcode() == ISD::BRCOND)
4781         AddToWorklist(Use);
4782     }
4783   }
4784
4785   return SDValue();
4786 }
4787
4788 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4789   SDValue N0 = N->getOperand(0);
4790   EVT VT = N->getValueType(0);
4791
4792   // fold (bswap c1) -> c2
4793   if (isConstantIntBuildVectorOrConstantInt(N0))
4794     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4795   // fold (bswap (bswap x)) -> x
4796   if (N0.getOpcode() == ISD::BSWAP)
4797     return N0->getOperand(0);
4798   return SDValue();
4799 }
4800
4801 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4802   SDValue N0 = N->getOperand(0);
4803   EVT VT = N->getValueType(0);
4804
4805   // fold (ctlz c1) -> c2
4806   if (isConstantIntBuildVectorOrConstantInt(N0))
4807     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4808   return SDValue();
4809 }
4810
4811 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4812   SDValue N0 = N->getOperand(0);
4813   EVT VT = N->getValueType(0);
4814
4815   // fold (ctlz_zero_undef c1) -> c2
4816   if (isConstantIntBuildVectorOrConstantInt(N0))
4817     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4818   return SDValue();
4819 }
4820
4821 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4822   SDValue N0 = N->getOperand(0);
4823   EVT VT = N->getValueType(0);
4824
4825   // fold (cttz c1) -> c2
4826   if (isConstantIntBuildVectorOrConstantInt(N0))
4827     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4828   return SDValue();
4829 }
4830
4831 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4832   SDValue N0 = N->getOperand(0);
4833   EVT VT = N->getValueType(0);
4834
4835   // fold (cttz_zero_undef c1) -> c2
4836   if (isConstantIntBuildVectorOrConstantInt(N0))
4837     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4838   return SDValue();
4839 }
4840
4841 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4842   SDValue N0 = N->getOperand(0);
4843   EVT VT = N->getValueType(0);
4844
4845   // fold (ctpop c1) -> c2
4846   if (isConstantIntBuildVectorOrConstantInt(N0))
4847     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4848   return SDValue();
4849 }
4850
4851
4852 /// \brief Generate Min/Max node
4853 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4854                                    SDValue True, SDValue False,
4855                                    ISD::CondCode CC, const TargetLowering &TLI,
4856                                    SelectionDAG &DAG) {
4857   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4858     return SDValue();
4859
4860   switch (CC) {
4861   case ISD::SETOLT:
4862   case ISD::SETOLE:
4863   case ISD::SETLT:
4864   case ISD::SETLE:
4865   case ISD::SETULT:
4866   case ISD::SETULE: {
4867     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4868     if (TLI.isOperationLegal(Opcode, VT))
4869       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4870     return SDValue();
4871   }
4872   case ISD::SETOGT:
4873   case ISD::SETOGE:
4874   case ISD::SETGT:
4875   case ISD::SETGE:
4876   case ISD::SETUGT:
4877   case ISD::SETUGE: {
4878     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4879     if (TLI.isOperationLegal(Opcode, VT))
4880       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4881     return SDValue();
4882   }
4883   default:
4884     return SDValue();
4885   }
4886 }
4887
4888 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4889   SDValue N0 = N->getOperand(0);
4890   SDValue N1 = N->getOperand(1);
4891   SDValue N2 = N->getOperand(2);
4892   EVT VT = N->getValueType(0);
4893   EVT VT0 = N0.getValueType();
4894
4895   // fold (select C, X, X) -> X
4896   if (N1 == N2)
4897     return N1;
4898   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4899     // fold (select true, X, Y) -> X
4900     // fold (select false, X, Y) -> Y
4901     return !N0C->isNullValue() ? N1 : N2;
4902   }
4903   // fold (select C, 1, X) -> (or C, X)
4904   if (VT == MVT::i1 && isOneConstant(N1))
4905     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4906   // fold (select C, 0, 1) -> (xor C, 1)
4907   // We can't do this reliably if integer based booleans have different contents
4908   // to floating point based booleans. This is because we can't tell whether we
4909   // have an integer-based boolean or a floating-point-based boolean unless we
4910   // can find the SETCC that produced it and inspect its operands. This is
4911   // fairly easy if C is the SETCC node, but it can potentially be
4912   // undiscoverable (or not reasonably discoverable). For example, it could be
4913   // in another basic block or it could require searching a complicated
4914   // expression.
4915   if (VT.isInteger() &&
4916       (VT0 == MVT::i1 || (VT0.isInteger() &&
4917                           TLI.getBooleanContents(false, false) ==
4918                               TLI.getBooleanContents(false, true) &&
4919                           TLI.getBooleanContents(false, false) ==
4920                               TargetLowering::ZeroOrOneBooleanContent)) &&
4921       isNullConstant(N1) && isOneConstant(N2)) {
4922     SDValue XORNode;
4923     if (VT == VT0) {
4924       SDLoc DL(N);
4925       return DAG.getNode(ISD::XOR, DL, VT0,
4926                          N0, DAG.getConstant(1, DL, VT0));
4927     }
4928     SDLoc DL0(N0);
4929     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4930                           N0, DAG.getConstant(1, DL0, VT0));
4931     AddToWorklist(XORNode.getNode());
4932     if (VT.bitsGT(VT0))
4933       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4934     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4935   }
4936   // fold (select C, 0, X) -> (and (not C), X)
4937   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4938     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4939     AddToWorklist(NOTNode.getNode());
4940     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4941   }
4942   // fold (select C, X, 1) -> (or (not C), X)
4943   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4944     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4945     AddToWorklist(NOTNode.getNode());
4946     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4947   }
4948   // fold (select C, X, 0) -> (and C, X)
4949   if (VT == MVT::i1 && isNullConstant(N2))
4950     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4951   // fold (select X, X, Y) -> (or X, Y)
4952   // fold (select X, 1, Y) -> (or X, Y)
4953   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4954     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4955   // fold (select X, Y, X) -> (and X, Y)
4956   // fold (select X, Y, 0) -> (and X, Y)
4957   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4958     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4959
4960   // If we can fold this based on the true/false value, do so.
4961   if (SimplifySelectOps(N, N1, N2))
4962     return SDValue(N, 0);  // Don't revisit N.
4963
4964   // fold selects based on a setcc into other things, such as min/max/abs
4965   if (N0.getOpcode() == ISD::SETCC) {
4966     // select x, y (fcmp lt x, y) -> fminnum x, y
4967     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4968     //
4969     // This is OK if we don't care about what happens if either operand is a
4970     // NaN.
4971     //
4972
4973     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4974     // no signed zeros as well as no nans.
4975     const TargetOptions &Options = DAG.getTarget().Options;
4976     if (Options.UnsafeFPMath &&
4977         VT.isFloatingPoint() && N0.hasOneUse() &&
4978         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4979       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4980
4981       SDValue FMinMax =
4982           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4983                               N1, N2, CC, TLI, DAG);
4984       if (FMinMax)
4985         return FMinMax;
4986     }
4987
4988     if ((!LegalOperations &&
4989          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4990         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4991       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4992                          N0.getOperand(0), N0.getOperand(1),
4993                          N1, N2, N0.getOperand(2));
4994     return SimplifySelect(SDLoc(N), N0, N1, N2);
4995   }
4996
4997   if (VT0 == MVT::i1) {
4998     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4999       // select (and Cond0, Cond1), X, Y
5000       //   -> select Cond0, (select Cond1, X, Y), Y
5001       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5002         SDValue Cond0 = N0->getOperand(0);
5003         SDValue Cond1 = N0->getOperand(1);
5004         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5005                                           N1.getValueType(), Cond1, N1, N2);
5006         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5007                            InnerSelect, N2);
5008       }
5009       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5010       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5011         SDValue Cond0 = N0->getOperand(0);
5012         SDValue Cond1 = N0->getOperand(1);
5013         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5014                                           N1.getValueType(), Cond1, N1, N2);
5015         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5016                            InnerSelect);
5017       }
5018     }
5019
5020     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5021     if (N1->getOpcode() == ISD::SELECT) {
5022       SDValue N1_0 = N1->getOperand(0);
5023       SDValue N1_1 = N1->getOperand(1);
5024       SDValue N1_2 = N1->getOperand(2);
5025       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5026         // Create the actual and node if we can generate good code for it.
5027         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5028           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5029                                     N0, N1_0);
5030           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5031                              N1_1, N2);
5032         }
5033         // Otherwise see if we can optimize the "and" to a better pattern.
5034         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5035           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5036                              N1_1, N2);
5037       }
5038     }
5039     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5040     if (N2->getOpcode() == ISD::SELECT) {
5041       SDValue N2_0 = N2->getOperand(0);
5042       SDValue N2_1 = N2->getOperand(1);
5043       SDValue N2_2 = N2->getOperand(2);
5044       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5045         // Create the actual or node if we can generate good code for it.
5046         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5047           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5048                                    N0, N2_0);
5049           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5050                              N1, N2_2);
5051         }
5052         // Otherwise see if we can optimize to a better pattern.
5053         if (SDValue Combined = visitORLike(N0, N2_0, N))
5054           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5055                              N1, N2_2);
5056       }
5057     }
5058   }
5059
5060   return SDValue();
5061 }
5062
5063 static
5064 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5065   SDLoc DL(N);
5066   EVT LoVT, HiVT;
5067   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5068
5069   // Split the inputs.
5070   SDValue Lo, Hi, LL, LH, RL, RH;
5071   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5072   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5073
5074   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5075   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5076
5077   return std::make_pair(Lo, Hi);
5078 }
5079
5080 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5081 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5082 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5083   SDLoc dl(N);
5084   SDValue Cond = N->getOperand(0);
5085   SDValue LHS = N->getOperand(1);
5086   SDValue RHS = N->getOperand(2);
5087   EVT VT = N->getValueType(0);
5088   int NumElems = VT.getVectorNumElements();
5089   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5090          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5091          Cond.getOpcode() == ISD::BUILD_VECTOR);
5092
5093   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5094   // binary ones here.
5095   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5096     return SDValue();
5097
5098   // We're sure we have an even number of elements due to the
5099   // concat_vectors we have as arguments to vselect.
5100   // Skip BV elements until we find one that's not an UNDEF
5101   // After we find an UNDEF element, keep looping until we get to half the
5102   // length of the BV and see if all the non-undef nodes are the same.
5103   ConstantSDNode *BottomHalf = nullptr;
5104   for (int i = 0; i < NumElems / 2; ++i) {
5105     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5106       continue;
5107
5108     if (BottomHalf == nullptr)
5109       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5110     else if (Cond->getOperand(i).getNode() != BottomHalf)
5111       return SDValue();
5112   }
5113
5114   // Do the same for the second half of the BuildVector
5115   ConstantSDNode *TopHalf = nullptr;
5116   for (int i = NumElems / 2; i < NumElems; ++i) {
5117     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5118       continue;
5119
5120     if (TopHalf == nullptr)
5121       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5122     else if (Cond->getOperand(i).getNode() != TopHalf)
5123       return SDValue();
5124   }
5125
5126   assert(TopHalf && BottomHalf &&
5127          "One half of the selector was all UNDEFs and the other was all the "
5128          "same value. This should have been addressed before this function.");
5129   return DAG.getNode(
5130       ISD::CONCAT_VECTORS, dl, VT,
5131       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5132       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5133 }
5134
5135 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5136
5137   if (Level >= AfterLegalizeTypes)
5138     return SDValue();
5139
5140   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5141   SDValue Mask = MSC->getMask();
5142   SDValue Data  = MSC->getValue();
5143   SDLoc DL(N);
5144
5145   // If the MSCATTER data type requires splitting and the mask is provided by a
5146   // SETCC, then split both nodes and its operands before legalization. This
5147   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5148   // and enables future optimizations (e.g. min/max pattern matching on X86).
5149   if (Mask.getOpcode() != ISD::SETCC)
5150     return SDValue();
5151
5152   // Check if any splitting is required.
5153   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5154       TargetLowering::TypeSplitVector)
5155     return SDValue();
5156   SDValue MaskLo, MaskHi, Lo, Hi;
5157   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5158
5159   EVT LoVT, HiVT;
5160   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5161
5162   SDValue Chain = MSC->getChain();
5163
5164   EVT MemoryVT = MSC->getMemoryVT();
5165   unsigned Alignment = MSC->getOriginalAlignment();
5166
5167   EVT LoMemVT, HiMemVT;
5168   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5169
5170   SDValue DataLo, DataHi;
5171   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5172
5173   SDValue BasePtr = MSC->getBasePtr();
5174   SDValue IndexLo, IndexHi;
5175   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5176
5177   MachineMemOperand *MMO = DAG.getMachineFunction().
5178     getMachineMemOperand(MSC->getPointerInfo(),
5179                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5180                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5181
5182   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5183   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5184                             DL, OpsLo, MMO);
5185
5186   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5187   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5188                             DL, OpsHi, MMO);
5189
5190   AddToWorklist(Lo.getNode());
5191   AddToWorklist(Hi.getNode());
5192
5193   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5194 }
5195
5196 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5197
5198   if (Level >= AfterLegalizeTypes)
5199     return SDValue();
5200
5201   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5202   SDValue Mask = MST->getMask();
5203   SDValue Data  = MST->getValue();
5204   SDLoc DL(N);
5205
5206   // If the MSTORE data type requires splitting and the mask is provided by a
5207   // SETCC, then split both nodes and its operands before legalization. This
5208   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5209   // and enables future optimizations (e.g. min/max pattern matching on X86).
5210   if (Mask.getOpcode() == ISD::SETCC) {
5211
5212     // Check if any splitting is required.
5213     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5214         TargetLowering::TypeSplitVector)
5215       return SDValue();
5216
5217     SDValue MaskLo, MaskHi, Lo, Hi;
5218     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5219
5220     EVT LoVT, HiVT;
5221     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5222
5223     SDValue Chain = MST->getChain();
5224     SDValue Ptr   = MST->getBasePtr();
5225
5226     EVT MemoryVT = MST->getMemoryVT();
5227     unsigned Alignment = MST->getOriginalAlignment();
5228
5229     // if Alignment is equal to the vector size,
5230     // take the half of it for the second part
5231     unsigned SecondHalfAlignment =
5232       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5233          Alignment/2 : Alignment;
5234
5235     EVT LoMemVT, HiMemVT;
5236     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5237
5238     SDValue DataLo, DataHi;
5239     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5240
5241     MachineMemOperand *MMO = DAG.getMachineFunction().
5242       getMachineMemOperand(MST->getPointerInfo(),
5243                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5244                            Alignment, MST->getAAInfo(), MST->getRanges());
5245
5246     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5247                             MST->isTruncatingStore());
5248
5249     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5250     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5251                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5252
5253     MMO = DAG.getMachineFunction().
5254       getMachineMemOperand(MST->getPointerInfo(),
5255                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5256                            SecondHalfAlignment, MST->getAAInfo(),
5257                            MST->getRanges());
5258
5259     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5260                             MST->isTruncatingStore());
5261
5262     AddToWorklist(Lo.getNode());
5263     AddToWorklist(Hi.getNode());
5264
5265     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5266   }
5267   return SDValue();
5268 }
5269
5270 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5271
5272   if (Level >= AfterLegalizeTypes)
5273     return SDValue();
5274
5275   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5276   SDValue Mask = MGT->getMask();
5277   SDLoc DL(N);
5278
5279   // If the MGATHER result requires splitting and the mask is provided by a
5280   // SETCC, then split both nodes and its operands before legalization. This
5281   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5282   // and enables future optimizations (e.g. min/max pattern matching on X86).
5283
5284   if (Mask.getOpcode() != ISD::SETCC)
5285     return SDValue();
5286
5287   EVT VT = N->getValueType(0);
5288
5289   // Check if any splitting is required.
5290   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5291       TargetLowering::TypeSplitVector)
5292     return SDValue();
5293
5294   SDValue MaskLo, MaskHi, Lo, Hi;
5295   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5296
5297   SDValue Src0 = MGT->getValue();
5298   SDValue Src0Lo, Src0Hi;
5299   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5300
5301   EVT LoVT, HiVT;
5302   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5303
5304   SDValue Chain = MGT->getChain();
5305   EVT MemoryVT = MGT->getMemoryVT();
5306   unsigned Alignment = MGT->getOriginalAlignment();
5307
5308   EVT LoMemVT, HiMemVT;
5309   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5310
5311   SDValue BasePtr = MGT->getBasePtr();
5312   SDValue Index = MGT->getIndex();
5313   SDValue IndexLo, IndexHi;
5314   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5315
5316   MachineMemOperand *MMO = DAG.getMachineFunction().
5317     getMachineMemOperand(MGT->getPointerInfo(),
5318                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5319                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5320
5321   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5322   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5323                             MMO);
5324
5325   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5326   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5327                             MMO);
5328
5329   AddToWorklist(Lo.getNode());
5330   AddToWorklist(Hi.getNode());
5331
5332   // Build a factor node to remember that this load is independent of the
5333   // other one.
5334   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5335                       Hi.getValue(1));
5336
5337   // Legalized the chain result - switch anything that used the old chain to
5338   // use the new one.
5339   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5340
5341   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5342
5343   SDValue RetOps[] = { GatherRes, Chain };
5344   return DAG.getMergeValues(RetOps, DL);
5345 }
5346
5347 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5348
5349   if (Level >= AfterLegalizeTypes)
5350     return SDValue();
5351
5352   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5353   SDValue Mask = MLD->getMask();
5354   SDLoc DL(N);
5355
5356   // If the MLOAD result requires splitting and the mask is provided by a
5357   // SETCC, then split both nodes and its operands before legalization. This
5358   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5359   // and enables future optimizations (e.g. min/max pattern matching on X86).
5360
5361   if (Mask.getOpcode() == ISD::SETCC) {
5362     EVT VT = N->getValueType(0);
5363
5364     // Check if any splitting is required.
5365     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5366         TargetLowering::TypeSplitVector)
5367       return SDValue();
5368
5369     SDValue MaskLo, MaskHi, Lo, Hi;
5370     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5371
5372     SDValue Src0 = MLD->getSrc0();
5373     SDValue Src0Lo, Src0Hi;
5374     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5375
5376     EVT LoVT, HiVT;
5377     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5378
5379     SDValue Chain = MLD->getChain();
5380     SDValue Ptr   = MLD->getBasePtr();
5381     EVT MemoryVT = MLD->getMemoryVT();
5382     unsigned Alignment = MLD->getOriginalAlignment();
5383
5384     // if Alignment is equal to the vector size,
5385     // take the half of it for the second part
5386     unsigned SecondHalfAlignment =
5387       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5388          Alignment/2 : Alignment;
5389
5390     EVT LoMemVT, HiMemVT;
5391     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5392
5393     MachineMemOperand *MMO = DAG.getMachineFunction().
5394     getMachineMemOperand(MLD->getPointerInfo(),
5395                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5396                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5397
5398     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5399                            ISD::NON_EXTLOAD);
5400
5401     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5402     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5403                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5404
5405     MMO = DAG.getMachineFunction().
5406     getMachineMemOperand(MLD->getPointerInfo(),
5407                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5408                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5409
5410     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5411                            ISD::NON_EXTLOAD);
5412
5413     AddToWorklist(Lo.getNode());
5414     AddToWorklist(Hi.getNode());
5415
5416     // Build a factor node to remember that this load is independent of the
5417     // other one.
5418     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5419                         Hi.getValue(1));
5420
5421     // Legalized the chain result - switch anything that used the old chain to
5422     // use the new one.
5423     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5424
5425     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5426
5427     SDValue RetOps[] = { LoadRes, Chain };
5428     return DAG.getMergeValues(RetOps, DL);
5429   }
5430   return SDValue();
5431 }
5432
5433 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5434   SDValue N0 = N->getOperand(0);
5435   SDValue N1 = N->getOperand(1);
5436   SDValue N2 = N->getOperand(2);
5437   SDLoc DL(N);
5438
5439   // Canonicalize integer abs.
5440   // vselect (setg[te] X,  0),  X, -X ->
5441   // vselect (setgt    X, -1),  X, -X ->
5442   // vselect (setl[te] X,  0), -X,  X ->
5443   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5444   if (N0.getOpcode() == ISD::SETCC) {
5445     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5446     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5447     bool isAbs = false;
5448     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5449
5450     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5451          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5452         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5453       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5454     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5455              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5456       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5457
5458     if (isAbs) {
5459       EVT VT = LHS.getValueType();
5460       SDValue Shift = DAG.getNode(
5461           ISD::SRA, DL, VT, LHS,
5462           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5463       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5464       AddToWorklist(Shift.getNode());
5465       AddToWorklist(Add.getNode());
5466       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5467     }
5468   }
5469
5470   if (SimplifySelectOps(N, N1, N2))
5471     return SDValue(N, 0);  // Don't revisit N.
5472
5473   // If the VSELECT result requires splitting and the mask is provided by a
5474   // SETCC, then split both nodes and its operands before legalization. This
5475   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5476   // and enables future optimizations (e.g. min/max pattern matching on X86).
5477   if (N0.getOpcode() == ISD::SETCC) {
5478     EVT VT = N->getValueType(0);
5479
5480     // Check if any splitting is required.
5481     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5482         TargetLowering::TypeSplitVector)
5483       return SDValue();
5484
5485     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5486     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5487     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5488     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5489
5490     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5491     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5492
5493     // Add the new VSELECT nodes to the work list in case they need to be split
5494     // again.
5495     AddToWorklist(Lo.getNode());
5496     AddToWorklist(Hi.getNode());
5497
5498     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5499   }
5500
5501   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5502   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5503     return N1;
5504   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5505   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5506     return N2;
5507
5508   // The ConvertSelectToConcatVector function is assuming both the above
5509   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5510   // and addressed.
5511   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5512       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5513       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5514     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5515     if (CV.getNode())
5516       return CV;
5517   }
5518
5519   return SDValue();
5520 }
5521
5522 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5523   SDValue N0 = N->getOperand(0);
5524   SDValue N1 = N->getOperand(1);
5525   SDValue N2 = N->getOperand(2);
5526   SDValue N3 = N->getOperand(3);
5527   SDValue N4 = N->getOperand(4);
5528   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5529
5530   // fold select_cc lhs, rhs, x, x, cc -> x
5531   if (N2 == N3)
5532     return N2;
5533
5534   // Determine if the condition we're dealing with is constant
5535   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5536                               N0, N1, CC, SDLoc(N), false);
5537   if (SCC.getNode()) {
5538     AddToWorklist(SCC.getNode());
5539
5540     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5541       if (!SCCC->isNullValue())
5542         return N2;    // cond always true -> true val
5543       else
5544         return N3;    // cond always false -> false val
5545     } else if (SCC->getOpcode() == ISD::UNDEF) {
5546       // When the condition is UNDEF, just return the first operand. This is
5547       // coherent the DAG creation, no setcc node is created in this case
5548       return N2;
5549     } else if (SCC.getOpcode() == ISD::SETCC) {
5550       // Fold to a simpler select_cc
5551       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5552                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5553                          SCC.getOperand(2));
5554     }
5555   }
5556
5557   // If we can fold this based on the true/false value, do so.
5558   if (SimplifySelectOps(N, N2, N3))
5559     return SDValue(N, 0);  // Don't revisit N.
5560
5561   // fold select_cc into other things, such as min/max/abs
5562   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5563 }
5564
5565 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5566   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5567                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5568                        SDLoc(N));
5569 }
5570
5571 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 
5572 /// a build_vector of constants.
5573 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5574 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5575 /// Vector extends are not folded if operations are legal; this is to
5576 /// avoid introducing illegal build_vector dag nodes.
5577 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5578                                          SelectionDAG &DAG, bool LegalTypes,
5579                                          bool LegalOperations) {
5580   unsigned Opcode = N->getOpcode();
5581   SDValue N0 = N->getOperand(0);
5582   EVT VT = N->getValueType(0);
5583
5584   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5585          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5586          && "Expected EXTEND dag node in input!");
5587
5588   // fold (sext c1) -> c1
5589   // fold (zext c1) -> c1
5590   // fold (aext c1) -> c1
5591   if (isa<ConstantSDNode>(N0))
5592     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5593
5594   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5595   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5596   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5597   EVT SVT = VT.getScalarType();
5598   if (!(VT.isVector() &&
5599       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5600       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5601     return nullptr;
5602
5603   // We can fold this node into a build_vector.
5604   unsigned VTBits = SVT.getSizeInBits();
5605   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5606   SmallVector<SDValue, 8> Elts;
5607   unsigned NumElts = VT.getVectorNumElements();
5608   SDLoc DL(N);
5609
5610   for (unsigned i=0; i != NumElts; ++i) {
5611     SDValue Op = N0->getOperand(i);
5612     if (Op->getOpcode() == ISD::UNDEF) {
5613       Elts.push_back(DAG.getUNDEF(SVT));
5614       continue;
5615     }
5616
5617     SDLoc DL(Op);
5618     // Get the constant value and if needed trunc it to the size of the type.
5619     // Nodes like build_vector might have constants wider than the scalar type.
5620     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5621     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5622       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5623     else
5624       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5625   }
5626
5627   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5628 }
5629
5630 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5631 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5632 // transformation. Returns true if extension are possible and the above
5633 // mentioned transformation is profitable.
5634 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5635                                     unsigned ExtOpc,
5636                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5637                                     const TargetLowering &TLI) {
5638   bool HasCopyToRegUses = false;
5639   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5640   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5641                             UE = N0.getNode()->use_end();
5642        UI != UE; ++UI) {
5643     SDNode *User = *UI;
5644     if (User == N)
5645       continue;
5646     if (UI.getUse().getResNo() != N0.getResNo())
5647       continue;
5648     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5649     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5650       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5651       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5652         // Sign bits will be lost after a zext.
5653         return false;
5654       bool Add = false;
5655       for (unsigned i = 0; i != 2; ++i) {
5656         SDValue UseOp = User->getOperand(i);
5657         if (UseOp == N0)
5658           continue;
5659         if (!isa<ConstantSDNode>(UseOp))
5660           return false;
5661         Add = true;
5662       }
5663       if (Add)
5664         ExtendNodes.push_back(User);
5665       continue;
5666     }
5667     // If truncates aren't free and there are users we can't
5668     // extend, it isn't worthwhile.
5669     if (!isTruncFree)
5670       return false;
5671     // Remember if this value is live-out.
5672     if (User->getOpcode() == ISD::CopyToReg)
5673       HasCopyToRegUses = true;
5674   }
5675
5676   if (HasCopyToRegUses) {
5677     bool BothLiveOut = false;
5678     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5679          UI != UE; ++UI) {
5680       SDUse &Use = UI.getUse();
5681       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5682         BothLiveOut = true;
5683         break;
5684       }
5685     }
5686     if (BothLiveOut)
5687       // Both unextended and extended values are live out. There had better be
5688       // a good reason for the transformation.
5689       return ExtendNodes.size();
5690   }
5691   return true;
5692 }
5693
5694 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5695                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5696                                   ISD::NodeType ExtType) {
5697   // Extend SetCC uses if necessary.
5698   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5699     SDNode *SetCC = SetCCs[i];
5700     SmallVector<SDValue, 4> Ops;
5701
5702     for (unsigned j = 0; j != 2; ++j) {
5703       SDValue SOp = SetCC->getOperand(j);
5704       if (SOp == Trunc)
5705         Ops.push_back(ExtLoad);
5706       else
5707         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5708     }
5709
5710     Ops.push_back(SetCC->getOperand(2));
5711     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5712   }
5713 }
5714
5715 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5716 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5717   SDValue N0 = N->getOperand(0);
5718   EVT DstVT = N->getValueType(0);
5719   EVT SrcVT = N0.getValueType();
5720
5721   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5722           N->getOpcode() == ISD::ZERO_EXTEND) &&
5723          "Unexpected node type (not an extend)!");
5724
5725   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5726   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5727   //   (v8i32 (sext (v8i16 (load x))))
5728   // into:
5729   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5730   //                          (v4i32 (sextload (x + 16)))))
5731   // Where uses of the original load, i.e.:
5732   //   (v8i16 (load x))
5733   // are replaced with:
5734   //   (v8i16 (truncate
5735   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5736   //                            (v4i32 (sextload (x + 16)))))))
5737   //
5738   // This combine is only applicable to illegal, but splittable, vectors.
5739   // All legal types, and illegal non-vector types, are handled elsewhere.
5740   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5741   //
5742   if (N0->getOpcode() != ISD::LOAD)
5743     return SDValue();
5744
5745   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5746
5747   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5748       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5749       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5750     return SDValue();
5751
5752   SmallVector<SDNode *, 4> SetCCs;
5753   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5754     return SDValue();
5755
5756   ISD::LoadExtType ExtType =
5757       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5758
5759   // Try to split the vector types to get down to legal types.
5760   EVT SplitSrcVT = SrcVT;
5761   EVT SplitDstVT = DstVT;
5762   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5763          SplitSrcVT.getVectorNumElements() > 1) {
5764     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5765     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5766   }
5767
5768   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5769     return SDValue();
5770
5771   SDLoc DL(N);
5772   const unsigned NumSplits =
5773       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5774   const unsigned Stride = SplitSrcVT.getStoreSize();
5775   SmallVector<SDValue, 4> Loads;
5776   SmallVector<SDValue, 4> Chains;
5777
5778   SDValue BasePtr = LN0->getBasePtr();
5779   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5780     const unsigned Offset = Idx * Stride;
5781     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5782
5783     SDValue SplitLoad = DAG.getExtLoad(
5784         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5785         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5786         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5787         Align, LN0->getAAInfo());
5788
5789     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5790                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5791
5792     Loads.push_back(SplitLoad.getValue(0));
5793     Chains.push_back(SplitLoad.getValue(1));
5794   }
5795
5796   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5797   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5798
5799   CombineTo(N, NewValue);
5800
5801   // Replace uses of the original load (before extension)
5802   // with a truncate of the concatenated sextloaded vectors.
5803   SDValue Trunc =
5804       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5805   CombineTo(N0.getNode(), Trunc, NewChain);
5806   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5807                   (ISD::NodeType)N->getOpcode());
5808   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5809 }
5810
5811 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5812   SDValue N0 = N->getOperand(0);
5813   EVT VT = N->getValueType(0);
5814
5815   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5816                                               LegalOperations))
5817     return SDValue(Res, 0);
5818
5819   // fold (sext (sext x)) -> (sext x)
5820   // fold (sext (aext x)) -> (sext x)
5821   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5822     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5823                        N0.getOperand(0));
5824
5825   if (N0.getOpcode() == ISD::TRUNCATE) {
5826     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5827     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5828     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5829       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5830       if (NarrowLoad.getNode() != N0.getNode()) {
5831         CombineTo(N0.getNode(), NarrowLoad);
5832         // CombineTo deleted the truncate, if needed, but not what's under it.
5833         AddToWorklist(oye);
5834       }
5835       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5836     }
5837
5838     // See if the value being truncated is already sign extended.  If so, just
5839     // eliminate the trunc/sext pair.
5840     SDValue Op = N0.getOperand(0);
5841     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5842     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5843     unsigned DestBits = VT.getScalarType().getSizeInBits();
5844     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5845
5846     if (OpBits == DestBits) {
5847       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5848       // bits, it is already ready.
5849       if (NumSignBits > DestBits-MidBits)
5850         return Op;
5851     } else if (OpBits < DestBits) {
5852       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5853       // bits, just sext from i32.
5854       if (NumSignBits > OpBits-MidBits)
5855         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5856     } else {
5857       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5858       // bits, just truncate to i32.
5859       if (NumSignBits > OpBits-MidBits)
5860         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5861     }
5862
5863     // fold (sext (truncate x)) -> (sextinreg x).
5864     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5865                                                  N0.getValueType())) {
5866       if (OpBits < DestBits)
5867         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5868       else if (OpBits > DestBits)
5869         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5870       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5871                          DAG.getValueType(N0.getValueType()));
5872     }
5873   }
5874
5875   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5876   // Only generate vector extloads when 1) they're legal, and 2) they are
5877   // deemed desirable by the target.
5878   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5879       ((!LegalOperations && !VT.isVector() &&
5880         !cast<LoadSDNode>(N0)->isVolatile()) ||
5881        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5882     bool DoXform = true;
5883     SmallVector<SDNode*, 4> SetCCs;
5884     if (!N0.hasOneUse())
5885       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5886     if (VT.isVector())
5887       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5888     if (DoXform) {
5889       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5890       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5891                                        LN0->getChain(),
5892                                        LN0->getBasePtr(), N0.getValueType(),
5893                                        LN0->getMemOperand());
5894       CombineTo(N, ExtLoad);
5895       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5896                                   N0.getValueType(), ExtLoad);
5897       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5898       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5899                       ISD::SIGN_EXTEND);
5900       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5901     }
5902   }
5903
5904   // fold (sext (load x)) to multiple smaller sextloads.
5905   // Only on illegal but splittable vectors.
5906   if (SDValue ExtLoad = CombineExtLoad(N))
5907     return ExtLoad;
5908
5909   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5910   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5911   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5912       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5913     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5914     EVT MemVT = LN0->getMemoryVT();
5915     if ((!LegalOperations && !LN0->isVolatile()) ||
5916         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5917       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5918                                        LN0->getChain(),
5919                                        LN0->getBasePtr(), MemVT,
5920                                        LN0->getMemOperand());
5921       CombineTo(N, ExtLoad);
5922       CombineTo(N0.getNode(),
5923                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5924                             N0.getValueType(), ExtLoad),
5925                 ExtLoad.getValue(1));
5926       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5927     }
5928   }
5929
5930   // fold (sext (and/or/xor (load x), cst)) ->
5931   //      (and/or/xor (sextload x), (sext cst))
5932   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5933        N0.getOpcode() == ISD::XOR) &&
5934       isa<LoadSDNode>(N0.getOperand(0)) &&
5935       N0.getOperand(1).getOpcode() == ISD::Constant &&
5936       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5937       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5938     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5939     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5940       bool DoXform = true;
5941       SmallVector<SDNode*, 4> SetCCs;
5942       if (!N0.hasOneUse())
5943         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5944                                           SetCCs, TLI);
5945       if (DoXform) {
5946         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5947                                          LN0->getChain(), LN0->getBasePtr(),
5948                                          LN0->getMemoryVT(),
5949                                          LN0->getMemOperand());
5950         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5951         Mask = Mask.sext(VT.getSizeInBits());
5952         SDLoc DL(N);
5953         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5954                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5955         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5956                                     SDLoc(N0.getOperand(0)),
5957                                     N0.getOperand(0).getValueType(), ExtLoad);
5958         CombineTo(N, And);
5959         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5960         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5961                         ISD::SIGN_EXTEND);
5962         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5963       }
5964     }
5965   }
5966
5967   if (N0.getOpcode() == ISD::SETCC) {
5968     EVT N0VT = N0.getOperand(0).getValueType();
5969     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5970     // Only do this before legalize for now.
5971     if (VT.isVector() && !LegalOperations &&
5972         TLI.getBooleanContents(N0VT) ==
5973             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5974       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5975       // of the same size as the compared operands. Only optimize sext(setcc())
5976       // if this is the case.
5977       EVT SVT = getSetCCResultType(N0VT);
5978
5979       // We know that the # elements of the results is the same as the
5980       // # elements of the compare (and the # elements of the compare result
5981       // for that matter).  Check to see that they are the same size.  If so,
5982       // we know that the element size of the sext'd result matches the
5983       // element size of the compare operands.
5984       if (VT.getSizeInBits() == SVT.getSizeInBits())
5985         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5986                              N0.getOperand(1),
5987                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5988
5989       // If the desired elements are smaller or larger than the source
5990       // elements we can use a matching integer vector type and then
5991       // truncate/sign extend
5992       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5993       if (SVT == MatchingVectorType) {
5994         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5995                                N0.getOperand(0), N0.getOperand(1),
5996                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5997         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5998       }
5999     }
6000
6001     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6002     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6003     SDLoc DL(N);
6004     SDValue NegOne =
6005       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6006     SDValue SCC =
6007       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6008                        NegOne, DAG.getConstant(0, DL, VT),
6009                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6010     if (SCC.getNode()) return SCC;
6011
6012     if (!VT.isVector()) {
6013       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6014       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6015         SDLoc DL(N);
6016         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6017         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6018                                      N0.getOperand(0), N0.getOperand(1), CC);
6019         return DAG.getSelect(DL, VT, SetCC,
6020                              NegOne, DAG.getConstant(0, DL, VT));
6021       }
6022     }
6023   }
6024
6025   // fold (sext x) -> (zext x) if the sign bit is known zero.
6026   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6027       DAG.SignBitIsZero(N0))
6028     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6029
6030   return SDValue();
6031 }
6032
6033 // isTruncateOf - If N is a truncate of some other value, return true, record
6034 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6035 // This function computes KnownZero to avoid a duplicated call to
6036 // computeKnownBits in the caller.
6037 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6038                          APInt &KnownZero) {
6039   APInt KnownOne;
6040   if (N->getOpcode() == ISD::TRUNCATE) {
6041     Op = N->getOperand(0);
6042     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6043     return true;
6044   }
6045
6046   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6047       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6048     return false;
6049
6050   SDValue Op0 = N->getOperand(0);
6051   SDValue Op1 = N->getOperand(1);
6052   assert(Op0.getValueType() == Op1.getValueType());
6053
6054   if (isNullConstant(Op0))
6055     Op = Op1;
6056   else if (isNullConstant(Op1))
6057     Op = Op0;
6058   else
6059     return false;
6060
6061   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6062
6063   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6064     return false;
6065
6066   return true;
6067 }
6068
6069 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6070   SDValue N0 = N->getOperand(0);
6071   EVT VT = N->getValueType(0);
6072
6073   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6074                                               LegalOperations))
6075     return SDValue(Res, 0);
6076
6077   // fold (zext (zext x)) -> (zext x)
6078   // fold (zext (aext x)) -> (zext x)
6079   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6080     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6081                        N0.getOperand(0));
6082
6083   // fold (zext (truncate x)) -> (zext x) or
6084   //      (zext (truncate x)) -> (truncate x)
6085   // This is valid when the truncated bits of x are already zero.
6086   // FIXME: We should extend this to work for vectors too.
6087   SDValue Op;
6088   APInt KnownZero;
6089   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6090     APInt TruncatedBits =
6091       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6092       APInt(Op.getValueSizeInBits(), 0) :
6093       APInt::getBitsSet(Op.getValueSizeInBits(),
6094                         N0.getValueSizeInBits(),
6095                         std::min(Op.getValueSizeInBits(),
6096                                  VT.getSizeInBits()));
6097     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6098       if (VT.bitsGT(Op.getValueType()))
6099         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6100       if (VT.bitsLT(Op.getValueType()))
6101         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6102
6103       return Op;
6104     }
6105   }
6106
6107   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6108   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6109   if (N0.getOpcode() == ISD::TRUNCATE) {
6110     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6111       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6112       if (NarrowLoad.getNode() != N0.getNode()) {
6113         CombineTo(N0.getNode(), NarrowLoad);
6114         // CombineTo deleted the truncate, if needed, but not what's under it.
6115         AddToWorklist(oye);
6116       }
6117       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6118     }
6119   }
6120
6121   // fold (zext (truncate x)) -> (and x, mask)
6122   if (N0.getOpcode() == ISD::TRUNCATE &&
6123       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6124
6125     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6126     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6127     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6128       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6129       if (NarrowLoad.getNode() != N0.getNode()) {
6130         CombineTo(N0.getNode(), NarrowLoad);
6131         // CombineTo deleted the truncate, if needed, but not what's under it.
6132         AddToWorklist(oye);
6133       }
6134       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6135     }
6136
6137     SDValue Op = N0.getOperand(0);
6138     if (Op.getValueType().bitsLT(VT)) {
6139       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6140       AddToWorklist(Op.getNode());
6141     } else if (Op.getValueType().bitsGT(VT)) {
6142       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6143       AddToWorklist(Op.getNode());
6144     }
6145     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6146                                   N0.getValueType().getScalarType());
6147   }
6148
6149   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6150   // if either of the casts is not free.
6151   if (N0.getOpcode() == ISD::AND &&
6152       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6153       N0.getOperand(1).getOpcode() == ISD::Constant &&
6154       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6155                            N0.getValueType()) ||
6156        !TLI.isZExtFree(N0.getValueType(), VT))) {
6157     SDValue X = N0.getOperand(0).getOperand(0);
6158     if (X.getValueType().bitsLT(VT)) {
6159       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6160     } else if (X.getValueType().bitsGT(VT)) {
6161       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6162     }
6163     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6164     Mask = Mask.zext(VT.getSizeInBits());
6165     SDLoc DL(N);
6166     return DAG.getNode(ISD::AND, DL, VT,
6167                        X, DAG.getConstant(Mask, DL, VT));
6168   }
6169
6170   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6171   // Only generate vector extloads when 1) they're legal, and 2) they are
6172   // deemed desirable by the target.
6173   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6174       ((!LegalOperations && !VT.isVector() &&
6175         !cast<LoadSDNode>(N0)->isVolatile()) ||
6176        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6177     bool DoXform = true;
6178     SmallVector<SDNode*, 4> SetCCs;
6179     if (!N0.hasOneUse())
6180       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6181     if (VT.isVector())
6182       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6183     if (DoXform) {
6184       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6185       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6186                                        LN0->getChain(),
6187                                        LN0->getBasePtr(), N0.getValueType(),
6188                                        LN0->getMemOperand());
6189       CombineTo(N, ExtLoad);
6190       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6191                                   N0.getValueType(), ExtLoad);
6192       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6193
6194       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6195                       ISD::ZERO_EXTEND);
6196       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6197     }
6198   }
6199
6200   // fold (zext (load x)) to multiple smaller zextloads.
6201   // Only on illegal but splittable vectors.
6202   if (SDValue ExtLoad = CombineExtLoad(N))
6203     return ExtLoad;
6204
6205   // fold (zext (and/or/xor (load x), cst)) ->
6206   //      (and/or/xor (zextload x), (zext cst))
6207   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6208        N0.getOpcode() == ISD::XOR) &&
6209       isa<LoadSDNode>(N0.getOperand(0)) &&
6210       N0.getOperand(1).getOpcode() == ISD::Constant &&
6211       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6212       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6213     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6214     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6215       bool DoXform = true;
6216       SmallVector<SDNode*, 4> SetCCs;
6217       if (!N0.hasOneUse())
6218         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6219                                           SetCCs, TLI);
6220       if (DoXform) {
6221         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6222                                          LN0->getChain(), LN0->getBasePtr(),
6223                                          LN0->getMemoryVT(),
6224                                          LN0->getMemOperand());
6225         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6226         Mask = Mask.zext(VT.getSizeInBits());
6227         SDLoc DL(N);
6228         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6229                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6230         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6231                                     SDLoc(N0.getOperand(0)),
6232                                     N0.getOperand(0).getValueType(), ExtLoad);
6233         CombineTo(N, And);
6234         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6235         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6236                         ISD::ZERO_EXTEND);
6237         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6238       }
6239     }
6240   }
6241
6242   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6243   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6244   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6245       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6246     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6247     EVT MemVT = LN0->getMemoryVT();
6248     if ((!LegalOperations && !LN0->isVolatile()) ||
6249         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6250       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6251                                        LN0->getChain(),
6252                                        LN0->getBasePtr(), MemVT,
6253                                        LN0->getMemOperand());
6254       CombineTo(N, ExtLoad);
6255       CombineTo(N0.getNode(),
6256                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6257                             ExtLoad),
6258                 ExtLoad.getValue(1));
6259       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6260     }
6261   }
6262
6263   if (N0.getOpcode() == ISD::SETCC) {
6264     if (!LegalOperations && VT.isVector() &&
6265         N0.getValueType().getVectorElementType() == MVT::i1) {
6266       EVT N0VT = N0.getOperand(0).getValueType();
6267       if (getSetCCResultType(N0VT) == N0.getValueType())
6268         return SDValue();
6269
6270       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6271       // Only do this before legalize for now.
6272       EVT EltVT = VT.getVectorElementType();
6273       SDLoc DL(N);
6274       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6275                                     DAG.getConstant(1, DL, EltVT));
6276       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6277         // We know that the # elements of the results is the same as the
6278         // # elements of the compare (and the # elements of the compare result
6279         // for that matter).  Check to see that they are the same size.  If so,
6280         // we know that the element size of the sext'd result matches the
6281         // element size of the compare operands.
6282         return DAG.getNode(ISD::AND, DL, VT,
6283                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6284                                          N0.getOperand(1),
6285                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6286                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6287                                        OneOps));
6288
6289       // If the desired elements are smaller or larger than the source
6290       // elements we can use a matching integer vector type and then
6291       // truncate/sign extend
6292       EVT MatchingElementType =
6293         EVT::getIntegerVT(*DAG.getContext(),
6294                           N0VT.getScalarType().getSizeInBits());
6295       EVT MatchingVectorType =
6296         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6297                          N0VT.getVectorNumElements());
6298       SDValue VsetCC =
6299         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6300                       N0.getOperand(1),
6301                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6302       return DAG.getNode(ISD::AND, DL, VT,
6303                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6304                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6305     }
6306
6307     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6308     SDLoc DL(N);
6309     SDValue SCC =
6310       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6311                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6312                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6313     if (SCC.getNode()) return SCC;
6314   }
6315
6316   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6317   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6318       isa<ConstantSDNode>(N0.getOperand(1)) &&
6319       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6320       N0.hasOneUse()) {
6321     SDValue ShAmt = N0.getOperand(1);
6322     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6323     if (N0.getOpcode() == ISD::SHL) {
6324       SDValue InnerZExt = N0.getOperand(0);
6325       // If the original shl may be shifting out bits, do not perform this
6326       // transformation.
6327       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6328         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6329       if (ShAmtVal > KnownZeroBits)
6330         return SDValue();
6331     }
6332
6333     SDLoc DL(N);
6334
6335     // Ensure that the shift amount is wide enough for the shifted value.
6336     if (VT.getSizeInBits() >= 256)
6337       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6338
6339     return DAG.getNode(N0.getOpcode(), DL, VT,
6340                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6341                        ShAmt);
6342   }
6343
6344   return SDValue();
6345 }
6346
6347 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6348   SDValue N0 = N->getOperand(0);
6349   EVT VT = N->getValueType(0);
6350
6351   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6352                                               LegalOperations))
6353     return SDValue(Res, 0);
6354
6355   // fold (aext (aext x)) -> (aext x)
6356   // fold (aext (zext x)) -> (zext x)
6357   // fold (aext (sext x)) -> (sext x)
6358   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6359       N0.getOpcode() == ISD::ZERO_EXTEND ||
6360       N0.getOpcode() == ISD::SIGN_EXTEND)
6361     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6362
6363   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6364   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6365   if (N0.getOpcode() == ISD::TRUNCATE) {
6366     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6367     if (NarrowLoad.getNode()) {
6368       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6369       if (NarrowLoad.getNode() != N0.getNode()) {
6370         CombineTo(N0.getNode(), NarrowLoad);
6371         // CombineTo deleted the truncate, if needed, but not what's under it.
6372         AddToWorklist(oye);
6373       }
6374       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6375     }
6376   }
6377
6378   // fold (aext (truncate x))
6379   if (N0.getOpcode() == ISD::TRUNCATE) {
6380     SDValue TruncOp = N0.getOperand(0);
6381     if (TruncOp.getValueType() == VT)
6382       return TruncOp; // x iff x size == zext size.
6383     if (TruncOp.getValueType().bitsGT(VT))
6384       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6385     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6386   }
6387
6388   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6389   // if the trunc is not free.
6390   if (N0.getOpcode() == ISD::AND &&
6391       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6392       N0.getOperand(1).getOpcode() == ISD::Constant &&
6393       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6394                           N0.getValueType())) {
6395     SDValue X = N0.getOperand(0).getOperand(0);
6396     if (X.getValueType().bitsLT(VT)) {
6397       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6398     } else if (X.getValueType().bitsGT(VT)) {
6399       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6400     }
6401     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6402     Mask = Mask.zext(VT.getSizeInBits());
6403     SDLoc DL(N);
6404     return DAG.getNode(ISD::AND, DL, VT,
6405                        X, DAG.getConstant(Mask, DL, VT));
6406   }
6407
6408   // fold (aext (load x)) -> (aext (truncate (extload x)))
6409   // None of the supported targets knows how to perform load and any_ext
6410   // on vectors in one instruction.  We only perform this transformation on
6411   // scalars.
6412   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6413       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6414       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6415     bool DoXform = true;
6416     SmallVector<SDNode*, 4> SetCCs;
6417     if (!N0.hasOneUse())
6418       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6419     if (DoXform) {
6420       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6421       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6422                                        LN0->getChain(),
6423                                        LN0->getBasePtr(), N0.getValueType(),
6424                                        LN0->getMemOperand());
6425       CombineTo(N, ExtLoad);
6426       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6427                                   N0.getValueType(), ExtLoad);
6428       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6429       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6430                       ISD::ANY_EXTEND);
6431       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6432     }
6433   }
6434
6435   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6436   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6437   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6438   if (N0.getOpcode() == ISD::LOAD &&
6439       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6440       N0.hasOneUse()) {
6441     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6442     ISD::LoadExtType ExtType = LN0->getExtensionType();
6443     EVT MemVT = LN0->getMemoryVT();
6444     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6445       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6446                                        VT, LN0->getChain(), LN0->getBasePtr(),
6447                                        MemVT, LN0->getMemOperand());
6448       CombineTo(N, ExtLoad);
6449       CombineTo(N0.getNode(),
6450                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6451                             N0.getValueType(), ExtLoad),
6452                 ExtLoad.getValue(1));
6453       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6454     }
6455   }
6456
6457   if (N0.getOpcode() == ISD::SETCC) {
6458     // For vectors:
6459     // aext(setcc) -> vsetcc
6460     // aext(setcc) -> truncate(vsetcc)
6461     // aext(setcc) -> aext(vsetcc)
6462     // Only do this before legalize for now.
6463     if (VT.isVector() && !LegalOperations) {
6464       EVT N0VT = N0.getOperand(0).getValueType();
6465         // We know that the # elements of the results is the same as the
6466         // # elements of the compare (and the # elements of the compare result
6467         // for that matter).  Check to see that they are the same size.  If so,
6468         // we know that the element size of the sext'd result matches the
6469         // element size of the compare operands.
6470       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6471         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6472                              N0.getOperand(1),
6473                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6474       // If the desired elements are smaller or larger than the source
6475       // elements we can use a matching integer vector type and then
6476       // truncate/any extend
6477       else {
6478         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6479         SDValue VsetCC =
6480           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6481                         N0.getOperand(1),
6482                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6483         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6484       }
6485     }
6486
6487     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6488     SDLoc DL(N);
6489     SDValue SCC =
6490       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6491                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6492                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6493     if (SCC.getNode())
6494       return SCC;
6495   }
6496
6497   return SDValue();
6498 }
6499
6500 /// See if the specified operand can be simplified with the knowledge that only
6501 /// the bits specified by Mask are used.  If so, return the simpler operand,
6502 /// otherwise return a null SDValue.
6503 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6504   switch (V.getOpcode()) {
6505   default: break;
6506   case ISD::Constant: {
6507     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6508     assert(CV && "Const value should be ConstSDNode.");
6509     const APInt &CVal = CV->getAPIntValue();
6510     APInt NewVal = CVal & Mask;
6511     if (NewVal != CVal)
6512       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6513     break;
6514   }
6515   case ISD::OR:
6516   case ISD::XOR:
6517     // If the LHS or RHS don't contribute bits to the or, drop them.
6518     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6519       return V.getOperand(1);
6520     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6521       return V.getOperand(0);
6522     break;
6523   case ISD::SRL:
6524     // Only look at single-use SRLs.
6525     if (!V.getNode()->hasOneUse())
6526       break;
6527     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6528       // See if we can recursively simplify the LHS.
6529       unsigned Amt = RHSC->getZExtValue();
6530
6531       // Watch out for shift count overflow though.
6532       if (Amt >= Mask.getBitWidth()) break;
6533       APInt NewMask = Mask << Amt;
6534       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6535         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6536                            SimplifyLHS, V.getOperand(1));
6537     }
6538   }
6539   return SDValue();
6540 }
6541
6542 /// If the result of a wider load is shifted to right of N  bits and then
6543 /// truncated to a narrower type and where N is a multiple of number of bits of
6544 /// the narrower type, transform it to a narrower load from address + N / num of
6545 /// bits of new type. If the result is to be extended, also fold the extension
6546 /// to form a extending load.
6547 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6548   unsigned Opc = N->getOpcode();
6549
6550   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6551   SDValue N0 = N->getOperand(0);
6552   EVT VT = N->getValueType(0);
6553   EVT ExtVT = VT;
6554
6555   // This transformation isn't valid for vector loads.
6556   if (VT.isVector())
6557     return SDValue();
6558
6559   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6560   // extended to VT.
6561   if (Opc == ISD::SIGN_EXTEND_INREG) {
6562     ExtType = ISD::SEXTLOAD;
6563     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6564   } else if (Opc == ISD::SRL) {
6565     // Another special-case: SRL is basically zero-extending a narrower value.
6566     ExtType = ISD::ZEXTLOAD;
6567     N0 = SDValue(N, 0);
6568     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6569     if (!N01) return SDValue();
6570     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6571                               VT.getSizeInBits() - N01->getZExtValue());
6572   }
6573   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6574     return SDValue();
6575
6576   unsigned EVTBits = ExtVT.getSizeInBits();
6577
6578   // Do not generate loads of non-round integer types since these can
6579   // be expensive (and would be wrong if the type is not byte sized).
6580   if (!ExtVT.isRound())
6581     return SDValue();
6582
6583   unsigned ShAmt = 0;
6584   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6585     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6586       ShAmt = N01->getZExtValue();
6587       // Is the shift amount a multiple of size of VT?
6588       if ((ShAmt & (EVTBits-1)) == 0) {
6589         N0 = N0.getOperand(0);
6590         // Is the load width a multiple of size of VT?
6591         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6592           return SDValue();
6593       }
6594
6595       // At this point, we must have a load or else we can't do the transform.
6596       if (!isa<LoadSDNode>(N0)) return SDValue();
6597
6598       // Because a SRL must be assumed to *need* to zero-extend the high bits
6599       // (as opposed to anyext the high bits), we can't combine the zextload
6600       // lowering of SRL and an sextload.
6601       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6602         return SDValue();
6603
6604       // If the shift amount is larger than the input type then we're not
6605       // accessing any of the loaded bytes.  If the load was a zextload/extload
6606       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6607       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6608         return SDValue();
6609     }
6610   }
6611
6612   // If the load is shifted left (and the result isn't shifted back right),
6613   // we can fold the truncate through the shift.
6614   unsigned ShLeftAmt = 0;
6615   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6616       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6617     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6618       ShLeftAmt = N01->getZExtValue();
6619       N0 = N0.getOperand(0);
6620     }
6621   }
6622
6623   // If we haven't found a load, we can't narrow it.  Don't transform one with
6624   // multiple uses, this would require adding a new load.
6625   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6626     return SDValue();
6627
6628   // Don't change the width of a volatile load.
6629   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6630   if (LN0->isVolatile())
6631     return SDValue();
6632
6633   // Verify that we are actually reducing a load width here.
6634   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6635     return SDValue();
6636
6637   // For the transform to be legal, the load must produce only two values
6638   // (the value loaded and the chain).  Don't transform a pre-increment
6639   // load, for example, which produces an extra value.  Otherwise the
6640   // transformation is not equivalent, and the downstream logic to replace
6641   // uses gets things wrong.
6642   if (LN0->getNumValues() > 2)
6643     return SDValue();
6644
6645   // If the load that we're shrinking is an extload and we're not just
6646   // discarding the extension we can't simply shrink the load. Bail.
6647   // TODO: It would be possible to merge the extensions in some cases.
6648   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6649       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6650     return SDValue();
6651
6652   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6653     return SDValue();
6654
6655   EVT PtrType = N0.getOperand(1).getValueType();
6656
6657   if (PtrType == MVT::Untyped || PtrType.isExtended())
6658     // It's not possible to generate a constant of extended or untyped type.
6659     return SDValue();
6660
6661   // For big endian targets, we need to adjust the offset to the pointer to
6662   // load the correct bytes.
6663   if (DAG.getDataLayout().isBigEndian()) {
6664     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6665     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6666     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6667   }
6668
6669   uint64_t PtrOff = ShAmt / 8;
6670   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6671   SDLoc DL(LN0);
6672   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6673                                PtrType, LN0->getBasePtr(),
6674                                DAG.getConstant(PtrOff, DL, PtrType));
6675   AddToWorklist(NewPtr.getNode());
6676
6677   SDValue Load;
6678   if (ExtType == ISD::NON_EXTLOAD)
6679     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6680                         LN0->getPointerInfo().getWithOffset(PtrOff),
6681                         LN0->isVolatile(), LN0->isNonTemporal(),
6682                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6683   else
6684     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6685                           LN0->getPointerInfo().getWithOffset(PtrOff),
6686                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6687                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6688
6689   // Replace the old load's chain with the new load's chain.
6690   WorklistRemover DeadNodes(*this);
6691   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6692
6693   // Shift the result left, if we've swallowed a left shift.
6694   SDValue Result = Load;
6695   if (ShLeftAmt != 0) {
6696     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6697     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6698       ShImmTy = VT;
6699     // If the shift amount is as large as the result size (but, presumably,
6700     // no larger than the source) then the useful bits of the result are
6701     // zero; we can't simply return the shortened shift, because the result
6702     // of that operation is undefined.
6703     SDLoc DL(N0);
6704     if (ShLeftAmt >= VT.getSizeInBits())
6705       Result = DAG.getConstant(0, DL, VT);
6706     else
6707       Result = DAG.getNode(ISD::SHL, DL, VT,
6708                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6709   }
6710
6711   // Return the new loaded value.
6712   return Result;
6713 }
6714
6715 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6716   SDValue N0 = N->getOperand(0);
6717   SDValue N1 = N->getOperand(1);
6718   EVT VT = N->getValueType(0);
6719   EVT EVT = cast<VTSDNode>(N1)->getVT();
6720   unsigned VTBits = VT.getScalarType().getSizeInBits();
6721   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6722
6723   // fold (sext_in_reg c1) -> c1
6724   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6725     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6726
6727   // If the input is already sign extended, just drop the extension.
6728   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6729     return N0;
6730
6731   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6732   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6733       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6734     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6735                        N0.getOperand(0), N1);
6736
6737   // fold (sext_in_reg (sext x)) -> (sext x)
6738   // fold (sext_in_reg (aext x)) -> (sext x)
6739   // if x is small enough.
6740   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6741     SDValue N00 = N0.getOperand(0);
6742     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6743         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6744       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6745   }
6746
6747   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6748   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6749     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6750
6751   // fold operands of sext_in_reg based on knowledge that the top bits are not
6752   // demanded.
6753   if (SimplifyDemandedBits(SDValue(N, 0)))
6754     return SDValue(N, 0);
6755
6756   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6757   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6758   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6759     return NarrowLoad;
6760
6761   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6762   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6763   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6764   if (N0.getOpcode() == ISD::SRL) {
6765     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6766       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6767         // We can turn this into an SRA iff the input to the SRL is already sign
6768         // extended enough.
6769         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6770         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6771           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6772                              N0.getOperand(0), N0.getOperand(1));
6773       }
6774   }
6775
6776   // fold (sext_inreg (extload x)) -> (sextload x)
6777   if (ISD::isEXTLoad(N0.getNode()) &&
6778       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6779       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6780       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6781        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6782     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6783     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6784                                      LN0->getChain(),
6785                                      LN0->getBasePtr(), EVT,
6786                                      LN0->getMemOperand());
6787     CombineTo(N, ExtLoad);
6788     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6789     AddToWorklist(ExtLoad.getNode());
6790     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6791   }
6792   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6793   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6794       N0.hasOneUse() &&
6795       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6796       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6797        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6798     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6799     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6800                                      LN0->getChain(),
6801                                      LN0->getBasePtr(), EVT,
6802                                      LN0->getMemOperand());
6803     CombineTo(N, ExtLoad);
6804     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6805     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6806   }
6807
6808   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6809   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6810     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6811                                        N0.getOperand(1), false);
6812     if (BSwap.getNode())
6813       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6814                          BSwap, N1);
6815   }
6816
6817   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6818   // into a build_vector.
6819   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6820     SmallVector<SDValue, 8> Elts;
6821     unsigned NumElts = N0->getNumOperands();
6822     unsigned ShAmt = VTBits - EVTBits;
6823
6824     for (unsigned i = 0; i != NumElts; ++i) {
6825       SDValue Op = N0->getOperand(i);
6826       if (Op->getOpcode() == ISD::UNDEF) {
6827         Elts.push_back(Op);
6828         continue;
6829       }
6830
6831       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6832       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6833       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6834                                      SDLoc(Op), Op.getValueType()));
6835     }
6836
6837     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6838   }
6839
6840   return SDValue();
6841 }
6842
6843 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6844   SDValue N0 = N->getOperand(0);
6845   EVT VT = N->getValueType(0);
6846
6847   if (N0.getOpcode() == ISD::UNDEF)
6848     return DAG.getUNDEF(VT);
6849
6850   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6851                                               LegalOperations))
6852     return SDValue(Res, 0);
6853
6854   return SDValue();
6855 }
6856
6857 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6858   SDValue N0 = N->getOperand(0);
6859   EVT VT = N->getValueType(0);
6860   bool isLE = DAG.getDataLayout().isLittleEndian();
6861
6862   // noop truncate
6863   if (N0.getValueType() == N->getValueType(0))
6864     return N0;
6865   // fold (truncate c1) -> c1
6866   if (isConstantIntBuildVectorOrConstantInt(N0))
6867     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6868   // fold (truncate (truncate x)) -> (truncate x)
6869   if (N0.getOpcode() == ISD::TRUNCATE)
6870     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6871   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6872   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6873       N0.getOpcode() == ISD::SIGN_EXTEND ||
6874       N0.getOpcode() == ISD::ANY_EXTEND) {
6875     if (N0.getOperand(0).getValueType().bitsLT(VT))
6876       // if the source is smaller than the dest, we still need an extend
6877       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6878                          N0.getOperand(0));
6879     if (N0.getOperand(0).getValueType().bitsGT(VT))
6880       // if the source is larger than the dest, than we just need the truncate
6881       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6882     // if the source and dest are the same type, we can drop both the extend
6883     // and the truncate.
6884     return N0.getOperand(0);
6885   }
6886
6887   // Fold extract-and-trunc into a narrow extract. For example:
6888   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6889   //   i32 y = TRUNCATE(i64 x)
6890   //        -- becomes --
6891   //   v16i8 b = BITCAST (v2i64 val)
6892   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6893   //
6894   // Note: We only run this optimization after type legalization (which often
6895   // creates this pattern) and before operation legalization after which
6896   // we need to be more careful about the vector instructions that we generate.
6897   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6898       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6899
6900     EVT VecTy = N0.getOperand(0).getValueType();
6901     EVT ExTy = N0.getValueType();
6902     EVT TrTy = N->getValueType(0);
6903
6904     unsigned NumElem = VecTy.getVectorNumElements();
6905     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6906
6907     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6908     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6909
6910     SDValue EltNo = N0->getOperand(1);
6911     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6912       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6913       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
6914       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6915
6916       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6917                               NVT, N0.getOperand(0));
6918
6919       SDLoc DL(N);
6920       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6921                          DL, TrTy, V,
6922                          DAG.getConstant(Index, DL, IndexTy));
6923     }
6924   }
6925
6926   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6927   if (N0.getOpcode() == ISD::SELECT) {
6928     EVT SrcVT = N0.getValueType();
6929     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6930         TLI.isTruncateFree(SrcVT, VT)) {
6931       SDLoc SL(N0);
6932       SDValue Cond = N0.getOperand(0);
6933       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6934       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6935       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6936     }
6937   }
6938
6939   // Fold a series of buildvector, bitcast, and truncate if possible.
6940   // For example fold
6941   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6942   //   (2xi32 (buildvector x, y)).
6943   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6944       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6945       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6946       N0.getOperand(0).hasOneUse()) {
6947
6948     SDValue BuildVect = N0.getOperand(0);
6949     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6950     EVT TruncVecEltTy = VT.getVectorElementType();
6951
6952     // Check that the element types match.
6953     if (BuildVectEltTy == TruncVecEltTy) {
6954       // Now we only need to compute the offset of the truncated elements.
6955       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6956       unsigned TruncVecNumElts = VT.getVectorNumElements();
6957       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6958
6959       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6960              "Invalid number of elements");
6961
6962       SmallVector<SDValue, 8> Opnds;
6963       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6964         Opnds.push_back(BuildVect.getOperand(i));
6965
6966       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6967     }
6968   }
6969
6970   // See if we can simplify the input to this truncate through knowledge that
6971   // only the low bits are being used.
6972   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6973   // Currently we only perform this optimization on scalars because vectors
6974   // may have different active low bits.
6975   if (!VT.isVector()) {
6976     SDValue Shorter =
6977       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6978                                                VT.getSizeInBits()));
6979     if (Shorter.getNode())
6980       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6981   }
6982   // fold (truncate (load x)) -> (smaller load x)
6983   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6984   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6985     if (SDValue Reduced = ReduceLoadWidth(N))
6986       return Reduced;
6987
6988     // Handle the case where the load remains an extending load even
6989     // after truncation.
6990     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6991       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6992       if (!LN0->isVolatile() &&
6993           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6994         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6995                                          VT, LN0->getChain(), LN0->getBasePtr(),
6996                                          LN0->getMemoryVT(),
6997                                          LN0->getMemOperand());
6998         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6999         return NewLoad;
7000       }
7001     }
7002   }
7003   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7004   // where ... are all 'undef'.
7005   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7006     SmallVector<EVT, 8> VTs;
7007     SDValue V;
7008     unsigned Idx = 0;
7009     unsigned NumDefs = 0;
7010
7011     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7012       SDValue X = N0.getOperand(i);
7013       if (X.getOpcode() != ISD::UNDEF) {
7014         V = X;
7015         Idx = i;
7016         NumDefs++;
7017       }
7018       // Stop if more than one members are non-undef.
7019       if (NumDefs > 1)
7020         break;
7021       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7022                                      VT.getVectorElementType(),
7023                                      X.getValueType().getVectorNumElements()));
7024     }
7025
7026     if (NumDefs == 0)
7027       return DAG.getUNDEF(VT);
7028
7029     if (NumDefs == 1) {
7030       assert(V.getNode() && "The single defined operand is empty!");
7031       SmallVector<SDValue, 8> Opnds;
7032       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7033         if (i != Idx) {
7034           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7035           continue;
7036         }
7037         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7038         AddToWorklist(NV.getNode());
7039         Opnds.push_back(NV);
7040       }
7041       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7042     }
7043   }
7044
7045   // Simplify the operands using demanded-bits information.
7046   if (!VT.isVector() &&
7047       SimplifyDemandedBits(SDValue(N, 0)))
7048     return SDValue(N, 0);
7049
7050   return SDValue();
7051 }
7052
7053 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7054   SDValue Elt = N->getOperand(i);
7055   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7056     return Elt.getNode();
7057   return Elt.getOperand(Elt.getResNo()).getNode();
7058 }
7059
7060 /// build_pair (load, load) -> load
7061 /// if load locations are consecutive.
7062 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7063   assert(N->getOpcode() == ISD::BUILD_PAIR);
7064
7065   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7066   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7067   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7068       LD1->getAddressSpace() != LD2->getAddressSpace())
7069     return SDValue();
7070   EVT LD1VT = LD1->getValueType(0);
7071
7072   if (ISD::isNON_EXTLoad(LD2) &&
7073       LD2->hasOneUse() &&
7074       // If both are volatile this would reduce the number of volatile loads.
7075       // If one is volatile it might be ok, but play conservative and bail out.
7076       !LD1->isVolatile() &&
7077       !LD2->isVolatile() &&
7078       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7079     unsigned Align = LD1->getAlignment();
7080     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7081         VT.getTypeForEVT(*DAG.getContext()));
7082
7083     if (NewAlign <= Align &&
7084         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7085       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7086                          LD1->getBasePtr(), LD1->getPointerInfo(),
7087                          false, false, false, Align);
7088   }
7089
7090   return SDValue();
7091 }
7092
7093 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7094   SDValue N0 = N->getOperand(0);
7095   EVT VT = N->getValueType(0);
7096
7097   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7098   // Only do this before legalize, since afterward the target may be depending
7099   // on the bitconvert.
7100   // First check to see if this is all constant.
7101   if (!LegalTypes &&
7102       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7103       VT.isVector()) {
7104     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7105
7106     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7107     assert(!DestEltVT.isVector() &&
7108            "Element type of vector ValueType must not be vector!");
7109     if (isSimple)
7110       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7111   }
7112
7113   // If the input is a constant, let getNode fold it.
7114   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7115     // If we can't allow illegal operations, we need to check that this is just
7116     // a fp -> int or int -> conversion and that the resulting operation will
7117     // be legal.
7118     if (!LegalOperations ||
7119         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7120          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7121         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7122          TLI.isOperationLegal(ISD::Constant, VT)))
7123       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7124   }
7125
7126   // (conv (conv x, t1), t2) -> (conv x, t2)
7127   if (N0.getOpcode() == ISD::BITCAST)
7128     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7129                        N0.getOperand(0));
7130
7131   // fold (conv (load x)) -> (load (conv*)x)
7132   // If the resultant load doesn't need a higher alignment than the original!
7133   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7134       // Do not change the width of a volatile load.
7135       !cast<LoadSDNode>(N0)->isVolatile() &&
7136       // Do not remove the cast if the types differ in endian layout.
7137       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7138           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7139       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7140       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7141     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7142     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7143         VT.getTypeForEVT(*DAG.getContext()));
7144     unsigned OrigAlign = LN0->getAlignment();
7145
7146     if (Align <= OrigAlign) {
7147       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7148                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7149                                  LN0->isVolatile(), LN0->isNonTemporal(),
7150                                  LN0->isInvariant(), OrigAlign,
7151                                  LN0->getAAInfo());
7152       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7153       return Load;
7154     }
7155   }
7156
7157   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7158   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7159   // This often reduces constant pool loads.
7160   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7161        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7162       N0.getNode()->hasOneUse() && VT.isInteger() &&
7163       !VT.isVector() && !N0.getValueType().isVector()) {
7164     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7165                                   N0.getOperand(0));
7166     AddToWorklist(NewConv.getNode());
7167
7168     SDLoc DL(N);
7169     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7170     if (N0.getOpcode() == ISD::FNEG)
7171       return DAG.getNode(ISD::XOR, DL, VT,
7172                          NewConv, DAG.getConstant(SignBit, DL, VT));
7173     assert(N0.getOpcode() == ISD::FABS);
7174     return DAG.getNode(ISD::AND, DL, VT,
7175                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7176   }
7177
7178   // fold (bitconvert (fcopysign cst, x)) ->
7179   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7180   // Note that we don't handle (copysign x, cst) because this can always be
7181   // folded to an fneg or fabs.
7182   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7183       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7184       VT.isInteger() && !VT.isVector()) {
7185     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7186     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7187     if (isTypeLegal(IntXVT)) {
7188       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7189                               IntXVT, N0.getOperand(1));
7190       AddToWorklist(X.getNode());
7191
7192       // If X has a different width than the result/lhs, sext it or truncate it.
7193       unsigned VTWidth = VT.getSizeInBits();
7194       if (OrigXWidth < VTWidth) {
7195         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7196         AddToWorklist(X.getNode());
7197       } else if (OrigXWidth > VTWidth) {
7198         // To get the sign bit in the right place, we have to shift it right
7199         // before truncating.
7200         SDLoc DL(X);
7201         X = DAG.getNode(ISD::SRL, DL,
7202                         X.getValueType(), X,
7203                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7204                                         X.getValueType()));
7205         AddToWorklist(X.getNode());
7206         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7207         AddToWorklist(X.getNode());
7208       }
7209
7210       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7211       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7212                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7213       AddToWorklist(X.getNode());
7214
7215       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7216                                 VT, N0.getOperand(0));
7217       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7218                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7219       AddToWorklist(Cst.getNode());
7220
7221       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7222     }
7223   }
7224
7225   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7226   if (N0.getOpcode() == ISD::BUILD_PAIR)
7227     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7228       return CombineLD;
7229
7230   // Remove double bitcasts from shuffles - this is often a legacy of
7231   // XformToShuffleWithZero being used to combine bitmaskings (of
7232   // float vectors bitcast to integer vectors) into shuffles.
7233   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7234   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7235       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7236       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7237       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7238     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7239
7240     // If operands are a bitcast, peek through if it casts the original VT.
7241     // If operands are a constant, just bitcast back to original VT.
7242     auto PeekThroughBitcast = [&](SDValue Op) {
7243       if (Op.getOpcode() == ISD::BITCAST &&
7244           Op.getOperand(0).getValueType() == VT)
7245         return SDValue(Op.getOperand(0));
7246       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7247           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7248         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7249       return SDValue();
7250     };
7251
7252     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7253     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7254     if (!(SV0 && SV1))
7255       return SDValue();
7256
7257     int MaskScale =
7258         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7259     SmallVector<int, 8> NewMask;
7260     for (int M : SVN->getMask())
7261       for (int i = 0; i != MaskScale; ++i)
7262         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7263
7264     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7265     if (!LegalMask) {
7266       std::swap(SV0, SV1);
7267       ShuffleVectorSDNode::commuteMask(NewMask);
7268       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7269     }
7270
7271     if (LegalMask)
7272       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7273   }
7274
7275   return SDValue();
7276 }
7277
7278 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7279   EVT VT = N->getValueType(0);
7280   return CombineConsecutiveLoads(N, VT);
7281 }
7282
7283 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7284 /// operands. DstEltVT indicates the destination element value type.
7285 SDValue DAGCombiner::
7286 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7287   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7288
7289   // If this is already the right type, we're done.
7290   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7291
7292   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7293   unsigned DstBitSize = DstEltVT.getSizeInBits();
7294
7295   // If this is a conversion of N elements of one type to N elements of another
7296   // type, convert each element.  This handles FP<->INT cases.
7297   if (SrcBitSize == DstBitSize) {
7298     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7299                               BV->getValueType(0).getVectorNumElements());
7300
7301     // Due to the FP element handling below calling this routine recursively,
7302     // we can end up with a scalar-to-vector node here.
7303     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7304       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7305                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7306                                      DstEltVT, BV->getOperand(0)));
7307
7308     SmallVector<SDValue, 8> Ops;
7309     for (SDValue Op : BV->op_values()) {
7310       // If the vector element type is not legal, the BUILD_VECTOR operands
7311       // are promoted and implicitly truncated.  Make that explicit here.
7312       if (Op.getValueType() != SrcEltVT)
7313         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7314       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7315                                 DstEltVT, Op));
7316       AddToWorklist(Ops.back().getNode());
7317     }
7318     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7319   }
7320
7321   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7322   // handle annoying details of growing/shrinking FP values, we convert them to
7323   // int first.
7324   if (SrcEltVT.isFloatingPoint()) {
7325     // Convert the input float vector to a int vector where the elements are the
7326     // same sizes.
7327     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7328     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7329     SrcEltVT = IntVT;
7330   }
7331
7332   // Now we know the input is an integer vector.  If the output is a FP type,
7333   // convert to integer first, then to FP of the right size.
7334   if (DstEltVT.isFloatingPoint()) {
7335     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7336     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7337
7338     // Next, convert to FP elements of the same size.
7339     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7340   }
7341
7342   SDLoc DL(BV);
7343
7344   // Okay, we know the src/dst types are both integers of differing types.
7345   // Handling growing first.
7346   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7347   if (SrcBitSize < DstBitSize) {
7348     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7349
7350     SmallVector<SDValue, 8> Ops;
7351     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7352          i += NumInputsPerOutput) {
7353       bool isLE = DAG.getDataLayout().isLittleEndian();
7354       APInt NewBits = APInt(DstBitSize, 0);
7355       bool EltIsUndef = true;
7356       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7357         // Shift the previously computed bits over.
7358         NewBits <<= SrcBitSize;
7359         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7360         if (Op.getOpcode() == ISD::UNDEF) continue;
7361         EltIsUndef = false;
7362
7363         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7364                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7365       }
7366
7367       if (EltIsUndef)
7368         Ops.push_back(DAG.getUNDEF(DstEltVT));
7369       else
7370         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7371     }
7372
7373     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7374     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7375   }
7376
7377   // Finally, this must be the case where we are shrinking elements: each input
7378   // turns into multiple outputs.
7379   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7380   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7381                             NumOutputsPerInput*BV->getNumOperands());
7382   SmallVector<SDValue, 8> Ops;
7383
7384   for (const SDValue &Op : BV->op_values()) {
7385     if (Op.getOpcode() == ISD::UNDEF) {
7386       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7387       continue;
7388     }
7389
7390     APInt OpVal = cast<ConstantSDNode>(Op)->
7391                   getAPIntValue().zextOrTrunc(SrcBitSize);
7392
7393     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7394       APInt ThisVal = OpVal.trunc(DstBitSize);
7395       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7396       OpVal = OpVal.lshr(DstBitSize);
7397     }
7398
7399     // For big endian targets, swap the order of the pieces of each element.
7400     if (DAG.getDataLayout().isBigEndian())
7401       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7402   }
7403
7404   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7405 }
7406
7407 /// Try to perform FMA combining on a given FADD node.
7408 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7409   SDValue N0 = N->getOperand(0);
7410   SDValue N1 = N->getOperand(1);
7411   EVT VT = N->getValueType(0);
7412   SDLoc SL(N);
7413
7414   const TargetOptions &Options = DAG.getTarget().Options;
7415   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7416                        Options.UnsafeFPMath);
7417
7418   // Floating-point multiply-add with intermediate rounding.
7419   bool HasFMAD = (LegalOperations &&
7420                   TLI.isOperationLegal(ISD::FMAD, VT));
7421
7422   // Floating-point multiply-add without intermediate rounding.
7423   bool HasFMA = ((!LegalOperations ||
7424                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7425                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7426                  UnsafeFPMath);
7427
7428   // No valid opcode, do not combine.
7429   if (!HasFMAD && !HasFMA)
7430     return SDValue();
7431
7432   // Always prefer FMAD to FMA for precision.
7433   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7434   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7435   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7436
7437   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7438   if (N0.getOpcode() == ISD::FMUL &&
7439       (Aggressive || N0->hasOneUse())) {
7440     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7441                        N0.getOperand(0), N0.getOperand(1), N1);
7442   }
7443
7444   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7445   // Note: Commutes FADD operands.
7446   if (N1.getOpcode() == ISD::FMUL &&
7447       (Aggressive || N1->hasOneUse())) {
7448     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7449                        N1.getOperand(0), N1.getOperand(1), N0);
7450   }
7451
7452   // Look through FP_EXTEND nodes to do more combining.
7453   if (UnsafeFPMath && LookThroughFPExt) {
7454     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7455     if (N0.getOpcode() == ISD::FP_EXTEND) {
7456       SDValue N00 = N0.getOperand(0);
7457       if (N00.getOpcode() == ISD::FMUL)
7458         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7459                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7460                                        N00.getOperand(0)),
7461                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7462                                        N00.getOperand(1)), N1);
7463     }
7464
7465     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7466     // Note: Commutes FADD operands.
7467     if (N1.getOpcode() == ISD::FP_EXTEND) {
7468       SDValue N10 = N1.getOperand(0);
7469       if (N10.getOpcode() == ISD::FMUL)
7470         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7472                                        N10.getOperand(0)),
7473                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7474                                        N10.getOperand(1)), N0);
7475     }
7476   }
7477
7478   // More folding opportunities when target permits.
7479   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7480     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7481     if (N0.getOpcode() == PreferredFusedOpcode &&
7482         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7483       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7484                          N0.getOperand(0), N0.getOperand(1),
7485                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7486                                      N0.getOperand(2).getOperand(0),
7487                                      N0.getOperand(2).getOperand(1),
7488                                      N1));
7489     }
7490
7491     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7492     if (N1->getOpcode() == PreferredFusedOpcode &&
7493         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7494       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7495                          N1.getOperand(0), N1.getOperand(1),
7496                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7497                                      N1.getOperand(2).getOperand(0),
7498                                      N1.getOperand(2).getOperand(1),
7499                                      N0));
7500     }
7501
7502     if (UnsafeFPMath && LookThroughFPExt) {
7503       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7504       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7505       auto FoldFAddFMAFPExtFMul = [&] (
7506           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7507         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7508                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7509                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7510                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7511                                        Z));
7512       };
7513       if (N0.getOpcode() == PreferredFusedOpcode) {
7514         SDValue N02 = N0.getOperand(2);
7515         if (N02.getOpcode() == ISD::FP_EXTEND) {
7516           SDValue N020 = N02.getOperand(0);
7517           if (N020.getOpcode() == ISD::FMUL)
7518             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7519                                         N020.getOperand(0), N020.getOperand(1),
7520                                         N1);
7521         }
7522       }
7523
7524       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7525       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7526       // FIXME: This turns two single-precision and one double-precision
7527       // operation into two double-precision operations, which might not be
7528       // interesting for all targets, especially GPUs.
7529       auto FoldFAddFPExtFMAFMul = [&] (
7530           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7531         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7532                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7533                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7534                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7535                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7536                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7537                                        Z));
7538       };
7539       if (N0.getOpcode() == ISD::FP_EXTEND) {
7540         SDValue N00 = N0.getOperand(0);
7541         if (N00.getOpcode() == PreferredFusedOpcode) {
7542           SDValue N002 = N00.getOperand(2);
7543           if (N002.getOpcode() == ISD::FMUL)
7544             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7545                                         N002.getOperand(0), N002.getOperand(1),
7546                                         N1);
7547         }
7548       }
7549
7550       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7551       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7552       if (N1.getOpcode() == PreferredFusedOpcode) {
7553         SDValue N12 = N1.getOperand(2);
7554         if (N12.getOpcode() == ISD::FP_EXTEND) {
7555           SDValue N120 = N12.getOperand(0);
7556           if (N120.getOpcode() == ISD::FMUL)
7557             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7558                                         N120.getOperand(0), N120.getOperand(1),
7559                                         N0);
7560         }
7561       }
7562
7563       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7564       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7565       // FIXME: This turns two single-precision and one double-precision
7566       // operation into two double-precision operations, which might not be
7567       // interesting for all targets, especially GPUs.
7568       if (N1.getOpcode() == ISD::FP_EXTEND) {
7569         SDValue N10 = N1.getOperand(0);
7570         if (N10.getOpcode() == PreferredFusedOpcode) {
7571           SDValue N102 = N10.getOperand(2);
7572           if (N102.getOpcode() == ISD::FMUL)
7573             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7574                                         N102.getOperand(0), N102.getOperand(1),
7575                                         N0);
7576         }
7577       }
7578     }
7579   }
7580
7581   return SDValue();
7582 }
7583
7584 /// Try to perform FMA combining on a given FSUB node.
7585 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7586   SDValue N0 = N->getOperand(0);
7587   SDValue N1 = N->getOperand(1);
7588   EVT VT = N->getValueType(0);
7589   SDLoc SL(N);
7590
7591   const TargetOptions &Options = DAG.getTarget().Options;
7592   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7593                        Options.UnsafeFPMath);
7594
7595   // Floating-point multiply-add with intermediate rounding.
7596   bool HasFMAD = (LegalOperations &&
7597                   TLI.isOperationLegal(ISD::FMAD, VT));
7598
7599   // Floating-point multiply-add without intermediate rounding.
7600   bool HasFMA = ((!LegalOperations ||
7601                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7602                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7603                  UnsafeFPMath);
7604
7605   // No valid opcode, do not combine.
7606   if (!HasFMAD && !HasFMA)
7607     return SDValue();
7608
7609   // Always prefer FMAD to FMA for precision.
7610   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7611   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7612   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7613
7614   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7615   if (N0.getOpcode() == ISD::FMUL &&
7616       (Aggressive || N0->hasOneUse())) {
7617     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7618                        N0.getOperand(0), N0.getOperand(1),
7619                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7620   }
7621
7622   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7623   // Note: Commutes FSUB operands.
7624   if (N1.getOpcode() == ISD::FMUL &&
7625       (Aggressive || N1->hasOneUse()))
7626     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7627                        DAG.getNode(ISD::FNEG, SL, VT,
7628                                    N1.getOperand(0)),
7629                        N1.getOperand(1), N0);
7630
7631   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7632   if (N0.getOpcode() == ISD::FNEG &&
7633       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7634       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7635     SDValue N00 = N0.getOperand(0).getOperand(0);
7636     SDValue N01 = N0.getOperand(0).getOperand(1);
7637     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7639                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7640   }
7641
7642   // Look through FP_EXTEND nodes to do more combining.
7643   if (UnsafeFPMath && LookThroughFPExt) {
7644     // fold (fsub (fpext (fmul x, y)), z)
7645     //   -> (fma (fpext x), (fpext y), (fneg z))
7646     if (N0.getOpcode() == ISD::FP_EXTEND) {
7647       SDValue N00 = N0.getOperand(0);
7648       if (N00.getOpcode() == ISD::FMUL)
7649         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7650                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7651                                        N00.getOperand(0)),
7652                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7653                                        N00.getOperand(1)),
7654                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7655     }
7656
7657     // fold (fsub x, (fpext (fmul y, z)))
7658     //   -> (fma (fneg (fpext y)), (fpext z), x)
7659     // Note: Commutes FSUB operands.
7660     if (N1.getOpcode() == ISD::FP_EXTEND) {
7661       SDValue N10 = N1.getOperand(0);
7662       if (N10.getOpcode() == ISD::FMUL)
7663         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7664                            DAG.getNode(ISD::FNEG, SL, VT,
7665                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7666                                                    N10.getOperand(0))),
7667                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7668                                        N10.getOperand(1)),
7669                            N0);
7670     }
7671
7672     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7673     //   -> (fneg (fma (fpext x), (fpext y), z))
7674     // Note: This could be removed with appropriate canonicalization of the
7675     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7676     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7677     // from implementing the canonicalization in visitFSUB.
7678     if (N0.getOpcode() == ISD::FP_EXTEND) {
7679       SDValue N00 = N0.getOperand(0);
7680       if (N00.getOpcode() == ISD::FNEG) {
7681         SDValue N000 = N00.getOperand(0);
7682         if (N000.getOpcode() == ISD::FMUL) {
7683           return DAG.getNode(ISD::FNEG, SL, VT,
7684                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7685                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7686                                                      N000.getOperand(0)),
7687                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7688                                                      N000.getOperand(1)),
7689                                          N1));
7690         }
7691       }
7692     }
7693
7694     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7695     //   -> (fneg (fma (fpext x)), (fpext y), z)
7696     // Note: This could be removed with appropriate canonicalization of the
7697     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7698     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7699     // from implementing the canonicalization in visitFSUB.
7700     if (N0.getOpcode() == ISD::FNEG) {
7701       SDValue N00 = N0.getOperand(0);
7702       if (N00.getOpcode() == ISD::FP_EXTEND) {
7703         SDValue N000 = N00.getOperand(0);
7704         if (N000.getOpcode() == ISD::FMUL) {
7705           return DAG.getNode(ISD::FNEG, SL, VT,
7706                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7707                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7708                                                      N000.getOperand(0)),
7709                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7710                                                      N000.getOperand(1)),
7711                                          N1));
7712         }
7713       }
7714     }
7715
7716   }
7717
7718   // More folding opportunities when target permits.
7719   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7720     // fold (fsub (fma x, y, (fmul u, v)), z)
7721     //   -> (fma x, y (fma u, v, (fneg z)))
7722     if (N0.getOpcode() == PreferredFusedOpcode &&
7723         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7724       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7725                          N0.getOperand(0), N0.getOperand(1),
7726                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7727                                      N0.getOperand(2).getOperand(0),
7728                                      N0.getOperand(2).getOperand(1),
7729                                      DAG.getNode(ISD::FNEG, SL, VT,
7730                                                  N1)));
7731     }
7732
7733     // fold (fsub x, (fma y, z, (fmul u, v)))
7734     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7735     if (N1.getOpcode() == PreferredFusedOpcode &&
7736         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7737       SDValue N20 = N1.getOperand(2).getOperand(0);
7738       SDValue N21 = N1.getOperand(2).getOperand(1);
7739       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7740                          DAG.getNode(ISD::FNEG, SL, VT,
7741                                      N1.getOperand(0)),
7742                          N1.getOperand(1),
7743                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7744                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7745
7746                                      N21, N0));
7747     }
7748
7749     if (UnsafeFPMath && LookThroughFPExt) {
7750       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7751       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7752       if (N0.getOpcode() == PreferredFusedOpcode) {
7753         SDValue N02 = N0.getOperand(2);
7754         if (N02.getOpcode() == ISD::FP_EXTEND) {
7755           SDValue N020 = N02.getOperand(0);
7756           if (N020.getOpcode() == ISD::FMUL)
7757             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7758                                N0.getOperand(0), N0.getOperand(1),
7759                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7760                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7761                                                        N020.getOperand(0)),
7762                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763                                                        N020.getOperand(1)),
7764                                            DAG.getNode(ISD::FNEG, SL, VT,
7765                                                        N1)));
7766         }
7767       }
7768
7769       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7770       //   -> (fma (fpext x), (fpext y),
7771       //           (fma (fpext u), (fpext v), (fneg z)))
7772       // FIXME: This turns two single-precision and one double-precision
7773       // operation into two double-precision operations, which might not be
7774       // interesting for all targets, especially GPUs.
7775       if (N0.getOpcode() == ISD::FP_EXTEND) {
7776         SDValue N00 = N0.getOperand(0);
7777         if (N00.getOpcode() == PreferredFusedOpcode) {
7778           SDValue N002 = N00.getOperand(2);
7779           if (N002.getOpcode() == ISD::FMUL)
7780             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7781                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782                                            N00.getOperand(0)),
7783                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7784                                            N00.getOperand(1)),
7785                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7786                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7787                                                        N002.getOperand(0)),
7788                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7789                                                        N002.getOperand(1)),
7790                                            DAG.getNode(ISD::FNEG, SL, VT,
7791                                                        N1)));
7792         }
7793       }
7794
7795       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7796       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7797       if (N1.getOpcode() == PreferredFusedOpcode &&
7798         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7799         SDValue N120 = N1.getOperand(2).getOperand(0);
7800         if (N120.getOpcode() == ISD::FMUL) {
7801           SDValue N1200 = N120.getOperand(0);
7802           SDValue N1201 = N120.getOperand(1);
7803           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7804                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7805                              N1.getOperand(1),
7806                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7807                                          DAG.getNode(ISD::FNEG, SL, VT,
7808                                              DAG.getNode(ISD::FP_EXTEND, SL,
7809                                                          VT, N1200)),
7810                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7811                                                      N1201),
7812                                          N0));
7813         }
7814       }
7815
7816       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7817       //   -> (fma (fneg (fpext y)), (fpext z),
7818       //           (fma (fneg (fpext u)), (fpext v), x))
7819       // FIXME: This turns two single-precision and one double-precision
7820       // operation into two double-precision operations, which might not be
7821       // interesting for all targets, especially GPUs.
7822       if (N1.getOpcode() == ISD::FP_EXTEND &&
7823         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7824         SDValue N100 = N1.getOperand(0).getOperand(0);
7825         SDValue N101 = N1.getOperand(0).getOperand(1);
7826         SDValue N102 = N1.getOperand(0).getOperand(2);
7827         if (N102.getOpcode() == ISD::FMUL) {
7828           SDValue N1020 = N102.getOperand(0);
7829           SDValue N1021 = N102.getOperand(1);
7830           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7831                              DAG.getNode(ISD::FNEG, SL, VT,
7832                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7833                                                      N100)),
7834                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7835                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7836                                          DAG.getNode(ISD::FNEG, SL, VT,
7837                                              DAG.getNode(ISD::FP_EXTEND, SL,
7838                                                          VT, N1020)),
7839                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7840                                                      N1021),
7841                                          N0));
7842         }
7843       }
7844     }
7845   }
7846
7847   return SDValue();
7848 }
7849
7850 SDValue DAGCombiner::visitFADD(SDNode *N) {
7851   SDValue N0 = N->getOperand(0);
7852   SDValue N1 = N->getOperand(1);
7853   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7854   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7855   EVT VT = N->getValueType(0);
7856   SDLoc DL(N);
7857   const TargetOptions &Options = DAG.getTarget().Options;
7858
7859   // fold vector ops
7860   if (VT.isVector())
7861     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7862       return FoldedVOp;
7863
7864   // fold (fadd c1, c2) -> c1 + c2
7865   if (N0CFP && N1CFP)
7866     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7867
7868   // canonicalize constant to RHS
7869   if (N0CFP && !N1CFP)
7870     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7871
7872   // fold (fadd A, (fneg B)) -> (fsub A, B)
7873   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7874       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7875     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7876                        GetNegatedExpression(N1, DAG, LegalOperations));
7877
7878   // fold (fadd (fneg A), B) -> (fsub B, A)
7879   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7880       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7881     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7882                        GetNegatedExpression(N0, DAG, LegalOperations));
7883
7884   // If 'unsafe math' is enabled, fold lots of things.
7885   if (Options.UnsafeFPMath) {
7886     // No FP constant should be created after legalization as Instruction
7887     // Selection pass has a hard time dealing with FP constants.
7888     bool AllowNewConst = (Level < AfterLegalizeDAG);
7889
7890     // fold (fadd A, 0) -> A
7891     if (N1CFP && N1CFP->isZero())
7892       return N0;
7893
7894     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7895     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7896         isa<ConstantFPSDNode>(N0.getOperand(1)))
7897       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7898                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7899
7900     // If allowed, fold (fadd (fneg x), x) -> 0.0
7901     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7902       return DAG.getConstantFP(0.0, DL, VT);
7903
7904     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7905     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7906       return DAG.getConstantFP(0.0, DL, VT);
7907
7908     // We can fold chains of FADD's of the same value into multiplications.
7909     // This transform is not safe in general because we are reducing the number
7910     // of rounding steps.
7911     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7912       if (N0.getOpcode() == ISD::FMUL) {
7913         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7914         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7915
7916         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7917         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7918           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7919                                        DAG.getConstantFP(1.0, DL, VT));
7920           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7921         }
7922
7923         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7924         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7925             N1.getOperand(0) == N1.getOperand(1) &&
7926             N0.getOperand(0) == N1.getOperand(0)) {
7927           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7928                                        DAG.getConstantFP(2.0, DL, VT));
7929           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7930         }
7931       }
7932
7933       if (N1.getOpcode() == ISD::FMUL) {
7934         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7935         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7936
7937         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7938         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7939           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7940                                        DAG.getConstantFP(1.0, DL, VT));
7941           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7942         }
7943
7944         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7945         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7946             N0.getOperand(0) == N0.getOperand(1) &&
7947             N1.getOperand(0) == N0.getOperand(0)) {
7948           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7949                                        DAG.getConstantFP(2.0, DL, VT));
7950           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7951         }
7952       }
7953
7954       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7955         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7956         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7957         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7958             (N0.getOperand(0) == N1)) {
7959           return DAG.getNode(ISD::FMUL, DL, VT,
7960                              N1, DAG.getConstantFP(3.0, DL, VT));
7961         }
7962       }
7963
7964       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7965         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7966         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7967         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7968             N1.getOperand(0) == N0) {
7969           return DAG.getNode(ISD::FMUL, DL, VT,
7970                              N0, DAG.getConstantFP(3.0, DL, VT));
7971         }
7972       }
7973
7974       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7975       if (AllowNewConst &&
7976           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7977           N0.getOperand(0) == N0.getOperand(1) &&
7978           N1.getOperand(0) == N1.getOperand(1) &&
7979           N0.getOperand(0) == N1.getOperand(0)) {
7980         return DAG.getNode(ISD::FMUL, DL, VT,
7981                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7982       }
7983     }
7984   } // enable-unsafe-fp-math
7985
7986   // FADD -> FMA combines:
7987   SDValue Fused = visitFADDForFMACombine(N);
7988   if (Fused) {
7989     AddToWorklist(Fused.getNode());
7990     return Fused;
7991   }
7992
7993   return SDValue();
7994 }
7995
7996 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7997   SDValue N0 = N->getOperand(0);
7998   SDValue N1 = N->getOperand(1);
7999   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8000   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8001   EVT VT = N->getValueType(0);
8002   SDLoc dl(N);
8003   const TargetOptions &Options = DAG.getTarget().Options;
8004
8005   // fold vector ops
8006   if (VT.isVector())
8007     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8008       return FoldedVOp;
8009
8010   // fold (fsub c1, c2) -> c1-c2
8011   if (N0CFP && N1CFP)
8012     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8013
8014   // fold (fsub A, (fneg B)) -> (fadd A, B)
8015   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8016     return DAG.getNode(ISD::FADD, dl, VT, N0,
8017                        GetNegatedExpression(N1, DAG, LegalOperations));
8018
8019   // If 'unsafe math' is enabled, fold lots of things.
8020   if (Options.UnsafeFPMath) {
8021     // (fsub A, 0) -> A
8022     if (N1CFP && N1CFP->isZero())
8023       return N0;
8024
8025     // (fsub 0, B) -> -B
8026     if (N0CFP && N0CFP->isZero()) {
8027       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8028         return GetNegatedExpression(N1, DAG, LegalOperations);
8029       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8030         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8031     }
8032
8033     // (fsub x, x) -> 0.0
8034     if (N0 == N1)
8035       return DAG.getConstantFP(0.0f, dl, VT);
8036
8037     // (fsub x, (fadd x, y)) -> (fneg y)
8038     // (fsub x, (fadd y, x)) -> (fneg y)
8039     if (N1.getOpcode() == ISD::FADD) {
8040       SDValue N10 = N1->getOperand(0);
8041       SDValue N11 = N1->getOperand(1);
8042
8043       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8044         return GetNegatedExpression(N11, DAG, LegalOperations);
8045
8046       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8047         return GetNegatedExpression(N10, DAG, LegalOperations);
8048     }
8049   }
8050
8051   // FSUB -> FMA combines:
8052   SDValue Fused = visitFSUBForFMACombine(N);
8053   if (Fused) {
8054     AddToWorklist(Fused.getNode());
8055     return Fused;
8056   }
8057
8058   return SDValue();
8059 }
8060
8061 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8062   SDValue N0 = N->getOperand(0);
8063   SDValue N1 = N->getOperand(1);
8064   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8065   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8066   EVT VT = N->getValueType(0);
8067   SDLoc DL(N);
8068   const TargetOptions &Options = DAG.getTarget().Options;
8069
8070   // fold vector ops
8071   if (VT.isVector()) {
8072     // This just handles C1 * C2 for vectors. Other vector folds are below.
8073     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8074       return FoldedVOp;
8075   }
8076
8077   // fold (fmul c1, c2) -> c1*c2
8078   if (N0CFP && N1CFP)
8079     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8080
8081   // canonicalize constant to RHS
8082   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8083      !isConstantFPBuildVectorOrConstantFP(N1))
8084     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8085
8086   // fold (fmul A, 1.0) -> A
8087   if (N1CFP && N1CFP->isExactlyValue(1.0))
8088     return N0;
8089
8090   if (Options.UnsafeFPMath) {
8091     // fold (fmul A, 0) -> 0
8092     if (N1CFP && N1CFP->isZero())
8093       return N1;
8094
8095     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8096     if (N0.getOpcode() == ISD::FMUL) {
8097       // Fold scalars or any vector constants (not just splats).
8098       // This fold is done in general by InstCombine, but extra fmul insts
8099       // may have been generated during lowering.
8100       SDValue N00 = N0.getOperand(0);
8101       SDValue N01 = N0.getOperand(1);
8102       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8103       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8104       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8105
8106       // Check 1: Make sure that the first operand of the inner multiply is NOT
8107       // a constant. Otherwise, we may induce infinite looping.
8108       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8109         // Check 2: Make sure that the second operand of the inner multiply and
8110         // the second operand of the outer multiply are constants.
8111         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8112             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8113           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8114           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8115         }
8116       }
8117     }
8118
8119     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8120     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8121     // during an early run of DAGCombiner can prevent folding with fmuls
8122     // inserted during lowering.
8123     if (N0.getOpcode() == ISD::FADD &&
8124         (N0.getOperand(0) == N0.getOperand(1)) &&
8125         N0.hasOneUse()) {
8126       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8127       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8128       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8129     }
8130   }
8131
8132   // fold (fmul X, 2.0) -> (fadd X, X)
8133   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8134     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8135
8136   // fold (fmul X, -1.0) -> (fneg X)
8137   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8138     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8139       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8140
8141   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8142   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8143     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8144       // Both can be negated for free, check to see if at least one is cheaper
8145       // negated.
8146       if (LHSNeg == 2 || RHSNeg == 2)
8147         return DAG.getNode(ISD::FMUL, DL, VT,
8148                            GetNegatedExpression(N0, DAG, LegalOperations),
8149                            GetNegatedExpression(N1, DAG, LegalOperations));
8150     }
8151   }
8152
8153   return SDValue();
8154 }
8155
8156 SDValue DAGCombiner::visitFMA(SDNode *N) {
8157   SDValue N0 = N->getOperand(0);
8158   SDValue N1 = N->getOperand(1);
8159   SDValue N2 = N->getOperand(2);
8160   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8161   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8162   EVT VT = N->getValueType(0);
8163   SDLoc dl(N);
8164   const TargetOptions &Options = DAG.getTarget().Options;
8165
8166   // Constant fold FMA.
8167   if (isa<ConstantFPSDNode>(N0) &&
8168       isa<ConstantFPSDNode>(N1) &&
8169       isa<ConstantFPSDNode>(N2)) {
8170     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8171   }
8172
8173   if (Options.UnsafeFPMath) {
8174     if (N0CFP && N0CFP->isZero())
8175       return N2;
8176     if (N1CFP && N1CFP->isZero())
8177       return N2;
8178   }
8179   if (N0CFP && N0CFP->isExactlyValue(1.0))
8180     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8181   if (N1CFP && N1CFP->isExactlyValue(1.0))
8182     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8183
8184   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8185   if (N0CFP && !N1CFP)
8186     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8187
8188   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8189   if (Options.UnsafeFPMath && N1CFP &&
8190       N2.getOpcode() == ISD::FMUL &&
8191       N0 == N2.getOperand(0) &&
8192       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8193     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8194                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8195   }
8196
8197
8198   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8199   if (Options.UnsafeFPMath &&
8200       N0.getOpcode() == ISD::FMUL && N1CFP &&
8201       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8202     return DAG.getNode(ISD::FMA, dl, VT,
8203                        N0.getOperand(0),
8204                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8205                        N2);
8206   }
8207
8208   // (fma x, 1, y) -> (fadd x, y)
8209   // (fma x, -1, y) -> (fadd (fneg x), y)
8210   if (N1CFP) {
8211     if (N1CFP->isExactlyValue(1.0))
8212       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8213
8214     if (N1CFP->isExactlyValue(-1.0) &&
8215         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8216       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8217       AddToWorklist(RHSNeg.getNode());
8218       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8219     }
8220   }
8221
8222   // (fma x, c, x) -> (fmul x, (c+1))
8223   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8224     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8225                        DAG.getNode(ISD::FADD, dl, VT,
8226                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8227
8228   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8229   if (Options.UnsafeFPMath && N1CFP &&
8230       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8231     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8232                        DAG.getNode(ISD::FADD, dl, VT,
8233                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8234
8235
8236   return SDValue();
8237 }
8238
8239 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8240 // reciprocal.
8241 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8242 // Notice that this is not always beneficial. One reason is different target
8243 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8244 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8245 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8246 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8247   if (!DAG.getTarget().Options.UnsafeFPMath)
8248     return SDValue();
8249   
8250   // Skip if current node is a reciprocal.
8251   SDValue N0 = N->getOperand(0);
8252   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8253   if (N0CFP && N0CFP->isExactlyValue(1.0))
8254     return SDValue();
8255   
8256   // Exit early if the target does not want this transform or if there can't
8257   // possibly be enough uses of the divisor to make the transform worthwhile.
8258   SDValue N1 = N->getOperand(1);
8259   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8260   if (!MinUses || N1->use_size() < MinUses)
8261     return SDValue();
8262
8263   // Find all FDIV users of the same divisor.
8264   // Use a set because duplicates may be present in the user list.
8265   SetVector<SDNode *> Users;
8266   for (auto *U : N1->uses())
8267     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8268       Users.insert(U);
8269
8270   // Now that we have the actual number of divisor uses, make sure it meets
8271   // the minimum threshold specified by the target.
8272   if (Users.size() < MinUses)
8273     return SDValue();
8274
8275   EVT VT = N->getValueType(0);
8276   SDLoc DL(N);
8277   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8278   // FIXME: This optimization requires some level of fast-math, so the
8279   // created reciprocal node should at least have the 'allowReciprocal'
8280   // fast-math-flag set.
8281   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8282
8283   // Dividend / Divisor -> Dividend * Reciprocal
8284   for (auto *U : Users) {
8285     SDValue Dividend = U->getOperand(0);
8286     if (Dividend != FPOne) {
8287       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8288                                     Reciprocal);
8289       CombineTo(U, NewNode);
8290     } else if (U != Reciprocal.getNode()) {
8291       // In the absence of fast-math-flags, this user node is always the
8292       // same node as Reciprocal, but with FMF they may be different nodes.
8293       CombineTo(U, Reciprocal);
8294     }
8295   }
8296   return SDValue(N, 0);  // N was replaced.
8297 }
8298
8299 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8300   SDValue N0 = N->getOperand(0);
8301   SDValue N1 = N->getOperand(1);
8302   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8303   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8304   EVT VT = N->getValueType(0);
8305   SDLoc DL(N);
8306   const TargetOptions &Options = DAG.getTarget().Options;
8307
8308   // fold vector ops
8309   if (VT.isVector())
8310     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8311       return FoldedVOp;
8312
8313   // fold (fdiv c1, c2) -> c1/c2
8314   if (N0CFP && N1CFP)
8315     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8316
8317   if (Options.UnsafeFPMath) {
8318     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8319     if (N1CFP) {
8320       // Compute the reciprocal 1.0 / c2.
8321       APFloat N1APF = N1CFP->getValueAPF();
8322       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8323       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8324       // Only do the transform if the reciprocal is a legal fp immediate that
8325       // isn't too nasty (eg NaN, denormal, ...).
8326       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8327           (!LegalOperations ||
8328            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8329            // backend)... we should handle this gracefully after Legalize.
8330            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8331            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8332            TLI.isFPImmLegal(Recip, VT)))
8333         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8334                            DAG.getConstantFP(Recip, DL, VT));
8335     }
8336
8337     // If this FDIV is part of a reciprocal square root, it may be folded
8338     // into a target-specific square root estimate instruction.
8339     if (N1.getOpcode() == ISD::FSQRT) {
8340       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8341         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8342       }
8343     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8344                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8345       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8346         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8347         AddToWorklist(RV.getNode());
8348         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8349       }
8350     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8351                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8352       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8353         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8354         AddToWorklist(RV.getNode());
8355         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8356       }
8357     } else if (N1.getOpcode() == ISD::FMUL) {
8358       // Look through an FMUL. Even though this won't remove the FDIV directly,
8359       // it's still worthwhile to get rid of the FSQRT if possible.
8360       SDValue SqrtOp;
8361       SDValue OtherOp;
8362       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8363         SqrtOp = N1.getOperand(0);
8364         OtherOp = N1.getOperand(1);
8365       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8366         SqrtOp = N1.getOperand(1);
8367         OtherOp = N1.getOperand(0);
8368       }
8369       if (SqrtOp.getNode()) {
8370         // We found a FSQRT, so try to make this fold:
8371         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8372         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8373           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8374           AddToWorklist(RV.getNode());
8375           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8376         }
8377       }
8378     }
8379
8380     // Fold into a reciprocal estimate and multiply instead of a real divide.
8381     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8382       AddToWorklist(RV.getNode());
8383       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8384     }
8385   }
8386
8387   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8388   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8389     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8390       // Both can be negated for free, check to see if at least one is cheaper
8391       // negated.
8392       if (LHSNeg == 2 || RHSNeg == 2)
8393         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8394                            GetNegatedExpression(N0, DAG, LegalOperations),
8395                            GetNegatedExpression(N1, DAG, LegalOperations));
8396     }
8397   }
8398
8399   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8400     return CombineRepeatedDivisors;
8401
8402   return SDValue();
8403 }
8404
8405 SDValue DAGCombiner::visitFREM(SDNode *N) {
8406   SDValue N0 = N->getOperand(0);
8407   SDValue N1 = N->getOperand(1);
8408   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8409   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8410   EVT VT = N->getValueType(0);
8411
8412   // fold (frem c1, c2) -> fmod(c1,c2)
8413   if (N0CFP && N1CFP)
8414     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8415
8416   return SDValue();
8417 }
8418
8419 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8420   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8421     return SDValue();
8422
8423   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8424   SDValue RV = BuildRsqrtEstimate(N->getOperand(0));
8425   if (!RV)
8426     return SDValue();
8427   
8428   EVT VT = RV.getValueType();
8429   SDLoc DL(N);
8430   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8431   AddToWorklist(RV.getNode());
8432
8433   // Unfortunately, RV is now NaN if the input was exactly 0.
8434   // Select out this case and force the answer to 0.
8435   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8436   EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8437   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8438   AddToWorklist(ZeroCmp.getNode());
8439   AddToWorklist(RV.getNode());
8440
8441   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8442                      ZeroCmp, Zero, RV);
8443 }
8444
8445 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8446   SDValue N0 = N->getOperand(0);
8447   SDValue N1 = N->getOperand(1);
8448   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8449   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8450   EVT VT = N->getValueType(0);
8451
8452   if (N0CFP && N1CFP)  // Constant fold
8453     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8454
8455   if (N1CFP) {
8456     const APFloat& V = N1CFP->getValueAPF();
8457     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8458     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8459     if (!V.isNegative()) {
8460       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8461         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8462     } else {
8463       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8464         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8465                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8466     }
8467   }
8468
8469   // copysign(fabs(x), y) -> copysign(x, y)
8470   // copysign(fneg(x), y) -> copysign(x, y)
8471   // copysign(copysign(x,z), y) -> copysign(x, y)
8472   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8473       N0.getOpcode() == ISD::FCOPYSIGN)
8474     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8475                        N0.getOperand(0), N1);
8476
8477   // copysign(x, abs(y)) -> abs(x)
8478   if (N1.getOpcode() == ISD::FABS)
8479     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8480
8481   // copysign(x, copysign(y,z)) -> copysign(x, z)
8482   if (N1.getOpcode() == ISD::FCOPYSIGN)
8483     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8484                        N0, N1.getOperand(1));
8485
8486   // copysign(x, fp_extend(y)) -> copysign(x, y)
8487   // copysign(x, fp_round(y)) -> copysign(x, y)
8488   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8489     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8490                        N0, N1.getOperand(0));
8491
8492   return SDValue();
8493 }
8494
8495 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8496   SDValue N0 = N->getOperand(0);
8497   EVT VT = N->getValueType(0);
8498   EVT OpVT = N0.getValueType();
8499
8500   // fold (sint_to_fp c1) -> c1fp
8501   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8502       // ...but only if the target supports immediate floating-point values
8503       (!LegalOperations ||
8504        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8505     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8506
8507   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8508   // but UINT_TO_FP is legal on this target, try to convert.
8509   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8510       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8511     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8512     if (DAG.SignBitIsZero(N0))
8513       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8514   }
8515
8516   // The next optimizations are desirable only if SELECT_CC can be lowered.
8517   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8518     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8519     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8520         !VT.isVector() &&
8521         (!LegalOperations ||
8522          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8523       SDLoc DL(N);
8524       SDValue Ops[] =
8525         { N0.getOperand(0), N0.getOperand(1),
8526           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8527           N0.getOperand(2) };
8528       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8529     }
8530
8531     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8532     //      (select_cc x, y, 1.0, 0.0,, cc)
8533     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8534         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8535         (!LegalOperations ||
8536          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8537       SDLoc DL(N);
8538       SDValue Ops[] =
8539         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8540           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8541           N0.getOperand(0).getOperand(2) };
8542       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8543     }
8544   }
8545
8546   return SDValue();
8547 }
8548
8549 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8550   SDValue N0 = N->getOperand(0);
8551   EVT VT = N->getValueType(0);
8552   EVT OpVT = N0.getValueType();
8553
8554   // fold (uint_to_fp c1) -> c1fp
8555   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8556       // ...but only if the target supports immediate floating-point values
8557       (!LegalOperations ||
8558        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8559     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8560
8561   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8562   // but SINT_TO_FP is legal on this target, try to convert.
8563   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8564       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8565     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8566     if (DAG.SignBitIsZero(N0))
8567       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8568   }
8569
8570   // The next optimizations are desirable only if SELECT_CC can be lowered.
8571   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8572     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8573
8574     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8575         (!LegalOperations ||
8576          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8577       SDLoc DL(N);
8578       SDValue Ops[] =
8579         { N0.getOperand(0), N0.getOperand(1),
8580           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8581           N0.getOperand(2) };
8582       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8583     }
8584   }
8585
8586   return SDValue();
8587 }
8588
8589 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8590 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8591   SDValue N0 = N->getOperand(0);
8592   EVT VT = N->getValueType(0);
8593
8594   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8595     return SDValue();
8596
8597   SDValue Src = N0.getOperand(0);
8598   EVT SrcVT = Src.getValueType();
8599   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8600   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8601
8602   // We can safely assume the conversion won't overflow the output range,
8603   // because (for example) (uint8_t)18293.f is undefined behavior.
8604
8605   // Since we can assume the conversion won't overflow, our decision as to
8606   // whether the input will fit in the float should depend on the minimum
8607   // of the input range and output range.
8608
8609   // This means this is also safe for a signed input and unsigned output, since
8610   // a negative input would lead to undefined behavior.
8611   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8612   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8613   unsigned ActualSize = std::min(InputSize, OutputSize);
8614   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8615
8616   // We can only fold away the float conversion if the input range can be
8617   // represented exactly in the float range.
8618   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8619     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8620       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8621                                                        : ISD::ZERO_EXTEND;
8622       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8623     }
8624     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8625       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8626     if (SrcVT == VT)
8627       return Src;
8628     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8629   }
8630   return SDValue();
8631 }
8632
8633 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8634   SDValue N0 = N->getOperand(0);
8635   EVT VT = N->getValueType(0);
8636
8637   // fold (fp_to_sint c1fp) -> c1
8638   if (isConstantFPBuildVectorOrConstantFP(N0))
8639     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8640
8641   return FoldIntToFPToInt(N, DAG);
8642 }
8643
8644 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8645   SDValue N0 = N->getOperand(0);
8646   EVT VT = N->getValueType(0);
8647
8648   // fold (fp_to_uint c1fp) -> c1
8649   if (isConstantFPBuildVectorOrConstantFP(N0))
8650     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8651
8652   return FoldIntToFPToInt(N, DAG);
8653 }
8654
8655 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8656   SDValue N0 = N->getOperand(0);
8657   SDValue N1 = N->getOperand(1);
8658   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8659   EVT VT = N->getValueType(0);
8660
8661   // fold (fp_round c1fp) -> c1fp
8662   if (N0CFP)
8663     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8664
8665   // fold (fp_round (fp_extend x)) -> x
8666   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8667     return N0.getOperand(0);
8668
8669   // fold (fp_round (fp_round x)) -> (fp_round x)
8670   if (N0.getOpcode() == ISD::FP_ROUND) {
8671     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8672     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8673     // If the first fp_round isn't a value preserving truncation, it might
8674     // introduce a tie in the second fp_round, that wouldn't occur in the
8675     // single-step fp_round we want to fold to.
8676     // In other words, double rounding isn't the same as rounding.
8677     // Also, this is a value preserving truncation iff both fp_round's are.
8678     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8679       SDLoc DL(N);
8680       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8681                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8682     }
8683   }
8684
8685   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8686   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8687     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8688                               N0.getOperand(0), N1);
8689     AddToWorklist(Tmp.getNode());
8690     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8691                        Tmp, N0.getOperand(1));
8692   }
8693
8694   return SDValue();
8695 }
8696
8697 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8698   SDValue N0 = N->getOperand(0);
8699   EVT VT = N->getValueType(0);
8700   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8701   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8702
8703   // fold (fp_round_inreg c1fp) -> c1fp
8704   if (N0CFP && isTypeLegal(EVT)) {
8705     SDLoc DL(N);
8706     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8707     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8708   }
8709
8710   return SDValue();
8711 }
8712
8713 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8714   SDValue N0 = N->getOperand(0);
8715   EVT VT = N->getValueType(0);
8716
8717   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8718   if (N->hasOneUse() &&
8719       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8720     return SDValue();
8721
8722   // fold (fp_extend c1fp) -> c1fp
8723   if (isConstantFPBuildVectorOrConstantFP(N0))
8724     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8725
8726   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8727   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8728       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8729     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8730
8731   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8732   // value of X.
8733   if (N0.getOpcode() == ISD::FP_ROUND
8734       && N0.getNode()->getConstantOperandVal(1) == 1) {
8735     SDValue In = N0.getOperand(0);
8736     if (In.getValueType() == VT) return In;
8737     if (VT.bitsLT(In.getValueType()))
8738       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8739                          In, N0.getOperand(1));
8740     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8741   }
8742
8743   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8744   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8745        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8746     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8747     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8748                                      LN0->getChain(),
8749                                      LN0->getBasePtr(), N0.getValueType(),
8750                                      LN0->getMemOperand());
8751     CombineTo(N, ExtLoad);
8752     CombineTo(N0.getNode(),
8753               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8754                           N0.getValueType(), ExtLoad,
8755                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8756               ExtLoad.getValue(1));
8757     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8758   }
8759
8760   return SDValue();
8761 }
8762
8763 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8764   SDValue N0 = N->getOperand(0);
8765   EVT VT = N->getValueType(0);
8766
8767   // fold (fceil c1) -> fceil(c1)
8768   if (isConstantFPBuildVectorOrConstantFP(N0))
8769     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8770
8771   return SDValue();
8772 }
8773
8774 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8775   SDValue N0 = N->getOperand(0);
8776   EVT VT = N->getValueType(0);
8777
8778   // fold (ftrunc c1) -> ftrunc(c1)
8779   if (isConstantFPBuildVectorOrConstantFP(N0))
8780     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8781
8782   return SDValue();
8783 }
8784
8785 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8786   SDValue N0 = N->getOperand(0);
8787   EVT VT = N->getValueType(0);
8788
8789   // fold (ffloor c1) -> ffloor(c1)
8790   if (isConstantFPBuildVectorOrConstantFP(N0))
8791     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8792
8793   return SDValue();
8794 }
8795
8796 // FIXME: FNEG and FABS have a lot in common; refactor.
8797 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8798   SDValue N0 = N->getOperand(0);
8799   EVT VT = N->getValueType(0);
8800
8801   // Constant fold FNEG.
8802   if (isConstantFPBuildVectorOrConstantFP(N0))
8803     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8804
8805   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8806                          &DAG.getTarget().Options))
8807     return GetNegatedExpression(N0, DAG, LegalOperations);
8808
8809   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8810   // constant pool values.
8811   if (!TLI.isFNegFree(VT) &&
8812       N0.getOpcode() == ISD::BITCAST &&
8813       N0.getNode()->hasOneUse()) {
8814     SDValue Int = N0.getOperand(0);
8815     EVT IntVT = Int.getValueType();
8816     if (IntVT.isInteger() && !IntVT.isVector()) {
8817       APInt SignMask;
8818       if (N0.getValueType().isVector()) {
8819         // For a vector, get a mask such as 0x80... per scalar element
8820         // and splat it.
8821         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8822         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8823       } else {
8824         // For a scalar, just generate 0x80...
8825         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8826       }
8827       SDLoc DL0(N0);
8828       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8829                         DAG.getConstant(SignMask, DL0, IntVT));
8830       AddToWorklist(Int.getNode());
8831       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8832     }
8833   }
8834
8835   // (fneg (fmul c, x)) -> (fmul -c, x)
8836   if (N0.getOpcode() == ISD::FMUL &&
8837       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8838     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8839     if (CFP1) {
8840       APFloat CVal = CFP1->getValueAPF();
8841       CVal.changeSign();
8842       if (Level >= AfterLegalizeDAG &&
8843           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8844            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8845         return DAG.getNode(
8846             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8847             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8848     }
8849   }
8850
8851   return SDValue();
8852 }
8853
8854 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8855   SDValue N0 = N->getOperand(0);
8856   SDValue N1 = N->getOperand(1);
8857   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8858   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8859
8860   if (N0CFP && N1CFP) {
8861     const APFloat &C0 = N0CFP->getValueAPF();
8862     const APFloat &C1 = N1CFP->getValueAPF();
8863     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8864   }
8865
8866   if (N0CFP) {
8867     EVT VT = N->getValueType(0);
8868     // Canonicalize to constant on RHS.
8869     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8870   }
8871
8872   return SDValue();
8873 }
8874
8875 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8876   SDValue N0 = N->getOperand(0);
8877   SDValue N1 = N->getOperand(1);
8878   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8879   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8880
8881   if (N0CFP && N1CFP) {
8882     const APFloat &C0 = N0CFP->getValueAPF();
8883     const APFloat &C1 = N1CFP->getValueAPF();
8884     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8885   }
8886
8887   if (N0CFP) {
8888     EVT VT = N->getValueType(0);
8889     // Canonicalize to constant on RHS.
8890     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8891   }
8892
8893   return SDValue();
8894 }
8895
8896 SDValue DAGCombiner::visitFABS(SDNode *N) {
8897   SDValue N0 = N->getOperand(0);
8898   EVT VT = N->getValueType(0);
8899
8900   // fold (fabs c1) -> fabs(c1)
8901   if (isConstantFPBuildVectorOrConstantFP(N0))
8902     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8903
8904   // fold (fabs (fabs x)) -> (fabs x)
8905   if (N0.getOpcode() == ISD::FABS)
8906     return N->getOperand(0);
8907
8908   // fold (fabs (fneg x)) -> (fabs x)
8909   // fold (fabs (fcopysign x, y)) -> (fabs x)
8910   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8911     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8912
8913   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8914   // constant pool values.
8915   if (!TLI.isFAbsFree(VT) &&
8916       N0.getOpcode() == ISD::BITCAST &&
8917       N0.getNode()->hasOneUse()) {
8918     SDValue Int = N0.getOperand(0);
8919     EVT IntVT = Int.getValueType();
8920     if (IntVT.isInteger() && !IntVT.isVector()) {
8921       APInt SignMask;
8922       if (N0.getValueType().isVector()) {
8923         // For a vector, get a mask such as 0x7f... per scalar element
8924         // and splat it.
8925         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8926         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8927       } else {
8928         // For a scalar, just generate 0x7f...
8929         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8930       }
8931       SDLoc DL(N0);
8932       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8933                         DAG.getConstant(SignMask, DL, IntVT));
8934       AddToWorklist(Int.getNode());
8935       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8936     }
8937   }
8938
8939   return SDValue();
8940 }
8941
8942 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8943   SDValue Chain = N->getOperand(0);
8944   SDValue N1 = N->getOperand(1);
8945   SDValue N2 = N->getOperand(2);
8946
8947   // If N is a constant we could fold this into a fallthrough or unconditional
8948   // branch. However that doesn't happen very often in normal code, because
8949   // Instcombine/SimplifyCFG should have handled the available opportunities.
8950   // If we did this folding here, it would be necessary to update the
8951   // MachineBasicBlock CFG, which is awkward.
8952
8953   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8954   // on the target.
8955   if (N1.getOpcode() == ISD::SETCC &&
8956       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8957                                    N1.getOperand(0).getValueType())) {
8958     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8959                        Chain, N1.getOperand(2),
8960                        N1.getOperand(0), N1.getOperand(1), N2);
8961   }
8962
8963   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8964       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8965        (N1.getOperand(0).hasOneUse() &&
8966         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8967     SDNode *Trunc = nullptr;
8968     if (N1.getOpcode() == ISD::TRUNCATE) {
8969       // Look pass the truncate.
8970       Trunc = N1.getNode();
8971       N1 = N1.getOperand(0);
8972     }
8973
8974     // Match this pattern so that we can generate simpler code:
8975     //
8976     //   %a = ...
8977     //   %b = and i32 %a, 2
8978     //   %c = srl i32 %b, 1
8979     //   brcond i32 %c ...
8980     //
8981     // into
8982     //
8983     //   %a = ...
8984     //   %b = and i32 %a, 2
8985     //   %c = setcc eq %b, 0
8986     //   brcond %c ...
8987     //
8988     // This applies only when the AND constant value has one bit set and the
8989     // SRL constant is equal to the log2 of the AND constant. The back-end is
8990     // smart enough to convert the result into a TEST/JMP sequence.
8991     SDValue Op0 = N1.getOperand(0);
8992     SDValue Op1 = N1.getOperand(1);
8993
8994     if (Op0.getOpcode() == ISD::AND &&
8995         Op1.getOpcode() == ISD::Constant) {
8996       SDValue AndOp1 = Op0.getOperand(1);
8997
8998       if (AndOp1.getOpcode() == ISD::Constant) {
8999         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9000
9001         if (AndConst.isPowerOf2() &&
9002             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9003           SDLoc DL(N);
9004           SDValue SetCC =
9005             DAG.getSetCC(DL,
9006                          getSetCCResultType(Op0.getValueType()),
9007                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9008                          ISD::SETNE);
9009
9010           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9011                                           MVT::Other, Chain, SetCC, N2);
9012           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9013           // will convert it back to (X & C1) >> C2.
9014           CombineTo(N, NewBRCond, false);
9015           // Truncate is dead.
9016           if (Trunc)
9017             deleteAndRecombine(Trunc);
9018           // Replace the uses of SRL with SETCC
9019           WorklistRemover DeadNodes(*this);
9020           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9021           deleteAndRecombine(N1.getNode());
9022           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9023         }
9024       }
9025     }
9026
9027     if (Trunc)
9028       // Restore N1 if the above transformation doesn't match.
9029       N1 = N->getOperand(1);
9030   }
9031
9032   // Transform br(xor(x, y)) -> br(x != y)
9033   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9034   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9035     SDNode *TheXor = N1.getNode();
9036     SDValue Op0 = TheXor->getOperand(0);
9037     SDValue Op1 = TheXor->getOperand(1);
9038     if (Op0.getOpcode() == Op1.getOpcode()) {
9039       // Avoid missing important xor optimizations.
9040       SDValue Tmp = visitXOR(TheXor);
9041       if (Tmp.getNode()) {
9042         if (Tmp.getNode() != TheXor) {
9043           DEBUG(dbgs() << "\nReplacing.8 ";
9044                 TheXor->dump(&DAG);
9045                 dbgs() << "\nWith: ";
9046                 Tmp.getNode()->dump(&DAG);
9047                 dbgs() << '\n');
9048           WorklistRemover DeadNodes(*this);
9049           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9050           deleteAndRecombine(TheXor);
9051           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9052                              MVT::Other, Chain, Tmp, N2);
9053         }
9054
9055         // visitXOR has changed XOR's operands or replaced the XOR completely,
9056         // bail out.
9057         return SDValue(N, 0);
9058       }
9059     }
9060
9061     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9062       bool Equal = false;
9063       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9064           Op0.getOpcode() == ISD::XOR) {
9065         TheXor = Op0.getNode();
9066         Equal = true;
9067       }
9068
9069       EVT SetCCVT = N1.getValueType();
9070       if (LegalTypes)
9071         SetCCVT = getSetCCResultType(SetCCVT);
9072       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9073                                    SetCCVT,
9074                                    Op0, Op1,
9075                                    Equal ? ISD::SETEQ : ISD::SETNE);
9076       // Replace the uses of XOR with SETCC
9077       WorklistRemover DeadNodes(*this);
9078       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9079       deleteAndRecombine(N1.getNode());
9080       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9081                          MVT::Other, Chain, SetCC, N2);
9082     }
9083   }
9084
9085   return SDValue();
9086 }
9087
9088 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9089 //
9090 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9091   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9092   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9093
9094   // If N is a constant we could fold this into a fallthrough or unconditional
9095   // branch. However that doesn't happen very often in normal code, because
9096   // Instcombine/SimplifyCFG should have handled the available opportunities.
9097   // If we did this folding here, it would be necessary to update the
9098   // MachineBasicBlock CFG, which is awkward.
9099
9100   // Use SimplifySetCC to simplify SETCC's.
9101   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9102                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9103                                false);
9104   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9105
9106   // fold to a simpler setcc
9107   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9108     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9109                        N->getOperand(0), Simp.getOperand(2),
9110                        Simp.getOperand(0), Simp.getOperand(1),
9111                        N->getOperand(4));
9112
9113   return SDValue();
9114 }
9115
9116 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9117 /// and that N may be folded in the load / store addressing mode.
9118 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9119                                     SelectionDAG &DAG,
9120                                     const TargetLowering &TLI) {
9121   EVT VT;
9122   unsigned AS;
9123
9124   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9125     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9126       return false;
9127     VT = LD->getMemoryVT();
9128     AS = LD->getAddressSpace();
9129   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9130     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9131       return false;
9132     VT = ST->getMemoryVT();
9133     AS = ST->getAddressSpace();
9134   } else
9135     return false;
9136
9137   TargetLowering::AddrMode AM;
9138   if (N->getOpcode() == ISD::ADD) {
9139     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9140     if (Offset)
9141       // [reg +/- imm]
9142       AM.BaseOffs = Offset->getSExtValue();
9143     else
9144       // [reg +/- reg]
9145       AM.Scale = 1;
9146   } else if (N->getOpcode() == ISD::SUB) {
9147     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9148     if (Offset)
9149       // [reg +/- imm]
9150       AM.BaseOffs = -Offset->getSExtValue();
9151     else
9152       // [reg +/- reg]
9153       AM.Scale = 1;
9154   } else
9155     return false;
9156
9157   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9158                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9159 }
9160
9161 /// Try turning a load/store into a pre-indexed load/store when the base
9162 /// pointer is an add or subtract and it has other uses besides the load/store.
9163 /// After the transformation, the new indexed load/store has effectively folded
9164 /// the add/subtract in and all of its other uses are redirected to the
9165 /// new load/store.
9166 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9167   if (Level < AfterLegalizeDAG)
9168     return false;
9169
9170   bool isLoad = true;
9171   SDValue Ptr;
9172   EVT VT;
9173   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9174     if (LD->isIndexed())
9175       return false;
9176     VT = LD->getMemoryVT();
9177     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9178         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9179       return false;
9180     Ptr = LD->getBasePtr();
9181   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9182     if (ST->isIndexed())
9183       return false;
9184     VT = ST->getMemoryVT();
9185     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9186         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9187       return false;
9188     Ptr = ST->getBasePtr();
9189     isLoad = false;
9190   } else {
9191     return false;
9192   }
9193
9194   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9195   // out.  There is no reason to make this a preinc/predec.
9196   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9197       Ptr.getNode()->hasOneUse())
9198     return false;
9199
9200   // Ask the target to do addressing mode selection.
9201   SDValue BasePtr;
9202   SDValue Offset;
9203   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9204   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9205     return false;
9206
9207   // Backends without true r+i pre-indexed forms may need to pass a
9208   // constant base with a variable offset so that constant coercion
9209   // will work with the patterns in canonical form.
9210   bool Swapped = false;
9211   if (isa<ConstantSDNode>(BasePtr)) {
9212     std::swap(BasePtr, Offset);
9213     Swapped = true;
9214   }
9215
9216   // Don't create a indexed load / store with zero offset.
9217   if (isNullConstant(Offset))
9218     return false;
9219
9220   // Try turning it into a pre-indexed load / store except when:
9221   // 1) The new base ptr is a frame index.
9222   // 2) If N is a store and the new base ptr is either the same as or is a
9223   //    predecessor of the value being stored.
9224   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9225   //    that would create a cycle.
9226   // 4) All uses are load / store ops that use it as old base ptr.
9227
9228   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9229   // (plus the implicit offset) to a register to preinc anyway.
9230   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9231     return false;
9232
9233   // Check #2.
9234   if (!isLoad) {
9235     SDValue Val = cast<StoreSDNode>(N)->getValue();
9236     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9237       return false;
9238   }
9239
9240   // If the offset is a constant, there may be other adds of constants that
9241   // can be folded with this one. We should do this to avoid having to keep
9242   // a copy of the original base pointer.
9243   SmallVector<SDNode *, 16> OtherUses;
9244   if (isa<ConstantSDNode>(Offset))
9245     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9246                               UE = BasePtr.getNode()->use_end();
9247          UI != UE; ++UI) {
9248       SDUse &Use = UI.getUse();
9249       // Skip the use that is Ptr and uses of other results from BasePtr's
9250       // node (important for nodes that return multiple results).
9251       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9252         continue;
9253
9254       if (Use.getUser()->isPredecessorOf(N))
9255         continue;
9256
9257       if (Use.getUser()->getOpcode() != ISD::ADD &&
9258           Use.getUser()->getOpcode() != ISD::SUB) {
9259         OtherUses.clear();
9260         break;
9261       }
9262
9263       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9264       if (!isa<ConstantSDNode>(Op1)) {
9265         OtherUses.clear();
9266         break;
9267       }
9268
9269       // FIXME: In some cases, we can be smarter about this.
9270       if (Op1.getValueType() != Offset.getValueType()) {
9271         OtherUses.clear();
9272         break;
9273       }
9274
9275       OtherUses.push_back(Use.getUser());
9276     }
9277
9278   if (Swapped)
9279     std::swap(BasePtr, Offset);
9280
9281   // Now check for #3 and #4.
9282   bool RealUse = false;
9283
9284   // Caches for hasPredecessorHelper
9285   SmallPtrSet<const SDNode *, 32> Visited;
9286   SmallVector<const SDNode *, 16> Worklist;
9287
9288   for (SDNode *Use : Ptr.getNode()->uses()) {
9289     if (Use == N)
9290       continue;
9291     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9292       return false;
9293
9294     // If Ptr may be folded in addressing mode of other use, then it's
9295     // not profitable to do this transformation.
9296     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9297       RealUse = true;
9298   }
9299
9300   if (!RealUse)
9301     return false;
9302
9303   SDValue Result;
9304   if (isLoad)
9305     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9306                                 BasePtr, Offset, AM);
9307   else
9308     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9309                                  BasePtr, Offset, AM);
9310   ++PreIndexedNodes;
9311   ++NodesCombined;
9312   DEBUG(dbgs() << "\nReplacing.4 ";
9313         N->dump(&DAG);
9314         dbgs() << "\nWith: ";
9315         Result.getNode()->dump(&DAG);
9316         dbgs() << '\n');
9317   WorklistRemover DeadNodes(*this);
9318   if (isLoad) {
9319     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9320     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9321   } else {
9322     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9323   }
9324
9325   // Finally, since the node is now dead, remove it from the graph.
9326   deleteAndRecombine(N);
9327
9328   if (Swapped)
9329     std::swap(BasePtr, Offset);
9330
9331   // Replace other uses of BasePtr that can be updated to use Ptr
9332   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9333     unsigned OffsetIdx = 1;
9334     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9335       OffsetIdx = 0;
9336     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9337            BasePtr.getNode() && "Expected BasePtr operand");
9338
9339     // We need to replace ptr0 in the following expression:
9340     //   x0 * offset0 + y0 * ptr0 = t0
9341     // knowing that
9342     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9343     //
9344     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9345     // indexed load/store and the expresion that needs to be re-written.
9346     //
9347     // Therefore, we have:
9348     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9349
9350     ConstantSDNode *CN =
9351       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9352     int X0, X1, Y0, Y1;
9353     APInt Offset0 = CN->getAPIntValue();
9354     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9355
9356     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9357     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9358     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9359     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9360
9361     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9362
9363     APInt CNV = Offset0;
9364     if (X0 < 0) CNV = -CNV;
9365     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9366     else CNV = CNV - Offset1;
9367
9368     SDLoc DL(OtherUses[i]);
9369
9370     // We can now generate the new expression.
9371     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9372     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9373
9374     SDValue NewUse = DAG.getNode(Opcode,
9375                                  DL,
9376                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9377     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9378     deleteAndRecombine(OtherUses[i]);
9379   }
9380
9381   // Replace the uses of Ptr with uses of the updated base value.
9382   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9383   deleteAndRecombine(Ptr.getNode());
9384
9385   return true;
9386 }
9387
9388 /// Try to combine a load/store with a add/sub of the base pointer node into a
9389 /// post-indexed load/store. The transformation folded the add/subtract into the
9390 /// new indexed load/store effectively and all of its uses are redirected to the
9391 /// new load/store.
9392 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9393   if (Level < AfterLegalizeDAG)
9394     return false;
9395
9396   bool isLoad = true;
9397   SDValue Ptr;
9398   EVT VT;
9399   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9400     if (LD->isIndexed())
9401       return false;
9402     VT = LD->getMemoryVT();
9403     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9404         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9405       return false;
9406     Ptr = LD->getBasePtr();
9407   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9408     if (ST->isIndexed())
9409       return false;
9410     VT = ST->getMemoryVT();
9411     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9412         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9413       return false;
9414     Ptr = ST->getBasePtr();
9415     isLoad = false;
9416   } else {
9417     return false;
9418   }
9419
9420   if (Ptr.getNode()->hasOneUse())
9421     return false;
9422
9423   for (SDNode *Op : Ptr.getNode()->uses()) {
9424     if (Op == N ||
9425         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9426       continue;
9427
9428     SDValue BasePtr;
9429     SDValue Offset;
9430     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9431     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9432       // Don't create a indexed load / store with zero offset.
9433       if (isNullConstant(Offset))
9434         continue;
9435
9436       // Try turning it into a post-indexed load / store except when
9437       // 1) All uses are load / store ops that use it as base ptr (and
9438       //    it may be folded as addressing mmode).
9439       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9440       //    nor a successor of N. Otherwise, if Op is folded that would
9441       //    create a cycle.
9442
9443       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9444         continue;
9445
9446       // Check for #1.
9447       bool TryNext = false;
9448       for (SDNode *Use : BasePtr.getNode()->uses()) {
9449         if (Use == Ptr.getNode())
9450           continue;
9451
9452         // If all the uses are load / store addresses, then don't do the
9453         // transformation.
9454         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9455           bool RealUse = false;
9456           for (SDNode *UseUse : Use->uses()) {
9457             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9458               RealUse = true;
9459           }
9460
9461           if (!RealUse) {
9462             TryNext = true;
9463             break;
9464           }
9465         }
9466       }
9467
9468       if (TryNext)
9469         continue;
9470
9471       // Check for #2
9472       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9473         SDValue Result = isLoad
9474           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9475                                BasePtr, Offset, AM)
9476           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9477                                 BasePtr, Offset, AM);
9478         ++PostIndexedNodes;
9479         ++NodesCombined;
9480         DEBUG(dbgs() << "\nReplacing.5 ";
9481               N->dump(&DAG);
9482               dbgs() << "\nWith: ";
9483               Result.getNode()->dump(&DAG);
9484               dbgs() << '\n');
9485         WorklistRemover DeadNodes(*this);
9486         if (isLoad) {
9487           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9488           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9489         } else {
9490           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9491         }
9492
9493         // Finally, since the node is now dead, remove it from the graph.
9494         deleteAndRecombine(N);
9495
9496         // Replace the uses of Use with uses of the updated base value.
9497         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9498                                       Result.getValue(isLoad ? 1 : 0));
9499         deleteAndRecombine(Op);
9500         return true;
9501       }
9502     }
9503   }
9504
9505   return false;
9506 }
9507
9508 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9509 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9510   ISD::MemIndexedMode AM = LD->getAddressingMode();
9511   assert(AM != ISD::UNINDEXED);
9512   SDValue BP = LD->getOperand(1);
9513   SDValue Inc = LD->getOperand(2);
9514
9515   // Some backends use TargetConstants for load offsets, but don't expect
9516   // TargetConstants in general ADD nodes. We can convert these constants into
9517   // regular Constants (if the constant is not opaque).
9518   assert((Inc.getOpcode() != ISD::TargetConstant ||
9519           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9520          "Cannot split out indexing using opaque target constants");
9521   if (Inc.getOpcode() == ISD::TargetConstant) {
9522     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9523     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9524                           ConstInc->getValueType(0));
9525   }
9526
9527   unsigned Opc =
9528       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9529   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9530 }
9531
9532 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9533   LoadSDNode *LD  = cast<LoadSDNode>(N);
9534   SDValue Chain = LD->getChain();
9535   SDValue Ptr   = LD->getBasePtr();
9536
9537   // If load is not volatile and there are no uses of the loaded value (and
9538   // the updated indexed value in case of indexed loads), change uses of the
9539   // chain value into uses of the chain input (i.e. delete the dead load).
9540   if (!LD->isVolatile()) {
9541     if (N->getValueType(1) == MVT::Other) {
9542       // Unindexed loads.
9543       if (!N->hasAnyUseOfValue(0)) {
9544         // It's not safe to use the two value CombineTo variant here. e.g.
9545         // v1, chain2 = load chain1, loc
9546         // v2, chain3 = load chain2, loc
9547         // v3         = add v2, c
9548         // Now we replace use of chain2 with chain1.  This makes the second load
9549         // isomorphic to the one we are deleting, and thus makes this load live.
9550         DEBUG(dbgs() << "\nReplacing.6 ";
9551               N->dump(&DAG);
9552               dbgs() << "\nWith chain: ";
9553               Chain.getNode()->dump(&DAG);
9554               dbgs() << "\n");
9555         WorklistRemover DeadNodes(*this);
9556         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9557
9558         if (N->use_empty())
9559           deleteAndRecombine(N);
9560
9561         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9562       }
9563     } else {
9564       // Indexed loads.
9565       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9566
9567       // If this load has an opaque TargetConstant offset, then we cannot split
9568       // the indexing into an add/sub directly (that TargetConstant may not be
9569       // valid for a different type of node, and we cannot convert an opaque
9570       // target constant into a regular constant).
9571       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9572                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9573
9574       if (!N->hasAnyUseOfValue(0) &&
9575           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9576         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9577         SDValue Index;
9578         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9579           Index = SplitIndexingFromLoad(LD);
9580           // Try to fold the base pointer arithmetic into subsequent loads and
9581           // stores.
9582           AddUsersToWorklist(N);
9583         } else
9584           Index = DAG.getUNDEF(N->getValueType(1));
9585         DEBUG(dbgs() << "\nReplacing.7 ";
9586               N->dump(&DAG);
9587               dbgs() << "\nWith: ";
9588               Undef.getNode()->dump(&DAG);
9589               dbgs() << " and 2 other values\n");
9590         WorklistRemover DeadNodes(*this);
9591         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9592         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9593         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9594         deleteAndRecombine(N);
9595         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9596       }
9597     }
9598   }
9599
9600   // If this load is directly stored, replace the load value with the stored
9601   // value.
9602   // TODO: Handle store large -> read small portion.
9603   // TODO: Handle TRUNCSTORE/LOADEXT
9604   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9605     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9606       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9607       if (PrevST->getBasePtr() == Ptr &&
9608           PrevST->getValue().getValueType() == N->getValueType(0))
9609       return CombineTo(N, Chain.getOperand(1), Chain);
9610     }
9611   }
9612
9613   // Try to infer better alignment information than the load already has.
9614   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9615     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9616       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9617         SDValue NewLoad =
9618                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9619                               LD->getValueType(0),
9620                               Chain, Ptr, LD->getPointerInfo(),
9621                               LD->getMemoryVT(),
9622                               LD->isVolatile(), LD->isNonTemporal(),
9623                               LD->isInvariant(), Align, LD->getAAInfo());
9624         if (NewLoad.getNode() != N)
9625           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9626       }
9627     }
9628   }
9629
9630   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9631                                                   : DAG.getSubtarget().useAA();
9632 #ifndef NDEBUG
9633   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9634       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9635     UseAA = false;
9636 #endif
9637   if (UseAA && LD->isUnindexed()) {
9638     // Walk up chain skipping non-aliasing memory nodes.
9639     SDValue BetterChain = FindBetterChain(N, Chain);
9640
9641     // If there is a better chain.
9642     if (Chain != BetterChain) {
9643       SDValue ReplLoad;
9644
9645       // Replace the chain to void dependency.
9646       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9647         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9648                                BetterChain, Ptr, LD->getMemOperand());
9649       } else {
9650         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9651                                   LD->getValueType(0),
9652                                   BetterChain, Ptr, LD->getMemoryVT(),
9653                                   LD->getMemOperand());
9654       }
9655
9656       // Create token factor to keep old chain connected.
9657       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9658                                   MVT::Other, Chain, ReplLoad.getValue(1));
9659
9660       // Make sure the new and old chains are cleaned up.
9661       AddToWorklist(Token.getNode());
9662
9663       // Replace uses with load result and token factor. Don't add users
9664       // to work list.
9665       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9666     }
9667   }
9668
9669   // Try transforming N to an indexed load.
9670   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9671     return SDValue(N, 0);
9672
9673   // Try to slice up N to more direct loads if the slices are mapped to
9674   // different register banks or pairing can take place.
9675   if (SliceUpLoad(N))
9676     return SDValue(N, 0);
9677
9678   return SDValue();
9679 }
9680
9681 namespace {
9682 /// \brief Helper structure used to slice a load in smaller loads.
9683 /// Basically a slice is obtained from the following sequence:
9684 /// Origin = load Ty1, Base
9685 /// Shift = srl Ty1 Origin, CstTy Amount
9686 /// Inst = trunc Shift to Ty2
9687 ///
9688 /// Then, it will be rewriten into:
9689 /// Slice = load SliceTy, Base + SliceOffset
9690 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9691 ///
9692 /// SliceTy is deduced from the number of bits that are actually used to
9693 /// build Inst.
9694 struct LoadedSlice {
9695   /// \brief Helper structure used to compute the cost of a slice.
9696   struct Cost {
9697     /// Are we optimizing for code size.
9698     bool ForCodeSize;
9699     /// Various cost.
9700     unsigned Loads;
9701     unsigned Truncates;
9702     unsigned CrossRegisterBanksCopies;
9703     unsigned ZExts;
9704     unsigned Shift;
9705
9706     Cost(bool ForCodeSize = false)
9707         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9708           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9709
9710     /// \brief Get the cost of one isolated slice.
9711     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9712         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9713           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9714       EVT TruncType = LS.Inst->getValueType(0);
9715       EVT LoadedType = LS.getLoadedType();
9716       if (TruncType != LoadedType &&
9717           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9718         ZExts = 1;
9719     }
9720
9721     /// \brief Account for slicing gain in the current cost.
9722     /// Slicing provide a few gains like removing a shift or a
9723     /// truncate. This method allows to grow the cost of the original
9724     /// load with the gain from this slice.
9725     void addSliceGain(const LoadedSlice &LS) {
9726       // Each slice saves a truncate.
9727       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9728       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9729                               LS.Inst->getOperand(0).getValueType()))
9730         ++Truncates;
9731       // If there is a shift amount, this slice gets rid of it.
9732       if (LS.Shift)
9733         ++Shift;
9734       // If this slice can merge a cross register bank copy, account for it.
9735       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9736         ++CrossRegisterBanksCopies;
9737     }
9738
9739     Cost &operator+=(const Cost &RHS) {
9740       Loads += RHS.Loads;
9741       Truncates += RHS.Truncates;
9742       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9743       ZExts += RHS.ZExts;
9744       Shift += RHS.Shift;
9745       return *this;
9746     }
9747
9748     bool operator==(const Cost &RHS) const {
9749       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9750              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9751              ZExts == RHS.ZExts && Shift == RHS.Shift;
9752     }
9753
9754     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9755
9756     bool operator<(const Cost &RHS) const {
9757       // Assume cross register banks copies are as expensive as loads.
9758       // FIXME: Do we want some more target hooks?
9759       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9760       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9761       // Unless we are optimizing for code size, consider the
9762       // expensive operation first.
9763       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9764         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9765       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9766              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9767     }
9768
9769     bool operator>(const Cost &RHS) const { return RHS < *this; }
9770
9771     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9772
9773     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9774   };
9775   // The last instruction that represent the slice. This should be a
9776   // truncate instruction.
9777   SDNode *Inst;
9778   // The original load instruction.
9779   LoadSDNode *Origin;
9780   // The right shift amount in bits from the original load.
9781   unsigned Shift;
9782   // The DAG from which Origin came from.
9783   // This is used to get some contextual information about legal types, etc.
9784   SelectionDAG *DAG;
9785
9786   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9787               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9788       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9789
9790   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9791   /// \return Result is \p BitWidth and has used bits set to 1 and
9792   ///         not used bits set to 0.
9793   APInt getUsedBits() const {
9794     // Reproduce the trunc(lshr) sequence:
9795     // - Start from the truncated value.
9796     // - Zero extend to the desired bit width.
9797     // - Shift left.
9798     assert(Origin && "No original load to compare against.");
9799     unsigned BitWidth = Origin->getValueSizeInBits(0);
9800     assert(Inst && "This slice is not bound to an instruction");
9801     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9802            "Extracted slice is bigger than the whole type!");
9803     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9804     UsedBits.setAllBits();
9805     UsedBits = UsedBits.zext(BitWidth);
9806     UsedBits <<= Shift;
9807     return UsedBits;
9808   }
9809
9810   /// \brief Get the size of the slice to be loaded in bytes.
9811   unsigned getLoadedSize() const {
9812     unsigned SliceSize = getUsedBits().countPopulation();
9813     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9814     return SliceSize / 8;
9815   }
9816
9817   /// \brief Get the type that will be loaded for this slice.
9818   /// Note: This may not be the final type for the slice.
9819   EVT getLoadedType() const {
9820     assert(DAG && "Missing context");
9821     LLVMContext &Ctxt = *DAG->getContext();
9822     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9823   }
9824
9825   /// \brief Get the alignment of the load used for this slice.
9826   unsigned getAlignment() const {
9827     unsigned Alignment = Origin->getAlignment();
9828     unsigned Offset = getOffsetFromBase();
9829     if (Offset != 0)
9830       Alignment = MinAlign(Alignment, Alignment + Offset);
9831     return Alignment;
9832   }
9833
9834   /// \brief Check if this slice can be rewritten with legal operations.
9835   bool isLegal() const {
9836     // An invalid slice is not legal.
9837     if (!Origin || !Inst || !DAG)
9838       return false;
9839
9840     // Offsets are for indexed load only, we do not handle that.
9841     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9842       return false;
9843
9844     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9845
9846     // Check that the type is legal.
9847     EVT SliceType = getLoadedType();
9848     if (!TLI.isTypeLegal(SliceType))
9849       return false;
9850
9851     // Check that the load is legal for this type.
9852     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9853       return false;
9854
9855     // Check that the offset can be computed.
9856     // 1. Check its type.
9857     EVT PtrType = Origin->getBasePtr().getValueType();
9858     if (PtrType == MVT::Untyped || PtrType.isExtended())
9859       return false;
9860
9861     // 2. Check that it fits in the immediate.
9862     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9863       return false;
9864
9865     // 3. Check that the computation is legal.
9866     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9867       return false;
9868
9869     // Check that the zext is legal if it needs one.
9870     EVT TruncateType = Inst->getValueType(0);
9871     if (TruncateType != SliceType &&
9872         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9873       return false;
9874
9875     return true;
9876   }
9877
9878   /// \brief Get the offset in bytes of this slice in the original chunk of
9879   /// bits.
9880   /// \pre DAG != nullptr.
9881   uint64_t getOffsetFromBase() const {
9882     assert(DAG && "Missing context.");
9883     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
9884     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9885     uint64_t Offset = Shift / 8;
9886     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9887     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9888            "The size of the original loaded type is not a multiple of a"
9889            " byte.");
9890     // If Offset is bigger than TySizeInBytes, it means we are loading all
9891     // zeros. This should have been optimized before in the process.
9892     assert(TySizeInBytes > Offset &&
9893            "Invalid shift amount for given loaded size");
9894     if (IsBigEndian)
9895       Offset = TySizeInBytes - Offset - getLoadedSize();
9896     return Offset;
9897   }
9898
9899   /// \brief Generate the sequence of instructions to load the slice
9900   /// represented by this object and redirect the uses of this slice to
9901   /// this new sequence of instructions.
9902   /// \pre this->Inst && this->Origin are valid Instructions and this
9903   /// object passed the legal check: LoadedSlice::isLegal returned true.
9904   /// \return The last instruction of the sequence used to load the slice.
9905   SDValue loadSlice() const {
9906     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9907     const SDValue &OldBaseAddr = Origin->getBasePtr();
9908     SDValue BaseAddr = OldBaseAddr;
9909     // Get the offset in that chunk of bytes w.r.t. the endianess.
9910     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9911     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9912     if (Offset) {
9913       // BaseAddr = BaseAddr + Offset.
9914       EVT ArithType = BaseAddr.getValueType();
9915       SDLoc DL(Origin);
9916       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9917                               DAG->getConstant(Offset, DL, ArithType));
9918     }
9919
9920     // Create the type of the loaded slice according to its size.
9921     EVT SliceType = getLoadedType();
9922
9923     // Create the load for the slice.
9924     SDValue LastInst = DAG->getLoad(
9925         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9926         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9927         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9928     // If the final type is not the same as the loaded type, this means that
9929     // we have to pad with zero. Create a zero extend for that.
9930     EVT FinalType = Inst->getValueType(0);
9931     if (SliceType != FinalType)
9932       LastInst =
9933           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9934     return LastInst;
9935   }
9936
9937   /// \brief Check if this slice can be merged with an expensive cross register
9938   /// bank copy. E.g.,
9939   /// i = load i32
9940   /// f = bitcast i32 i to float
9941   bool canMergeExpensiveCrossRegisterBankCopy() const {
9942     if (!Inst || !Inst->hasOneUse())
9943       return false;
9944     SDNode *Use = *Inst->use_begin();
9945     if (Use->getOpcode() != ISD::BITCAST)
9946       return false;
9947     assert(DAG && "Missing context");
9948     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9949     EVT ResVT = Use->getValueType(0);
9950     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9951     const TargetRegisterClass *ArgRC =
9952         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9953     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9954       return false;
9955
9956     // At this point, we know that we perform a cross-register-bank copy.
9957     // Check if it is expensive.
9958     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9959     // Assume bitcasts are cheap, unless both register classes do not
9960     // explicitly share a common sub class.
9961     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9962       return false;
9963
9964     // Check if it will be merged with the load.
9965     // 1. Check the alignment constraint.
9966     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
9967         ResVT.getTypeForEVT(*DAG->getContext()));
9968
9969     if (RequiredAlignment > getAlignment())
9970       return false;
9971
9972     // 2. Check that the load is a legal operation for that type.
9973     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9974       return false;
9975
9976     // 3. Check that we do not have a zext in the way.
9977     if (Inst->getValueType(0) != getLoadedType())
9978       return false;
9979
9980     return true;
9981   }
9982 };
9983 }
9984
9985 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9986 /// \p UsedBits looks like 0..0 1..1 0..0.
9987 static bool areUsedBitsDense(const APInt &UsedBits) {
9988   // If all the bits are one, this is dense!
9989   if (UsedBits.isAllOnesValue())
9990     return true;
9991
9992   // Get rid of the unused bits on the right.
9993   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9994   // Get rid of the unused bits on the left.
9995   if (NarrowedUsedBits.countLeadingZeros())
9996     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9997   // Check that the chunk of bits is completely used.
9998   return NarrowedUsedBits.isAllOnesValue();
9999 }
10000
10001 /// \brief Check whether or not \p First and \p Second are next to each other
10002 /// in memory. This means that there is no hole between the bits loaded
10003 /// by \p First and the bits loaded by \p Second.
10004 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10005                                      const LoadedSlice &Second) {
10006   assert(First.Origin == Second.Origin && First.Origin &&
10007          "Unable to match different memory origins.");
10008   APInt UsedBits = First.getUsedBits();
10009   assert((UsedBits & Second.getUsedBits()) == 0 &&
10010          "Slices are not supposed to overlap.");
10011   UsedBits |= Second.getUsedBits();
10012   return areUsedBitsDense(UsedBits);
10013 }
10014
10015 /// \brief Adjust the \p GlobalLSCost according to the target
10016 /// paring capabilities and the layout of the slices.
10017 /// \pre \p GlobalLSCost should account for at least as many loads as
10018 /// there is in the slices in \p LoadedSlices.
10019 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10020                                  LoadedSlice::Cost &GlobalLSCost) {
10021   unsigned NumberOfSlices = LoadedSlices.size();
10022   // If there is less than 2 elements, no pairing is possible.
10023   if (NumberOfSlices < 2)
10024     return;
10025
10026   // Sort the slices so that elements that are likely to be next to each
10027   // other in memory are next to each other in the list.
10028   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10029             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10030     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10031     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10032   });
10033   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10034   // First (resp. Second) is the first (resp. Second) potentially candidate
10035   // to be placed in a paired load.
10036   const LoadedSlice *First = nullptr;
10037   const LoadedSlice *Second = nullptr;
10038   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10039                 // Set the beginning of the pair.
10040                                                            First = Second) {
10041
10042     Second = &LoadedSlices[CurrSlice];
10043
10044     // If First is NULL, it means we start a new pair.
10045     // Get to the next slice.
10046     if (!First)
10047       continue;
10048
10049     EVT LoadedType = First->getLoadedType();
10050
10051     // If the types of the slices are different, we cannot pair them.
10052     if (LoadedType != Second->getLoadedType())
10053       continue;
10054
10055     // Check if the target supplies paired loads for this type.
10056     unsigned RequiredAlignment = 0;
10057     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10058       // move to the next pair, this type is hopeless.
10059       Second = nullptr;
10060       continue;
10061     }
10062     // Check if we meet the alignment requirement.
10063     if (RequiredAlignment > First->getAlignment())
10064       continue;
10065
10066     // Check that both loads are next to each other in memory.
10067     if (!areSlicesNextToEachOther(*First, *Second))
10068       continue;
10069
10070     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10071     --GlobalLSCost.Loads;
10072     // Move to the next pair.
10073     Second = nullptr;
10074   }
10075 }
10076
10077 /// \brief Check the profitability of all involved LoadedSlice.
10078 /// Currently, it is considered profitable if there is exactly two
10079 /// involved slices (1) which are (2) next to each other in memory, and
10080 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10081 ///
10082 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10083 /// the elements themselves.
10084 ///
10085 /// FIXME: When the cost model will be mature enough, we can relax
10086 /// constraints (1) and (2).
10087 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10088                                 const APInt &UsedBits, bool ForCodeSize) {
10089   unsigned NumberOfSlices = LoadedSlices.size();
10090   if (StressLoadSlicing)
10091     return NumberOfSlices > 1;
10092
10093   // Check (1).
10094   if (NumberOfSlices != 2)
10095     return false;
10096
10097   // Check (2).
10098   if (!areUsedBitsDense(UsedBits))
10099     return false;
10100
10101   // Check (3).
10102   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10103   // The original code has one big load.
10104   OrigCost.Loads = 1;
10105   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10106     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10107     // Accumulate the cost of all the slices.
10108     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10109     GlobalSlicingCost += SliceCost;
10110
10111     // Account as cost in the original configuration the gain obtained
10112     // with the current slices.
10113     OrigCost.addSliceGain(LS);
10114   }
10115
10116   // If the target supports paired load, adjust the cost accordingly.
10117   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10118   return OrigCost > GlobalSlicingCost;
10119 }
10120
10121 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10122 /// operations, split it in the various pieces being extracted.
10123 ///
10124 /// This sort of thing is introduced by SROA.
10125 /// This slicing takes care not to insert overlapping loads.
10126 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10127 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10128   if (Level < AfterLegalizeDAG)
10129     return false;
10130
10131   LoadSDNode *LD = cast<LoadSDNode>(N);
10132   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10133       !LD->getValueType(0).isInteger())
10134     return false;
10135
10136   // Keep track of already used bits to detect overlapping values.
10137   // In that case, we will just abort the transformation.
10138   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10139
10140   SmallVector<LoadedSlice, 4> LoadedSlices;
10141
10142   // Check if this load is used as several smaller chunks of bits.
10143   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10144   // of computation for each trunc.
10145   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10146        UI != UIEnd; ++UI) {
10147     // Skip the uses of the chain.
10148     if (UI.getUse().getResNo() != 0)
10149       continue;
10150
10151     SDNode *User = *UI;
10152     unsigned Shift = 0;
10153
10154     // Check if this is a trunc(lshr).
10155     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10156         isa<ConstantSDNode>(User->getOperand(1))) {
10157       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10158       User = *User->use_begin();
10159     }
10160
10161     // At this point, User is a Truncate, iff we encountered, trunc or
10162     // trunc(lshr).
10163     if (User->getOpcode() != ISD::TRUNCATE)
10164       return false;
10165
10166     // The width of the type must be a power of 2 and greater than 8-bits.
10167     // Otherwise the load cannot be represented in LLVM IR.
10168     // Moreover, if we shifted with a non-8-bits multiple, the slice
10169     // will be across several bytes. We do not support that.
10170     unsigned Width = User->getValueSizeInBits(0);
10171     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10172       return 0;
10173
10174     // Build the slice for this chain of computations.
10175     LoadedSlice LS(User, LD, Shift, &DAG);
10176     APInt CurrentUsedBits = LS.getUsedBits();
10177
10178     // Check if this slice overlaps with another.
10179     if ((CurrentUsedBits & UsedBits) != 0)
10180       return false;
10181     // Update the bits used globally.
10182     UsedBits |= CurrentUsedBits;
10183
10184     // Check if the new slice would be legal.
10185     if (!LS.isLegal())
10186       return false;
10187
10188     // Record the slice.
10189     LoadedSlices.push_back(LS);
10190   }
10191
10192   // Abort slicing if it does not seem to be profitable.
10193   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10194     return false;
10195
10196   ++SlicedLoads;
10197
10198   // Rewrite each chain to use an independent load.
10199   // By construction, each chain can be represented by a unique load.
10200
10201   // Prepare the argument for the new token factor for all the slices.
10202   SmallVector<SDValue, 8> ArgChains;
10203   for (SmallVectorImpl<LoadedSlice>::const_iterator
10204            LSIt = LoadedSlices.begin(),
10205            LSItEnd = LoadedSlices.end();
10206        LSIt != LSItEnd; ++LSIt) {
10207     SDValue SliceInst = LSIt->loadSlice();
10208     CombineTo(LSIt->Inst, SliceInst, true);
10209     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10210       SliceInst = SliceInst.getOperand(0);
10211     assert(SliceInst->getOpcode() == ISD::LOAD &&
10212            "It takes more than a zext to get to the loaded slice!!");
10213     ArgChains.push_back(SliceInst.getValue(1));
10214   }
10215
10216   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10217                               ArgChains);
10218   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10219   return true;
10220 }
10221
10222 /// Check to see if V is (and load (ptr), imm), where the load is having
10223 /// specific bytes cleared out.  If so, return the byte size being masked out
10224 /// and the shift amount.
10225 static std::pair<unsigned, unsigned>
10226 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10227   std::pair<unsigned, unsigned> Result(0, 0);
10228
10229   // Check for the structure we're looking for.
10230   if (V->getOpcode() != ISD::AND ||
10231       !isa<ConstantSDNode>(V->getOperand(1)) ||
10232       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10233     return Result;
10234
10235   // Check the chain and pointer.
10236   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10237   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10238
10239   // The store should be chained directly to the load or be an operand of a
10240   // tokenfactor.
10241   if (LD == Chain.getNode())
10242     ; // ok.
10243   else if (Chain->getOpcode() != ISD::TokenFactor)
10244     return Result; // Fail.
10245   else {
10246     bool isOk = false;
10247     for (const SDValue &ChainOp : Chain->op_values())
10248       if (ChainOp.getNode() == LD) {
10249         isOk = true;
10250         break;
10251       }
10252     if (!isOk) return Result;
10253   }
10254
10255   // This only handles simple types.
10256   if (V.getValueType() != MVT::i16 &&
10257       V.getValueType() != MVT::i32 &&
10258       V.getValueType() != MVT::i64)
10259     return Result;
10260
10261   // Check the constant mask.  Invert it so that the bits being masked out are
10262   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10263   // follow the sign bit for uniformity.
10264   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10265   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10266   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10267   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10268   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10269   if (NotMaskLZ == 64) return Result;  // All zero mask.
10270
10271   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10272   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10273     return Result;
10274
10275   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10276   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10277     NotMaskLZ -= 64-V.getValueSizeInBits();
10278
10279   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10280   switch (MaskedBytes) {
10281   case 1:
10282   case 2:
10283   case 4: break;
10284   default: return Result; // All one mask, or 5-byte mask.
10285   }
10286
10287   // Verify that the first bit starts at a multiple of mask so that the access
10288   // is aligned the same as the access width.
10289   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10290
10291   Result.first = MaskedBytes;
10292   Result.second = NotMaskTZ/8;
10293   return Result;
10294 }
10295
10296
10297 /// Check to see if IVal is something that provides a value as specified by
10298 /// MaskInfo. If so, replace the specified store with a narrower store of
10299 /// truncated IVal.
10300 static SDNode *
10301 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10302                                 SDValue IVal, StoreSDNode *St,
10303                                 DAGCombiner *DC) {
10304   unsigned NumBytes = MaskInfo.first;
10305   unsigned ByteShift = MaskInfo.second;
10306   SelectionDAG &DAG = DC->getDAG();
10307
10308   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10309   // that uses this.  If not, this is not a replacement.
10310   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10311                                   ByteShift*8, (ByteShift+NumBytes)*8);
10312   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10313
10314   // Check that it is legal on the target to do this.  It is legal if the new
10315   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10316   // legalization.
10317   MVT VT = MVT::getIntegerVT(NumBytes*8);
10318   if (!DC->isTypeLegal(VT))
10319     return nullptr;
10320
10321   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10322   // shifted by ByteShift and truncated down to NumBytes.
10323   if (ByteShift) {
10324     SDLoc DL(IVal);
10325     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10326                        DAG.getConstant(ByteShift*8, DL,
10327                                     DC->getShiftAmountTy(IVal.getValueType())));
10328   }
10329
10330   // Figure out the offset for the store and the alignment of the access.
10331   unsigned StOffset;
10332   unsigned NewAlign = St->getAlignment();
10333
10334   if (DAG.getDataLayout().isLittleEndian())
10335     StOffset = ByteShift;
10336   else
10337     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10338
10339   SDValue Ptr = St->getBasePtr();
10340   if (StOffset) {
10341     SDLoc DL(IVal);
10342     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10343                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10344     NewAlign = MinAlign(NewAlign, StOffset);
10345   }
10346
10347   // Truncate down to the new size.
10348   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10349
10350   ++OpsNarrowed;
10351   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10352                       St->getPointerInfo().getWithOffset(StOffset),
10353                       false, false, NewAlign).getNode();
10354 }
10355
10356
10357 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10358 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10359 /// narrowing the load and store if it would end up being a win for performance
10360 /// or code size.
10361 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10362   StoreSDNode *ST  = cast<StoreSDNode>(N);
10363   if (ST->isVolatile())
10364     return SDValue();
10365
10366   SDValue Chain = ST->getChain();
10367   SDValue Value = ST->getValue();
10368   SDValue Ptr   = ST->getBasePtr();
10369   EVT VT = Value.getValueType();
10370
10371   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10372     return SDValue();
10373
10374   unsigned Opc = Value.getOpcode();
10375
10376   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10377   // is a byte mask indicating a consecutive number of bytes, check to see if
10378   // Y is known to provide just those bytes.  If so, we try to replace the
10379   // load + replace + store sequence with a single (narrower) store, which makes
10380   // the load dead.
10381   if (Opc == ISD::OR) {
10382     std::pair<unsigned, unsigned> MaskedLoad;
10383     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10384     if (MaskedLoad.first)
10385       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10386                                                   Value.getOperand(1), ST,this))
10387         return SDValue(NewST, 0);
10388
10389     // Or is commutative, so try swapping X and Y.
10390     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10391     if (MaskedLoad.first)
10392       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10393                                                   Value.getOperand(0), ST,this))
10394         return SDValue(NewST, 0);
10395   }
10396
10397   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10398       Value.getOperand(1).getOpcode() != ISD::Constant)
10399     return SDValue();
10400
10401   SDValue N0 = Value.getOperand(0);
10402   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10403       Chain == SDValue(N0.getNode(), 1)) {
10404     LoadSDNode *LD = cast<LoadSDNode>(N0);
10405     if (LD->getBasePtr() != Ptr ||
10406         LD->getPointerInfo().getAddrSpace() !=
10407         ST->getPointerInfo().getAddrSpace())
10408       return SDValue();
10409
10410     // Find the type to narrow it the load / op / store to.
10411     SDValue N1 = Value.getOperand(1);
10412     unsigned BitWidth = N1.getValueSizeInBits();
10413     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10414     if (Opc == ISD::AND)
10415       Imm ^= APInt::getAllOnesValue(BitWidth);
10416     if (Imm == 0 || Imm.isAllOnesValue())
10417       return SDValue();
10418     unsigned ShAmt = Imm.countTrailingZeros();
10419     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10420     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10421     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10422     // The narrowing should be profitable, the load/store operation should be
10423     // legal (or custom) and the store size should be equal to the NewVT width.
10424     while (NewBW < BitWidth &&
10425            (NewVT.getStoreSizeInBits() != NewBW ||
10426             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10427             !TLI.isNarrowingProfitable(VT, NewVT))) {
10428       NewBW = NextPowerOf2(NewBW);
10429       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10430     }
10431     if (NewBW >= BitWidth)
10432       return SDValue();
10433
10434     // If the lsb changed does not start at the type bitwidth boundary,
10435     // start at the previous one.
10436     if (ShAmt % NewBW)
10437       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10438     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10439                                    std::min(BitWidth, ShAmt + NewBW));
10440     if ((Imm & Mask) == Imm) {
10441       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10442       if (Opc == ISD::AND)
10443         NewImm ^= APInt::getAllOnesValue(NewBW);
10444       uint64_t PtrOff = ShAmt / 8;
10445       // For big endian targets, we need to adjust the offset to the pointer to
10446       // load the correct bytes.
10447       if (DAG.getDataLayout().isBigEndian())
10448         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10449
10450       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10451       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10452       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10453         return SDValue();
10454
10455       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10456                                    Ptr.getValueType(), Ptr,
10457                                    DAG.getConstant(PtrOff, SDLoc(LD),
10458                                                    Ptr.getValueType()));
10459       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10460                                   LD->getChain(), NewPtr,
10461                                   LD->getPointerInfo().getWithOffset(PtrOff),
10462                                   LD->isVolatile(), LD->isNonTemporal(),
10463                                   LD->isInvariant(), NewAlign,
10464                                   LD->getAAInfo());
10465       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10466                                    DAG.getConstant(NewImm, SDLoc(Value),
10467                                                    NewVT));
10468       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10469                                    NewVal, NewPtr,
10470                                    ST->getPointerInfo().getWithOffset(PtrOff),
10471                                    false, false, NewAlign);
10472
10473       AddToWorklist(NewPtr.getNode());
10474       AddToWorklist(NewLD.getNode());
10475       AddToWorklist(NewVal.getNode());
10476       WorklistRemover DeadNodes(*this);
10477       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10478       ++OpsNarrowed;
10479       return NewST;
10480     }
10481   }
10482
10483   return SDValue();
10484 }
10485
10486 /// For a given floating point load / store pair, if the load value isn't used
10487 /// by any other operations, then consider transforming the pair to integer
10488 /// load / store operations if the target deems the transformation profitable.
10489 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10490   StoreSDNode *ST  = cast<StoreSDNode>(N);
10491   SDValue Chain = ST->getChain();
10492   SDValue Value = ST->getValue();
10493   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10494       Value.hasOneUse() &&
10495       Chain == SDValue(Value.getNode(), 1)) {
10496     LoadSDNode *LD = cast<LoadSDNode>(Value);
10497     EVT VT = LD->getMemoryVT();
10498     if (!VT.isFloatingPoint() ||
10499         VT != ST->getMemoryVT() ||
10500         LD->isNonTemporal() ||
10501         ST->isNonTemporal() ||
10502         LD->getPointerInfo().getAddrSpace() != 0 ||
10503         ST->getPointerInfo().getAddrSpace() != 0)
10504       return SDValue();
10505
10506     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10507     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10508         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10509         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10510         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10511       return SDValue();
10512
10513     unsigned LDAlign = LD->getAlignment();
10514     unsigned STAlign = ST->getAlignment();
10515     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10516     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10517     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10518       return SDValue();
10519
10520     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10521                                 LD->getChain(), LD->getBasePtr(),
10522                                 LD->getPointerInfo(),
10523                                 false, false, false, LDAlign);
10524
10525     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10526                                  NewLD, ST->getBasePtr(),
10527                                  ST->getPointerInfo(),
10528                                  false, false, STAlign);
10529
10530     AddToWorklist(NewLD.getNode());
10531     AddToWorklist(NewST.getNode());
10532     WorklistRemover DeadNodes(*this);
10533     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10534     ++LdStFP2Int;
10535     return NewST;
10536   }
10537
10538   return SDValue();
10539 }
10540
10541 namespace {
10542 /// Helper struct to parse and store a memory address as base + index + offset.
10543 /// We ignore sign extensions when it is safe to do so.
10544 /// The following two expressions are not equivalent. To differentiate we need
10545 /// to store whether there was a sign extension involved in the index
10546 /// computation.
10547 ///  (load (i64 add (i64 copyfromreg %c)
10548 ///                 (i64 signextend (add (i8 load %index)
10549 ///                                      (i8 1))))
10550 /// vs
10551 ///
10552 /// (load (i64 add (i64 copyfromreg %c)
10553 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10554 ///                                         (i32 1)))))
10555 struct BaseIndexOffset {
10556   SDValue Base;
10557   SDValue Index;
10558   int64_t Offset;
10559   bool IsIndexSignExt;
10560
10561   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10562
10563   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10564                   bool IsIndexSignExt) :
10565     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10566
10567   bool equalBaseIndex(const BaseIndexOffset &Other) {
10568     return Other.Base == Base && Other.Index == Index &&
10569       Other.IsIndexSignExt == IsIndexSignExt;
10570   }
10571
10572   /// Parses tree in Ptr for base, index, offset addresses.
10573   static BaseIndexOffset match(SDValue Ptr) {
10574     bool IsIndexSignExt = false;
10575
10576     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10577     // instruction, then it could be just the BASE or everything else we don't
10578     // know how to handle. Just use Ptr as BASE and give up.
10579     if (Ptr->getOpcode() != ISD::ADD)
10580       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10581
10582     // We know that we have at least an ADD instruction. Try to pattern match
10583     // the simple case of BASE + OFFSET.
10584     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10585       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10586       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10587                               IsIndexSignExt);
10588     }
10589
10590     // Inside a loop the current BASE pointer is calculated using an ADD and a
10591     // MUL instruction. In this case Ptr is the actual BASE pointer.
10592     // (i64 add (i64 %array_ptr)
10593     //          (i64 mul (i64 %induction_var)
10594     //                   (i64 %element_size)))
10595     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10596       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10597
10598     // Look at Base + Index + Offset cases.
10599     SDValue Base = Ptr->getOperand(0);
10600     SDValue IndexOffset = Ptr->getOperand(1);
10601
10602     // Skip signextends.
10603     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10604       IndexOffset = IndexOffset->getOperand(0);
10605       IsIndexSignExt = true;
10606     }
10607
10608     // Either the case of Base + Index (no offset) or something else.
10609     if (IndexOffset->getOpcode() != ISD::ADD)
10610       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10611
10612     // Now we have the case of Base + Index + offset.
10613     SDValue Index = IndexOffset->getOperand(0);
10614     SDValue Offset = IndexOffset->getOperand(1);
10615
10616     if (!isa<ConstantSDNode>(Offset))
10617       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10618
10619     // Ignore signextends.
10620     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10621       Index = Index->getOperand(0);
10622       IsIndexSignExt = true;
10623     } else IsIndexSignExt = false;
10624
10625     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10626     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10627   }
10628 };
10629 } // namespace
10630
10631 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10632                                                   SDLoc SL,
10633                                                   ArrayRef<MemOpLink> Stores,
10634                                                   EVT Ty) const {
10635   SmallVector<SDValue, 8> BuildVector;
10636
10637   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10638     BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10639
10640   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10641 }
10642
10643 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10644                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10645                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10646   // Make sure we have something to merge.
10647   if (NumElem < 2)
10648     return false;
10649
10650   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10651   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10652   unsigned LatestNodeUsed = 0;
10653
10654   for (unsigned i=0; i < NumElem; ++i) {
10655     // Find a chain for the new wide-store operand. Notice that some
10656     // of the store nodes that we found may not be selected for inclusion
10657     // in the wide store. The chain we use needs to be the chain of the
10658     // latest store node which is *used* and replaced by the wide store.
10659     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10660       LatestNodeUsed = i;
10661   }
10662
10663   // The latest Node in the DAG.
10664   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10665   SDLoc DL(StoreNodes[0].MemNode);
10666
10667   SDValue StoredVal;
10668   if (UseVector) {
10669     // Find a legal type for the vector store.
10670     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10671     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10672     if (IsConstantSrc) {
10673       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10674     } else {
10675       SmallVector<SDValue, 8> Ops;
10676       for (unsigned i = 0; i < NumElem ; ++i) {
10677         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10678         SDValue Val = St->getValue();
10679         // All of the operands of a BUILD_VECTOR must have the same type.
10680         if (Val.getValueType() != MemVT)
10681           return false;
10682         Ops.push_back(Val);
10683       }
10684
10685       // Build the extracted vector elements back into a vector.
10686       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10687     }
10688   } else {
10689     // We should always use a vector store when merging extracted vector
10690     // elements, so this path implies a store of constants.
10691     assert(IsConstantSrc && "Merged vector elements should use vector store");
10692
10693     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10694     APInt StoreInt(SizeInBits, 0);
10695
10696     // Construct a single integer constant which is made of the smaller
10697     // constant inputs.
10698     bool IsLE = DAG.getDataLayout().isLittleEndian();
10699     for (unsigned i = 0; i < NumElem ; ++i) {
10700       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10701       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10702       SDValue Val = St->getValue();
10703       StoreInt <<= ElementSizeBytes * 8;
10704       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10705         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10706       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10707         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10708       } else {
10709         llvm_unreachable("Invalid constant element type");
10710       }
10711     }
10712
10713     // Create the new Load and Store operations.
10714     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10715     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10716   }
10717
10718   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10719                                   FirstInChain->getBasePtr(),
10720                                   FirstInChain->getPointerInfo(),
10721                                   false, false,
10722                                   FirstInChain->getAlignment());
10723
10724   // Replace the last store with the new store
10725   CombineTo(LatestOp, NewStore);
10726   // Erase all other stores.
10727   for (unsigned i = 0; i < NumElem ; ++i) {
10728     if (StoreNodes[i].MemNode == LatestOp)
10729       continue;
10730     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10731     // ReplaceAllUsesWith will replace all uses that existed when it was
10732     // called, but graph optimizations may cause new ones to appear. For
10733     // example, the case in pr14333 looks like
10734     //
10735     //  St's chain -> St -> another store -> X
10736     //
10737     // And the only difference from St to the other store is the chain.
10738     // When we change it's chain to be St's chain they become identical,
10739     // get CSEed and the net result is that X is now a use of St.
10740     // Since we know that St is redundant, just iterate.
10741     while (!St->use_empty())
10742       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10743     deleteAndRecombine(St);
10744   }
10745
10746   return true;
10747 }
10748
10749 void DAGCombiner::getStoreMergeAndAliasCandidates(
10750     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10751     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10752   // This holds the base pointer, index, and the offset in bytes from the base
10753   // pointer.
10754   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10755
10756   // We must have a base and an offset.
10757   if (!BasePtr.Base.getNode())
10758     return;
10759
10760   // Do not handle stores to undef base pointers.
10761   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10762     return;
10763
10764   // Walk up the chain and look for nodes with offsets from the same
10765   // base pointer. Stop when reaching an instruction with a different kind
10766   // or instruction which has a different base pointer.
10767   EVT MemVT = St->getMemoryVT();
10768   unsigned Seq = 0;
10769   StoreSDNode *Index = St;
10770   while (Index) {
10771     // If the chain has more than one use, then we can't reorder the mem ops.
10772     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10773       break;
10774
10775     // Find the base pointer and offset for this memory node.
10776     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10777
10778     // Check that the base pointer is the same as the original one.
10779     if (!Ptr.equalBaseIndex(BasePtr))
10780       break;
10781
10782     // The memory operands must not be volatile.
10783     if (Index->isVolatile() || Index->isIndexed())
10784       break;
10785
10786     // No truncation.
10787     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10788       if (St->isTruncatingStore())
10789         break;
10790
10791     // The stored memory type must be the same.
10792     if (Index->getMemoryVT() != MemVT)
10793       break;
10794
10795     // We found a potential memory operand to merge.
10796     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10797
10798     // Find the next memory operand in the chain. If the next operand in the
10799     // chain is a store then move up and continue the scan with the next
10800     // memory operand. If the next operand is a load save it and use alias
10801     // information to check if it interferes with anything.
10802     SDNode *NextInChain = Index->getChain().getNode();
10803     while (1) {
10804       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10805         // We found a store node. Use it for the next iteration.
10806         Index = STn;
10807         break;
10808       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10809         if (Ldn->isVolatile()) {
10810           Index = nullptr;
10811           break;
10812         }
10813
10814         // Save the load node for later. Continue the scan.
10815         AliasLoadNodes.push_back(Ldn);
10816         NextInChain = Ldn->getChain().getNode();
10817         continue;
10818       } else {
10819         Index = nullptr;
10820         break;
10821       }
10822     }
10823   }
10824 }
10825
10826 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10827   if (OptLevel == CodeGenOpt::None)
10828     return false;
10829
10830   EVT MemVT = St->getMemoryVT();
10831   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10832   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10833       Attribute::NoImplicitFloat);
10834
10835   // This function cannot currently deal with non-byte-sized memory sizes.
10836   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10837     return false;
10838
10839   // Don't merge vectors into wider inputs.
10840   if (MemVT.isVector() || !MemVT.isSimple())
10841     return false;
10842
10843   // Perform an early exit check. Do not bother looking at stored values that
10844   // are not constants, loads, or extracted vector elements.
10845   SDValue StoredVal = St->getValue();
10846   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10847   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10848                        isa<ConstantFPSDNode>(StoredVal);
10849   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10850
10851   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10852     return false;
10853
10854   // Only look at ends of store sequences.
10855   SDValue Chain = SDValue(St, 0);
10856   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10857     return false;
10858
10859   // Save the LoadSDNodes that we find in the chain.
10860   // We need to make sure that these nodes do not interfere with
10861   // any of the store nodes.
10862   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10863   
10864   // Save the StoreSDNodes that we find in the chain.
10865   SmallVector<MemOpLink, 8> StoreNodes;
10866
10867   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10868   
10869   // Check if there is anything to merge.
10870   if (StoreNodes.size() < 2)
10871     return false;
10872
10873   // Sort the memory operands according to their distance from the base pointer.
10874   std::sort(StoreNodes.begin(), StoreNodes.end(),
10875             [](MemOpLink LHS, MemOpLink RHS) {
10876     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10877            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10878             LHS.SequenceNum > RHS.SequenceNum);
10879   });
10880
10881   // Scan the memory operations on the chain and find the first non-consecutive
10882   // store memory address.
10883   unsigned LastConsecutiveStore = 0;
10884   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10885   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10886
10887     // Check that the addresses are consecutive starting from the second
10888     // element in the list of stores.
10889     if (i > 0) {
10890       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10891       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10892         break;
10893     }
10894
10895     bool Alias = false;
10896     // Check if this store interferes with any of the loads that we found.
10897     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10898       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10899         Alias = true;
10900         break;
10901       }
10902     // We found a load that alias with this store. Stop the sequence.
10903     if (Alias)
10904       break;
10905
10906     // Mark this node as useful.
10907     LastConsecutiveStore = i;
10908   }
10909
10910   // The node with the lowest store address.
10911   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10912   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10913   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10914   LLVMContext &Context = *DAG.getContext();
10915   const DataLayout &DL = DAG.getDataLayout();
10916
10917   // Store the constants into memory as one consecutive store.
10918   if (IsConstantSrc) {
10919     unsigned LastLegalType = 0;
10920     unsigned LastLegalVectorType = 0;
10921     bool NonZero = false;
10922     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10923       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10924       SDValue StoredVal = St->getValue();
10925
10926       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10927         NonZero |= !C->isNullValue();
10928       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10929         NonZero |= !C->getConstantFPValue()->isNullValue();
10930       } else {
10931         // Non-constant.
10932         break;
10933       }
10934
10935       // Find a legal type for the constant store.
10936       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10937       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
10938       if (TLI.isTypeLegal(StoreTy) &&
10939           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
10940                                  FirstStoreAlign)) {
10941         LastLegalType = i+1;
10942       // Or check whether a truncstore is legal.
10943       } else if (TLI.getTypeAction(Context, StoreTy) ==
10944                  TargetLowering::TypePromoteInteger) {
10945         EVT LegalizedStoredValueTy =
10946           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
10947         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10948             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
10949                                    FirstStoreAS, FirstStoreAlign)) {
10950           LastLegalType = i + 1;
10951         }
10952       }
10953
10954       // Find a legal type for the vector store.
10955       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
10956       if (TLI.isTypeLegal(Ty) &&
10957           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
10958                                  FirstStoreAlign)) {
10959         LastLegalVectorType = i + 1;
10960       }
10961     }
10962
10963
10964     // We only use vectors if the constant is known to be zero or the target
10965     // allows it and the function is not marked with the noimplicitfloat
10966     // attribute.
10967     if (NoVectors) {
10968       LastLegalVectorType = 0;
10969     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10970                                                             LastLegalVectorType,
10971                                                             FirstStoreAS)) {
10972       LastLegalVectorType = 0;
10973     }
10974
10975     // Check if we found a legal integer type to store.
10976     if (LastLegalType == 0 && LastLegalVectorType == 0)
10977       return false;
10978
10979     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10980     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10981
10982     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10983                                            true, UseVector);
10984   }
10985
10986   // When extracting multiple vector elements, try to store them
10987   // in one vector store rather than a sequence of scalar stores.
10988   if (IsExtractVecEltSrc) {
10989     unsigned NumElem = 0;
10990     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10991       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10992       SDValue StoredVal = St->getValue();
10993       // This restriction could be loosened.
10994       // Bail out if any stored values are not elements extracted from a vector.
10995       // It should be possible to handle mixed sources, but load sources need
10996       // more careful handling (see the block of code below that handles
10997       // consecutive loads).
10998       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10999         return false;
11000
11001       // Find a legal type for the vector store.
11002       EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11003       if (TLI.isTypeLegal(Ty) &&
11004           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11005                                  FirstStoreAlign))
11006         NumElem = i + 1;
11007     }
11008
11009     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11010                                            false, true);
11011   }
11012
11013   // Below we handle the case of multiple consecutive stores that
11014   // come from multiple consecutive loads. We merge them into a single
11015   // wide load and a single wide store.
11016
11017   // Look for load nodes which are used by the stored values.
11018   SmallVector<MemOpLink, 8> LoadNodes;
11019
11020   // Find acceptable loads. Loads need to have the same chain (token factor),
11021   // must not be zext, volatile, indexed, and they must be consecutive.
11022   BaseIndexOffset LdBasePtr;
11023   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11024     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11025     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11026     if (!Ld) break;
11027
11028     // Loads must only have one use.
11029     if (!Ld->hasNUsesOfValue(1, 0))
11030       break;
11031
11032     // The memory operands must not be volatile.
11033     if (Ld->isVolatile() || Ld->isIndexed())
11034       break;
11035
11036     // We do not accept ext loads.
11037     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11038       break;
11039
11040     // The stored memory type must be the same.
11041     if (Ld->getMemoryVT() != MemVT)
11042       break;
11043
11044     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11045     // If this is not the first ptr that we check.
11046     if (LdBasePtr.Base.getNode()) {
11047       // The base ptr must be the same.
11048       if (!LdPtr.equalBaseIndex(LdBasePtr))
11049         break;
11050     } else {
11051       // Check that all other base pointers are the same as this one.
11052       LdBasePtr = LdPtr;
11053     }
11054
11055     // We found a potential memory operand to merge.
11056     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11057   }
11058
11059   if (LoadNodes.size() < 2)
11060     return false;
11061
11062   // If we have load/store pair instructions and we only have two values,
11063   // don't bother.
11064   unsigned RequiredAlignment;
11065   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11066       St->getAlignment() >= RequiredAlignment)
11067     return false;
11068
11069   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11070   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11071   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11072
11073   // Scan the memory operations on the chain and find the first non-consecutive
11074   // load memory address. These variables hold the index in the store node
11075   // array.
11076   unsigned LastConsecutiveLoad = 0;
11077   // This variable refers to the size and not index in the array.
11078   unsigned LastLegalVectorType = 0;
11079   unsigned LastLegalIntegerType = 0;
11080   StartAddress = LoadNodes[0].OffsetFromBase;
11081   SDValue FirstChain = FirstLoad->getChain();
11082   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11083     // All loads much share the same chain.
11084     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11085       break;
11086
11087     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11088     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11089       break;
11090     LastConsecutiveLoad = i;
11091
11092     // Find a legal type for the vector store.
11093     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11094     if (TLI.isTypeLegal(StoreTy) &&
11095         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11096                                FirstStoreAlign) &&
11097         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11098                                FirstLoadAlign)) {
11099       LastLegalVectorType = i + 1;
11100     }
11101
11102     // Find a legal type for the integer store.
11103     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11104     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11105     if (TLI.isTypeLegal(StoreTy) &&
11106         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11107                                FirstStoreAlign) &&
11108         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11109                                FirstLoadAlign))
11110       LastLegalIntegerType = i + 1;
11111     // Or check whether a truncstore and extload is legal.
11112     else if (TLI.getTypeAction(Context, StoreTy) ==
11113              TargetLowering::TypePromoteInteger) {
11114       EVT LegalizedStoredValueTy =
11115         TLI.getTypeToTransformTo(Context, StoreTy);
11116       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11117           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11118           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11119           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11120           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11121                                  FirstStoreAS, FirstStoreAlign) &&
11122           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11123                                  FirstLoadAS, FirstLoadAlign))
11124         LastLegalIntegerType = i+1;
11125     }
11126   }
11127
11128   // Only use vector types if the vector type is larger than the integer type.
11129   // If they are the same, use integers.
11130   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11131   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11132
11133   // We add +1 here because the LastXXX variables refer to location while
11134   // the NumElem refers to array/index size.
11135   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11136   NumElem = std::min(LastLegalType, NumElem);
11137
11138   if (NumElem < 2)
11139     return false;
11140
11141   // The latest Node in the DAG.
11142   unsigned LatestNodeUsed = 0;
11143   for (unsigned i=1; i<NumElem; ++i) {
11144     // Find a chain for the new wide-store operand. Notice that some
11145     // of the store nodes that we found may not be selected for inclusion
11146     // in the wide store. The chain we use needs to be the chain of the
11147     // latest store node which is *used* and replaced by the wide store.
11148     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11149       LatestNodeUsed = i;
11150   }
11151
11152   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11153
11154   // Find if it is better to use vectors or integers to load and store
11155   // to memory.
11156   EVT JointMemOpVT;
11157   if (UseVectorTy) {
11158     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11159   } else {
11160     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11161     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11162   }
11163
11164   SDLoc LoadDL(LoadNodes[0].MemNode);
11165   SDLoc StoreDL(StoreNodes[0].MemNode);
11166
11167   SDValue NewLoad = DAG.getLoad(
11168       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11169       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11170
11171   SDValue NewStore = DAG.getStore(
11172       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11173       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11174
11175   // Replace one of the loads with the new load.
11176   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11177   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11178                                 SDValue(NewLoad.getNode(), 1));
11179
11180   // Remove the rest of the load chains.
11181   for (unsigned i = 1; i < NumElem ; ++i) {
11182     // Replace all chain users of the old load nodes with the chain of the new
11183     // load node.
11184     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11185     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11186   }
11187
11188   // Replace the last store with the new store.
11189   CombineTo(LatestOp, NewStore);
11190   // Erase all other stores.
11191   for (unsigned i = 0; i < NumElem ; ++i) {
11192     // Remove all Store nodes.
11193     if (StoreNodes[i].MemNode == LatestOp)
11194       continue;
11195     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11196     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11197     deleteAndRecombine(St);
11198   }
11199
11200   return true;
11201 }
11202
11203 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11204   StoreSDNode *ST  = cast<StoreSDNode>(N);
11205   SDValue Chain = ST->getChain();
11206   SDValue Value = ST->getValue();
11207   SDValue Ptr   = ST->getBasePtr();
11208
11209   // If this is a store of a bit convert, store the input value if the
11210   // resultant store does not need a higher alignment than the original.
11211   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11212       ST->isUnindexed()) {
11213     unsigned OrigAlign = ST->getAlignment();
11214     EVT SVT = Value.getOperand(0).getValueType();
11215     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11216         SVT.getTypeForEVT(*DAG.getContext()));
11217     if (Align <= OrigAlign &&
11218         ((!LegalOperations && !ST->isVolatile()) ||
11219          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11220       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11221                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11222                           ST->isNonTemporal(), OrigAlign,
11223                           ST->getAAInfo());
11224   }
11225
11226   // Turn 'store undef, Ptr' -> nothing.
11227   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11228     return Chain;
11229
11230   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11231   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11232     // NOTE: If the original store is volatile, this transform must not increase
11233     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11234     // processor operation but an i64 (which is not legal) requires two.  So the
11235     // transform should not be done in this case.
11236     if (Value.getOpcode() != ISD::TargetConstantFP) {
11237       SDValue Tmp;
11238       switch (CFP->getSimpleValueType(0).SimpleTy) {
11239       default: llvm_unreachable("Unknown FP type");
11240       case MVT::f16:    // We don't do this for these yet.
11241       case MVT::f80:
11242       case MVT::f128:
11243       case MVT::ppcf128:
11244         break;
11245       case MVT::f32:
11246         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11247             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11248           ;
11249           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11250                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11251                               MVT::i32);
11252           return DAG.getStore(Chain, SDLoc(N), Tmp,
11253                               Ptr, ST->getMemOperand());
11254         }
11255         break;
11256       case MVT::f64:
11257         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11258              !ST->isVolatile()) ||
11259             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11260           ;
11261           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11262                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11263           return DAG.getStore(Chain, SDLoc(N), Tmp,
11264                               Ptr, ST->getMemOperand());
11265         }
11266
11267         if (!ST->isVolatile() &&
11268             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11269           // Many FP stores are not made apparent until after legalize, e.g. for
11270           // argument passing.  Since this is so common, custom legalize the
11271           // 64-bit integer store into two 32-bit stores.
11272           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11273           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11274           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11275           if (DAG.getDataLayout().isBigEndian())
11276             std::swap(Lo, Hi);
11277
11278           unsigned Alignment = ST->getAlignment();
11279           bool isVolatile = ST->isVolatile();
11280           bool isNonTemporal = ST->isNonTemporal();
11281           AAMDNodes AAInfo = ST->getAAInfo();
11282
11283           SDLoc DL(N);
11284
11285           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11286                                      Ptr, ST->getPointerInfo(),
11287                                      isVolatile, isNonTemporal,
11288                                      ST->getAlignment(), AAInfo);
11289           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11290                             DAG.getConstant(4, DL, Ptr.getValueType()));
11291           Alignment = MinAlign(Alignment, 4U);
11292           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11293                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11294                                      isVolatile, isNonTemporal,
11295                                      Alignment, AAInfo);
11296           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11297                              St0, St1);
11298         }
11299
11300         break;
11301       }
11302     }
11303   }
11304
11305   // Try to infer better alignment information than the store already has.
11306   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11307     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11308       if (Align > ST->getAlignment()) {
11309         SDValue NewStore =
11310                DAG.getTruncStore(Chain, SDLoc(N), Value,
11311                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11312                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11313                                  ST->getAAInfo());
11314         if (NewStore.getNode() != N)
11315           return CombineTo(ST, NewStore, true);
11316       }
11317     }
11318   }
11319
11320   // Try transforming a pair floating point load / store ops to integer
11321   // load / store ops.
11322   SDValue NewST = TransformFPLoadStorePair(N);
11323   if (NewST.getNode())
11324     return NewST;
11325
11326   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11327                                                   : DAG.getSubtarget().useAA();
11328 #ifndef NDEBUG
11329   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11330       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11331     UseAA = false;
11332 #endif
11333   if (UseAA && ST->isUnindexed()) {
11334     // Walk up chain skipping non-aliasing memory nodes.
11335     SDValue BetterChain = FindBetterChain(N, Chain);
11336
11337     // If there is a better chain.
11338     if (Chain != BetterChain) {
11339       SDValue ReplStore;
11340
11341       // Replace the chain to avoid dependency.
11342       if (ST->isTruncatingStore()) {
11343         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11344                                       ST->getMemoryVT(), ST->getMemOperand());
11345       } else {
11346         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11347                                  ST->getMemOperand());
11348       }
11349
11350       // Create token to keep both nodes around.
11351       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11352                                   MVT::Other, Chain, ReplStore);
11353
11354       // Make sure the new and old chains are cleaned up.
11355       AddToWorklist(Token.getNode());
11356
11357       // Don't add users to work list.
11358       return CombineTo(N, Token, false);
11359     }
11360   }
11361
11362   // Try transforming N to an indexed store.
11363   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11364     return SDValue(N, 0);
11365
11366   // FIXME: is there such a thing as a truncating indexed store?
11367   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11368       Value.getValueType().isInteger()) {
11369     // See if we can simplify the input to this truncstore with knowledge that
11370     // only the low bits are being used.  For example:
11371     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11372     SDValue Shorter =
11373       GetDemandedBits(Value,
11374                       APInt::getLowBitsSet(
11375                         Value.getValueType().getScalarType().getSizeInBits(),
11376                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11377     AddToWorklist(Value.getNode());
11378     if (Shorter.getNode())
11379       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11380                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11381
11382     // Otherwise, see if we can simplify the operation with
11383     // SimplifyDemandedBits, which only works if the value has a single use.
11384     if (SimplifyDemandedBits(Value,
11385                         APInt::getLowBitsSet(
11386                           Value.getValueType().getScalarType().getSizeInBits(),
11387                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11388       return SDValue(N, 0);
11389   }
11390
11391   // If this is a load followed by a store to the same location, then the store
11392   // is dead/noop.
11393   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11394     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11395         ST->isUnindexed() && !ST->isVolatile() &&
11396         // There can't be any side effects between the load and store, such as
11397         // a call or store.
11398         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11399       // The store is dead, remove it.
11400       return Chain;
11401     }
11402   }
11403
11404   // If this is a store followed by a store with the same value to the same
11405   // location, then the store is dead/noop.
11406   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11407     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11408         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11409         ST1->isUnindexed() && !ST1->isVolatile()) {
11410       // The store is dead, remove it.
11411       return Chain;
11412     }
11413   }
11414
11415   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11416   // truncating store.  We can do this even if this is already a truncstore.
11417   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11418       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11419       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11420                             ST->getMemoryVT())) {
11421     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11422                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11423   }
11424
11425   // Only perform this optimization before the types are legal, because we
11426   // don't want to perform this optimization on every DAGCombine invocation.
11427   if (!LegalTypes) {
11428     bool EverChanged = false;
11429
11430     do {
11431       // There can be multiple store sequences on the same chain.
11432       // Keep trying to merge store sequences until we are unable to do so
11433       // or until we merge the last store on the chain.
11434       bool Changed = MergeConsecutiveStores(ST);
11435       EverChanged |= Changed;
11436       if (!Changed) break;
11437     } while (ST->getOpcode() != ISD::DELETED_NODE);
11438
11439     if (EverChanged)
11440       return SDValue(N, 0);
11441   }
11442
11443   return ReduceLoadOpStoreWidth(N);
11444 }
11445
11446 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11447   SDValue InVec = N->getOperand(0);
11448   SDValue InVal = N->getOperand(1);
11449   SDValue EltNo = N->getOperand(2);
11450   SDLoc dl(N);
11451
11452   // If the inserted element is an UNDEF, just use the input vector.
11453   if (InVal.getOpcode() == ISD::UNDEF)
11454     return InVec;
11455
11456   EVT VT = InVec.getValueType();
11457
11458   // If we can't generate a legal BUILD_VECTOR, exit
11459   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11460     return SDValue();
11461
11462   // Check that we know which element is being inserted
11463   if (!isa<ConstantSDNode>(EltNo))
11464     return SDValue();
11465   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11466
11467   // Canonicalize insert_vector_elt dag nodes.
11468   // Example:
11469   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11470   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11471   //
11472   // Do this only if the child insert_vector node has one use; also
11473   // do this only if indices are both constants and Idx1 < Idx0.
11474   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11475       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11476     unsigned OtherElt =
11477       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11478     if (Elt < OtherElt) {
11479       // Swap nodes.
11480       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11481                                   InVec.getOperand(0), InVal, EltNo);
11482       AddToWorklist(NewOp.getNode());
11483       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11484                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11485     }
11486   }
11487
11488   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11489   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11490   // vector elements.
11491   SmallVector<SDValue, 8> Ops;
11492   // Do not combine these two vectors if the output vector will not replace
11493   // the input vector.
11494   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11495     Ops.append(InVec.getNode()->op_begin(),
11496                InVec.getNode()->op_end());
11497   } else if (InVec.getOpcode() == ISD::UNDEF) {
11498     unsigned NElts = VT.getVectorNumElements();
11499     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11500   } else {
11501     return SDValue();
11502   }
11503
11504   // Insert the element
11505   if (Elt < Ops.size()) {
11506     // All the operands of BUILD_VECTOR must have the same type;
11507     // we enforce that here.
11508     EVT OpVT = Ops[0].getValueType();
11509     if (InVal.getValueType() != OpVT)
11510       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11511                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11512                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11513     Ops[Elt] = InVal;
11514   }
11515
11516   // Return the new vector
11517   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11518 }
11519
11520 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11521     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11522   EVT ResultVT = EVE->getValueType(0);
11523   EVT VecEltVT = InVecVT.getVectorElementType();
11524   unsigned Align = OriginalLoad->getAlignment();
11525   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11526       VecEltVT.getTypeForEVT(*DAG.getContext()));
11527
11528   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11529     return SDValue();
11530
11531   Align = NewAlign;
11532
11533   SDValue NewPtr = OriginalLoad->getBasePtr();
11534   SDValue Offset;
11535   EVT PtrType = NewPtr.getValueType();
11536   MachinePointerInfo MPI;
11537   SDLoc DL(EVE);
11538   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11539     int Elt = ConstEltNo->getZExtValue();
11540     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11541     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11542     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11543   } else {
11544     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11545     Offset = DAG.getNode(
11546         ISD::MUL, DL, PtrType, Offset,
11547         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11548     MPI = OriginalLoad->getPointerInfo();
11549   }
11550   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11551
11552   // The replacement we need to do here is a little tricky: we need to
11553   // replace an extractelement of a load with a load.
11554   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11555   // Note that this replacement assumes that the extractvalue is the only
11556   // use of the load; that's okay because we don't want to perform this
11557   // transformation in other cases anyway.
11558   SDValue Load;
11559   SDValue Chain;
11560   if (ResultVT.bitsGT(VecEltVT)) {
11561     // If the result type of vextract is wider than the load, then issue an
11562     // extending load instead.
11563     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11564                                                   VecEltVT)
11565                                    ? ISD::ZEXTLOAD
11566                                    : ISD::EXTLOAD;
11567     Load = DAG.getExtLoad(
11568         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11569         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11570         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11571     Chain = Load.getValue(1);
11572   } else {
11573     Load = DAG.getLoad(
11574         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11575         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11576         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11577     Chain = Load.getValue(1);
11578     if (ResultVT.bitsLT(VecEltVT))
11579       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11580     else
11581       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11582   }
11583   WorklistRemover DeadNodes(*this);
11584   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11585   SDValue To[] = { Load, Chain };
11586   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11587   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11588   // worklist explicitly as well.
11589   AddToWorklist(Load.getNode());
11590   AddUsersToWorklist(Load.getNode()); // Add users too
11591   // Make sure to revisit this node to clean it up; it will usually be dead.
11592   AddToWorklist(EVE);
11593   ++OpsNarrowed;
11594   return SDValue(EVE, 0);
11595 }
11596
11597 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11598   // (vextract (scalar_to_vector val, 0) -> val
11599   SDValue InVec = N->getOperand(0);
11600   EVT VT = InVec.getValueType();
11601   EVT NVT = N->getValueType(0);
11602
11603   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11604     // Check if the result type doesn't match the inserted element type. A
11605     // SCALAR_TO_VECTOR may truncate the inserted element and the
11606     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11607     SDValue InOp = InVec.getOperand(0);
11608     if (InOp.getValueType() != NVT) {
11609       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11610       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11611     }
11612     return InOp;
11613   }
11614
11615   SDValue EltNo = N->getOperand(1);
11616   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11617
11618   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11619   // We only perform this optimization before the op legalization phase because
11620   // we may introduce new vector instructions which are not backed by TD
11621   // patterns. For example on AVX, extracting elements from a wide vector
11622   // without using extract_subvector. However, if we can find an underlying
11623   // scalar value, then we can always use that.
11624   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11625       && ConstEltNo) {
11626     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11627     int NumElem = VT.getVectorNumElements();
11628     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11629     // Find the new index to extract from.
11630     int OrigElt = SVOp->getMaskElt(Elt);
11631
11632     // Extracting an undef index is undef.
11633     if (OrigElt == -1)
11634       return DAG.getUNDEF(NVT);
11635
11636     // Select the right vector half to extract from.
11637     SDValue SVInVec;
11638     if (OrigElt < NumElem) {
11639       SVInVec = InVec->getOperand(0);
11640     } else {
11641       SVInVec = InVec->getOperand(1);
11642       OrigElt -= NumElem;
11643     }
11644
11645     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11646       SDValue InOp = SVInVec.getOperand(OrigElt);
11647       if (InOp.getValueType() != NVT) {
11648         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11649         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11650       }
11651
11652       return InOp;
11653     }
11654
11655     // FIXME: We should handle recursing on other vector shuffles and
11656     // scalar_to_vector here as well.
11657
11658     if (!LegalOperations) {
11659       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11660       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11661                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11662     }
11663   }
11664
11665   bool BCNumEltsChanged = false;
11666   EVT ExtVT = VT.getVectorElementType();
11667   EVT LVT = ExtVT;
11668
11669   // If the result of load has to be truncated, then it's not necessarily
11670   // profitable.
11671   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11672     return SDValue();
11673
11674   if (InVec.getOpcode() == ISD::BITCAST) {
11675     // Don't duplicate a load with other uses.
11676     if (!InVec.hasOneUse())
11677       return SDValue();
11678
11679     EVT BCVT = InVec.getOperand(0).getValueType();
11680     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11681       return SDValue();
11682     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11683       BCNumEltsChanged = true;
11684     InVec = InVec.getOperand(0);
11685     ExtVT = BCVT.getVectorElementType();
11686   }
11687
11688   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11689   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11690       ISD::isNormalLoad(InVec.getNode()) &&
11691       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11692     SDValue Index = N->getOperand(1);
11693     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11694       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11695                                                            OrigLoad);
11696   }
11697
11698   // Perform only after legalization to ensure build_vector / vector_shuffle
11699   // optimizations have already been done.
11700   if (!LegalOperations) return SDValue();
11701
11702   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11703   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11704   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11705
11706   if (ConstEltNo) {
11707     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11708
11709     LoadSDNode *LN0 = nullptr;
11710     const ShuffleVectorSDNode *SVN = nullptr;
11711     if (ISD::isNormalLoad(InVec.getNode())) {
11712       LN0 = cast<LoadSDNode>(InVec);
11713     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11714                InVec.getOperand(0).getValueType() == ExtVT &&
11715                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11716       // Don't duplicate a load with other uses.
11717       if (!InVec.hasOneUse())
11718         return SDValue();
11719
11720       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11721     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11722       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11723       // =>
11724       // (load $addr+1*size)
11725
11726       // Don't duplicate a load with other uses.
11727       if (!InVec.hasOneUse())
11728         return SDValue();
11729
11730       // If the bit convert changed the number of elements, it is unsafe
11731       // to examine the mask.
11732       if (BCNumEltsChanged)
11733         return SDValue();
11734
11735       // Select the input vector, guarding against out of range extract vector.
11736       unsigned NumElems = VT.getVectorNumElements();
11737       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11738       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11739
11740       if (InVec.getOpcode() == ISD::BITCAST) {
11741         // Don't duplicate a load with other uses.
11742         if (!InVec.hasOneUse())
11743           return SDValue();
11744
11745         InVec = InVec.getOperand(0);
11746       }
11747       if (ISD::isNormalLoad(InVec.getNode())) {
11748         LN0 = cast<LoadSDNode>(InVec);
11749         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11750         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11751       }
11752     }
11753
11754     // Make sure we found a non-volatile load and the extractelement is
11755     // the only use.
11756     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11757       return SDValue();
11758
11759     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11760     if (Elt == -1)
11761       return DAG.getUNDEF(LVT);
11762
11763     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11764   }
11765
11766   return SDValue();
11767 }
11768
11769 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11770 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11771   // We perform this optimization post type-legalization because
11772   // the type-legalizer often scalarizes integer-promoted vectors.
11773   // Performing this optimization before may create bit-casts which
11774   // will be type-legalized to complex code sequences.
11775   // We perform this optimization only before the operation legalizer because we
11776   // may introduce illegal operations.
11777   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11778     return SDValue();
11779
11780   unsigned NumInScalars = N->getNumOperands();
11781   SDLoc dl(N);
11782   EVT VT = N->getValueType(0);
11783
11784   // Check to see if this is a BUILD_VECTOR of a bunch of values
11785   // which come from any_extend or zero_extend nodes. If so, we can create
11786   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11787   // optimizations. We do not handle sign-extend because we can't fill the sign
11788   // using shuffles.
11789   EVT SourceType = MVT::Other;
11790   bool AllAnyExt = true;
11791
11792   for (unsigned i = 0; i != NumInScalars; ++i) {
11793     SDValue In = N->getOperand(i);
11794     // Ignore undef inputs.
11795     if (In.getOpcode() == ISD::UNDEF) continue;
11796
11797     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11798     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11799
11800     // Abort if the element is not an extension.
11801     if (!ZeroExt && !AnyExt) {
11802       SourceType = MVT::Other;
11803       break;
11804     }
11805
11806     // The input is a ZeroExt or AnyExt. Check the original type.
11807     EVT InTy = In.getOperand(0).getValueType();
11808
11809     // Check that all of the widened source types are the same.
11810     if (SourceType == MVT::Other)
11811       // First time.
11812       SourceType = InTy;
11813     else if (InTy != SourceType) {
11814       // Multiple income types. Abort.
11815       SourceType = MVT::Other;
11816       break;
11817     }
11818
11819     // Check if all of the extends are ANY_EXTENDs.
11820     AllAnyExt &= AnyExt;
11821   }
11822
11823   // In order to have valid types, all of the inputs must be extended from the
11824   // same source type and all of the inputs must be any or zero extend.
11825   // Scalar sizes must be a power of two.
11826   EVT OutScalarTy = VT.getScalarType();
11827   bool ValidTypes = SourceType != MVT::Other &&
11828                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11829                  isPowerOf2_32(SourceType.getSizeInBits());
11830
11831   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11832   // turn into a single shuffle instruction.
11833   if (!ValidTypes)
11834     return SDValue();
11835
11836   bool isLE = DAG.getDataLayout().isLittleEndian();
11837   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11838   assert(ElemRatio > 1 && "Invalid element size ratio");
11839   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11840                                DAG.getConstant(0, SDLoc(N), SourceType);
11841
11842   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11843   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11844
11845   // Populate the new build_vector
11846   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11847     SDValue Cast = N->getOperand(i);
11848     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11849             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11850             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11851     SDValue In;
11852     if (Cast.getOpcode() == ISD::UNDEF)
11853       In = DAG.getUNDEF(SourceType);
11854     else
11855       In = Cast->getOperand(0);
11856     unsigned Index = isLE ? (i * ElemRatio) :
11857                             (i * ElemRatio + (ElemRatio - 1));
11858
11859     assert(Index < Ops.size() && "Invalid index");
11860     Ops[Index] = In;
11861   }
11862
11863   // The type of the new BUILD_VECTOR node.
11864   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11865   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11866          "Invalid vector size");
11867   // Check if the new vector type is legal.
11868   if (!isTypeLegal(VecVT)) return SDValue();
11869
11870   // Make the new BUILD_VECTOR.
11871   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11872
11873   // The new BUILD_VECTOR node has the potential to be further optimized.
11874   AddToWorklist(BV.getNode());
11875   // Bitcast to the desired type.
11876   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11877 }
11878
11879 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11880   EVT VT = N->getValueType(0);
11881
11882   unsigned NumInScalars = N->getNumOperands();
11883   SDLoc dl(N);
11884
11885   EVT SrcVT = MVT::Other;
11886   unsigned Opcode = ISD::DELETED_NODE;
11887   unsigned NumDefs = 0;
11888
11889   for (unsigned i = 0; i != NumInScalars; ++i) {
11890     SDValue In = N->getOperand(i);
11891     unsigned Opc = In.getOpcode();
11892
11893     if (Opc == ISD::UNDEF)
11894       continue;
11895
11896     // If all scalar values are floats and converted from integers.
11897     if (Opcode == ISD::DELETED_NODE &&
11898         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11899       Opcode = Opc;
11900     }
11901
11902     if (Opc != Opcode)
11903       return SDValue();
11904
11905     EVT InVT = In.getOperand(0).getValueType();
11906
11907     // If all scalar values are typed differently, bail out. It's chosen to
11908     // simplify BUILD_VECTOR of integer types.
11909     if (SrcVT == MVT::Other)
11910       SrcVT = InVT;
11911     if (SrcVT != InVT)
11912       return SDValue();
11913     NumDefs++;
11914   }
11915
11916   // If the vector has just one element defined, it's not worth to fold it into
11917   // a vectorized one.
11918   if (NumDefs < 2)
11919     return SDValue();
11920
11921   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11922          && "Should only handle conversion from integer to float.");
11923   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11924
11925   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11926
11927   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11928     return SDValue();
11929
11930   // Just because the floating-point vector type is legal does not necessarily
11931   // mean that the corresponding integer vector type is.
11932   if (!isTypeLegal(NVT))
11933     return SDValue();
11934
11935   SmallVector<SDValue, 8> Opnds;
11936   for (unsigned i = 0; i != NumInScalars; ++i) {
11937     SDValue In = N->getOperand(i);
11938
11939     if (In.getOpcode() == ISD::UNDEF)
11940       Opnds.push_back(DAG.getUNDEF(SrcVT));
11941     else
11942       Opnds.push_back(In.getOperand(0));
11943   }
11944   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11945   AddToWorklist(BV.getNode());
11946
11947   return DAG.getNode(Opcode, dl, VT, BV);
11948 }
11949
11950 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11951   unsigned NumInScalars = N->getNumOperands();
11952   SDLoc dl(N);
11953   EVT VT = N->getValueType(0);
11954
11955   // A vector built entirely of undefs is undef.
11956   if (ISD::allOperandsUndef(N))
11957     return DAG.getUNDEF(VT);
11958
11959   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11960     return V;
11961
11962   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11963     return V;
11964
11965   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11966   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11967   // at most two distinct vectors, turn this into a shuffle node.
11968
11969   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11970   if (!isTypeLegal(VT))
11971     return SDValue();
11972
11973   // May only combine to shuffle after legalize if shuffle is legal.
11974   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11975     return SDValue();
11976
11977   SDValue VecIn1, VecIn2;
11978   bool UsesZeroVector = false;
11979   for (unsigned i = 0; i != NumInScalars; ++i) {
11980     SDValue Op = N->getOperand(i);
11981     // Ignore undef inputs.
11982     if (Op.getOpcode() == ISD::UNDEF) continue;
11983
11984     // See if we can combine this build_vector into a blend with a zero vector.
11985     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11986       UsesZeroVector = true;
11987       continue;
11988     }
11989
11990     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11991     // constant index, bail out.
11992     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11993         !isa<ConstantSDNode>(Op.getOperand(1))) {
11994       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11995       break;
11996     }
11997
11998     // We allow up to two distinct input vectors.
11999     SDValue ExtractedFromVec = Op.getOperand(0);
12000     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12001       continue;
12002
12003     if (!VecIn1.getNode()) {
12004       VecIn1 = ExtractedFromVec;
12005     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12006       VecIn2 = ExtractedFromVec;
12007     } else {
12008       // Too many inputs.
12009       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12010       break;
12011     }
12012   }
12013
12014   // If everything is good, we can make a shuffle operation.
12015   if (VecIn1.getNode()) {
12016     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12017     SmallVector<int, 8> Mask;
12018     for (unsigned i = 0; i != NumInScalars; ++i) {
12019       unsigned Opcode = N->getOperand(i).getOpcode();
12020       if (Opcode == ISD::UNDEF) {
12021         Mask.push_back(-1);
12022         continue;
12023       }
12024
12025       // Operands can also be zero.
12026       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12027         assert(UsesZeroVector &&
12028                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12029                "Unexpected node found!");
12030         Mask.push_back(NumInScalars+i);
12031         continue;
12032       }
12033
12034       // If extracting from the first vector, just use the index directly.
12035       SDValue Extract = N->getOperand(i);
12036       SDValue ExtVal = Extract.getOperand(1);
12037       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12038       if (Extract.getOperand(0) == VecIn1) {
12039         Mask.push_back(ExtIndex);
12040         continue;
12041       }
12042
12043       // Otherwise, use InIdx + InputVecSize
12044       Mask.push_back(InNumElements + ExtIndex);
12045     }
12046
12047     // Avoid introducing illegal shuffles with zero.
12048     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12049       return SDValue();
12050
12051     // We can't generate a shuffle node with mismatched input and output types.
12052     // Attempt to transform a single input vector to the correct type.
12053     if ((VT != VecIn1.getValueType())) {
12054       // If the input vector type has a different base type to the output
12055       // vector type, bail out.
12056       EVT VTElemType = VT.getVectorElementType();
12057       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12058           (VecIn2.getNode() &&
12059            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12060         return SDValue();
12061
12062       // If the input vector is too small, widen it.
12063       // We only support widening of vectors which are half the size of the
12064       // output registers. For example XMM->YMM widening on X86 with AVX.
12065       EVT VecInT = VecIn1.getValueType();
12066       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12067         // If we only have one small input, widen it by adding undef values.
12068         if (!VecIn2.getNode())
12069           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12070                                DAG.getUNDEF(VecIn1.getValueType()));
12071         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12072           // If we have two small inputs of the same type, try to concat them.
12073           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12074           VecIn2 = SDValue(nullptr, 0);
12075         } else
12076           return SDValue();
12077       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12078         // If the input vector is too large, try to split it.
12079         // We don't support having two input vectors that are too large.
12080         // If the zero vector was used, we can not split the vector,
12081         // since we'd need 3 inputs.
12082         if (UsesZeroVector || VecIn2.getNode())
12083           return SDValue();
12084
12085         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12086           return SDValue();
12087
12088         // Try to replace VecIn1 with two extract_subvectors
12089         // No need to update the masks, they should still be correct.
12090         VecIn2 = DAG.getNode(
12091             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12092             DAG.getConstant(VT.getVectorNumElements(), dl,
12093                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12094         VecIn1 = DAG.getNode(
12095             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12096             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12097       } else
12098         return SDValue();
12099     }
12100
12101     if (UsesZeroVector)
12102       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12103                                 DAG.getConstantFP(0.0, dl, VT);
12104     else
12105       // If VecIn2 is unused then change it to undef.
12106       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12107
12108     // Check that we were able to transform all incoming values to the same
12109     // type.
12110     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12111         VecIn1.getValueType() != VT)
12112           return SDValue();
12113
12114     // Return the new VECTOR_SHUFFLE node.
12115     SDValue Ops[2];
12116     Ops[0] = VecIn1;
12117     Ops[1] = VecIn2;
12118     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12119   }
12120
12121   return SDValue();
12122 }
12123
12124 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12125   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12126   EVT OpVT = N->getOperand(0).getValueType();
12127
12128   // If the operands are legal vectors, leave them alone.
12129   if (TLI.isTypeLegal(OpVT))
12130     return SDValue();
12131
12132   SDLoc DL(N);
12133   EVT VT = N->getValueType(0);
12134   SmallVector<SDValue, 8> Ops;
12135
12136   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12137   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12138
12139   // Keep track of what we encounter.
12140   bool AnyInteger = false;
12141   bool AnyFP = false;
12142   for (const SDValue &Op : N->ops()) {
12143     if (ISD::BITCAST == Op.getOpcode() &&
12144         !Op.getOperand(0).getValueType().isVector())
12145       Ops.push_back(Op.getOperand(0));
12146     else if (ISD::UNDEF == Op.getOpcode())
12147       Ops.push_back(ScalarUndef);
12148     else
12149       return SDValue();
12150
12151     // Note whether we encounter an integer or floating point scalar.
12152     // If it's neither, bail out, it could be something weird like x86mmx.
12153     EVT LastOpVT = Ops.back().getValueType();
12154     if (LastOpVT.isFloatingPoint())
12155       AnyFP = true;
12156     else if (LastOpVT.isInteger())
12157       AnyInteger = true;
12158     else
12159       return SDValue();
12160   }
12161
12162   // If any of the operands is a floating point scalar bitcast to a vector,
12163   // use floating point types throughout, and bitcast everything.
12164   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12165   if (AnyFP) {
12166     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12167     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12168     if (AnyInteger) {
12169       for (SDValue &Op : Ops) {
12170         if (Op.getValueType() == SVT)
12171           continue;
12172         if (Op.getOpcode() == ISD::UNDEF)
12173           Op = ScalarUndef;
12174         else
12175           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12176       }
12177     }
12178   }
12179
12180   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12181                                VT.getSizeInBits() / SVT.getSizeInBits());
12182   return DAG.getNode(ISD::BITCAST, DL, VT,
12183                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12184 }
12185
12186 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12187   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12188   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12189   // inputs come from at most two distinct vectors, turn this into a shuffle
12190   // node.
12191
12192   // If we only have one input vector, we don't need to do any concatenation.
12193   if (N->getNumOperands() == 1)
12194     return N->getOperand(0);
12195
12196   // Check if all of the operands are undefs.
12197   EVT VT = N->getValueType(0);
12198   if (ISD::allOperandsUndef(N))
12199     return DAG.getUNDEF(VT);
12200
12201   // Optimize concat_vectors where all but the first of the vectors are undef.
12202   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12203         return Op.getOpcode() == ISD::UNDEF;
12204       })) {
12205     SDValue In = N->getOperand(0);
12206     assert(In.getValueType().isVector() && "Must concat vectors");
12207
12208     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12209     if (In->getOpcode() == ISD::BITCAST &&
12210         !In->getOperand(0)->getValueType(0).isVector()) {
12211       SDValue Scalar = In->getOperand(0);
12212
12213       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12214       // look through the trunc so we can still do the transform:
12215       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12216       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12217           !TLI.isTypeLegal(Scalar.getValueType()) &&
12218           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12219         Scalar = Scalar->getOperand(0);
12220
12221       EVT SclTy = Scalar->getValueType(0);
12222
12223       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12224         return SDValue();
12225
12226       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12227                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12228       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12229         return SDValue();
12230
12231       SDLoc dl = SDLoc(N);
12232       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12233       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12234     }
12235   }
12236
12237   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12238   // We have already tested above for an UNDEF only concatenation.
12239   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12240   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12241   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12242     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12243   };
12244   bool AllBuildVectorsOrUndefs =
12245       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12246   if (AllBuildVectorsOrUndefs) {
12247     SmallVector<SDValue, 8> Opnds;
12248     EVT SVT = VT.getScalarType();
12249
12250     EVT MinVT = SVT;
12251     if (!SVT.isFloatingPoint()) {
12252       // If BUILD_VECTOR are from built from integer, they may have different
12253       // operand types. Get the smallest type and truncate all operands to it.
12254       bool FoundMinVT = false;
12255       for (const SDValue &Op : N->ops())
12256         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12257           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12258           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12259           FoundMinVT = true;
12260         }
12261       assert(FoundMinVT && "Concat vector type mismatch");
12262     }
12263
12264     for (const SDValue &Op : N->ops()) {
12265       EVT OpVT = Op.getValueType();
12266       unsigned NumElts = OpVT.getVectorNumElements();
12267
12268       if (ISD::UNDEF == Op.getOpcode())
12269         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12270
12271       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12272         if (SVT.isFloatingPoint()) {
12273           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12274           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12275         } else {
12276           for (unsigned i = 0; i != NumElts; ++i)
12277             Opnds.push_back(
12278                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12279         }
12280       }
12281     }
12282
12283     assert(VT.getVectorNumElements() == Opnds.size() &&
12284            "Concat vector type mismatch");
12285     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12286   }
12287
12288   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12289   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12290     return V;
12291
12292   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12293   // nodes often generate nop CONCAT_VECTOR nodes.
12294   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12295   // place the incoming vectors at the exact same location.
12296   SDValue SingleSource = SDValue();
12297   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12298
12299   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12300     SDValue Op = N->getOperand(i);
12301
12302     if (Op.getOpcode() == ISD::UNDEF)
12303       continue;
12304
12305     // Check if this is the identity extract:
12306     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12307       return SDValue();
12308
12309     // Find the single incoming vector for the extract_subvector.
12310     if (SingleSource.getNode()) {
12311       if (Op.getOperand(0) != SingleSource)
12312         return SDValue();
12313     } else {
12314       SingleSource = Op.getOperand(0);
12315
12316       // Check the source type is the same as the type of the result.
12317       // If not, this concat may extend the vector, so we can not
12318       // optimize it away.
12319       if (SingleSource.getValueType() != N->getValueType(0))
12320         return SDValue();
12321     }
12322
12323     unsigned IdentityIndex = i * PartNumElem;
12324     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12325     // The extract index must be constant.
12326     if (!CS)
12327       return SDValue();
12328
12329     // Check that we are reading from the identity index.
12330     if (CS->getZExtValue() != IdentityIndex)
12331       return SDValue();
12332   }
12333
12334   if (SingleSource.getNode())
12335     return SingleSource;
12336
12337   return SDValue();
12338 }
12339
12340 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12341   EVT NVT = N->getValueType(0);
12342   SDValue V = N->getOperand(0);
12343
12344   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12345     // Combine:
12346     //    (extract_subvec (concat V1, V2, ...), i)
12347     // Into:
12348     //    Vi if possible
12349     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12350     // type.
12351     if (V->getOperand(0).getValueType() != NVT)
12352       return SDValue();
12353     unsigned Idx = N->getConstantOperandVal(1);
12354     unsigned NumElems = NVT.getVectorNumElements();
12355     assert((Idx % NumElems) == 0 &&
12356            "IDX in concat is not a multiple of the result vector length.");
12357     return V->getOperand(Idx / NumElems);
12358   }
12359
12360   // Skip bitcasting
12361   if (V->getOpcode() == ISD::BITCAST)
12362     V = V.getOperand(0);
12363
12364   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12365     SDLoc dl(N);
12366     // Handle only simple case where vector being inserted and vector
12367     // being extracted are of same type, and are half size of larger vectors.
12368     EVT BigVT = V->getOperand(0).getValueType();
12369     EVT SmallVT = V->getOperand(1).getValueType();
12370     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12371       return SDValue();
12372
12373     // Only handle cases where both indexes are constants with the same type.
12374     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12375     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12376
12377     if (InsIdx && ExtIdx &&
12378         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12379         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12380       // Combine:
12381       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12382       // Into:
12383       //    indices are equal or bit offsets are equal => V1
12384       //    otherwise => (extract_subvec V1, ExtIdx)
12385       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12386           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12387         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12388       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12389                          DAG.getNode(ISD::BITCAST, dl,
12390                                      N->getOperand(0).getValueType(),
12391                                      V->getOperand(0)), N->getOperand(1));
12392     }
12393   }
12394
12395   return SDValue();
12396 }
12397
12398 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12399                                                  SDValue V, SelectionDAG &DAG) {
12400   SDLoc DL(V);
12401   EVT VT = V.getValueType();
12402
12403   switch (V.getOpcode()) {
12404   default:
12405     return V;
12406
12407   case ISD::CONCAT_VECTORS: {
12408     EVT OpVT = V->getOperand(0).getValueType();
12409     int OpSize = OpVT.getVectorNumElements();
12410     SmallBitVector OpUsedElements(OpSize, false);
12411     bool FoundSimplification = false;
12412     SmallVector<SDValue, 4> NewOps;
12413     NewOps.reserve(V->getNumOperands());
12414     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12415       SDValue Op = V->getOperand(i);
12416       bool OpUsed = false;
12417       for (int j = 0; j < OpSize; ++j)
12418         if (UsedElements[i * OpSize + j]) {
12419           OpUsedElements[j] = true;
12420           OpUsed = true;
12421         }
12422       NewOps.push_back(
12423           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12424                  : DAG.getUNDEF(OpVT));
12425       FoundSimplification |= Op == NewOps.back();
12426       OpUsedElements.reset();
12427     }
12428     if (FoundSimplification)
12429       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12430     return V;
12431   }
12432
12433   case ISD::INSERT_SUBVECTOR: {
12434     SDValue BaseV = V->getOperand(0);
12435     SDValue SubV = V->getOperand(1);
12436     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12437     if (!IdxN)
12438       return V;
12439
12440     int SubSize = SubV.getValueType().getVectorNumElements();
12441     int Idx = IdxN->getZExtValue();
12442     bool SubVectorUsed = false;
12443     SmallBitVector SubUsedElements(SubSize, false);
12444     for (int i = 0; i < SubSize; ++i)
12445       if (UsedElements[i + Idx]) {
12446         SubVectorUsed = true;
12447         SubUsedElements[i] = true;
12448         UsedElements[i + Idx] = false;
12449       }
12450
12451     // Now recurse on both the base and sub vectors.
12452     SDValue SimplifiedSubV =
12453         SubVectorUsed
12454             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12455             : DAG.getUNDEF(SubV.getValueType());
12456     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12457     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12458       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12459                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12460     return V;
12461   }
12462   }
12463 }
12464
12465 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12466                                        SDValue N1, SelectionDAG &DAG) {
12467   EVT VT = SVN->getValueType(0);
12468   int NumElts = VT.getVectorNumElements();
12469   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12470   for (int M : SVN->getMask())
12471     if (M >= 0 && M < NumElts)
12472       N0UsedElements[M] = true;
12473     else if (M >= NumElts)
12474       N1UsedElements[M - NumElts] = true;
12475
12476   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12477   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12478   if (S0 == N0 && S1 == N1)
12479     return SDValue();
12480
12481   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12482 }
12483
12484 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12485 // or turn a shuffle of a single concat into simpler shuffle then concat.
12486 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12487   EVT VT = N->getValueType(0);
12488   unsigned NumElts = VT.getVectorNumElements();
12489
12490   SDValue N0 = N->getOperand(0);
12491   SDValue N1 = N->getOperand(1);
12492   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12493
12494   SmallVector<SDValue, 4> Ops;
12495   EVT ConcatVT = N0.getOperand(0).getValueType();
12496   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12497   unsigned NumConcats = NumElts / NumElemsPerConcat;
12498
12499   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12500   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12501   // half vector elements.
12502   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12503       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12504                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12505     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12506                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12507     N1 = DAG.getUNDEF(ConcatVT);
12508     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12509   }
12510
12511   // Look at every vector that's inserted. We're looking for exact
12512   // subvector-sized copies from a concatenated vector
12513   for (unsigned I = 0; I != NumConcats; ++I) {
12514     // Make sure we're dealing with a copy.
12515     unsigned Begin = I * NumElemsPerConcat;
12516     bool AllUndef = true, NoUndef = true;
12517     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12518       if (SVN->getMaskElt(J) >= 0)
12519         AllUndef = false;
12520       else
12521         NoUndef = false;
12522     }
12523
12524     if (NoUndef) {
12525       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12526         return SDValue();
12527
12528       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12529         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12530           return SDValue();
12531
12532       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12533       if (FirstElt < N0.getNumOperands())
12534         Ops.push_back(N0.getOperand(FirstElt));
12535       else
12536         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12537
12538     } else if (AllUndef) {
12539       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12540     } else { // Mixed with general masks and undefs, can't do optimization.
12541       return SDValue();
12542     }
12543   }
12544
12545   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12546 }
12547
12548 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12549   EVT VT = N->getValueType(0);
12550   unsigned NumElts = VT.getVectorNumElements();
12551
12552   SDValue N0 = N->getOperand(0);
12553   SDValue N1 = N->getOperand(1);
12554
12555   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12556
12557   // Canonicalize shuffle undef, undef -> undef
12558   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12559     return DAG.getUNDEF(VT);
12560
12561   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12562
12563   // Canonicalize shuffle v, v -> v, undef
12564   if (N0 == N1) {
12565     SmallVector<int, 8> NewMask;
12566     for (unsigned i = 0; i != NumElts; ++i) {
12567       int Idx = SVN->getMaskElt(i);
12568       if (Idx >= (int)NumElts) Idx -= NumElts;
12569       NewMask.push_back(Idx);
12570     }
12571     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12572                                 &NewMask[0]);
12573   }
12574
12575   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12576   if (N0.getOpcode() == ISD::UNDEF) {
12577     SmallVector<int, 8> NewMask;
12578     for (unsigned i = 0; i != NumElts; ++i) {
12579       int Idx = SVN->getMaskElt(i);
12580       if (Idx >= 0) {
12581         if (Idx >= (int)NumElts)
12582           Idx -= NumElts;
12583         else
12584           Idx = -1; // remove reference to lhs
12585       }
12586       NewMask.push_back(Idx);
12587     }
12588     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12589                                 &NewMask[0]);
12590   }
12591
12592   // Remove references to rhs if it is undef
12593   if (N1.getOpcode() == ISD::UNDEF) {
12594     bool Changed = false;
12595     SmallVector<int, 8> NewMask;
12596     for (unsigned i = 0; i != NumElts; ++i) {
12597       int Idx = SVN->getMaskElt(i);
12598       if (Idx >= (int)NumElts) {
12599         Idx = -1;
12600         Changed = true;
12601       }
12602       NewMask.push_back(Idx);
12603     }
12604     if (Changed)
12605       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12606   }
12607
12608   // If it is a splat, check if the argument vector is another splat or a
12609   // build_vector.
12610   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12611     SDNode *V = N0.getNode();
12612
12613     // If this is a bit convert that changes the element type of the vector but
12614     // not the number of vector elements, look through it.  Be careful not to
12615     // look though conversions that change things like v4f32 to v2f64.
12616     if (V->getOpcode() == ISD::BITCAST) {
12617       SDValue ConvInput = V->getOperand(0);
12618       if (ConvInput.getValueType().isVector() &&
12619           ConvInput.getValueType().getVectorNumElements() == NumElts)
12620         V = ConvInput.getNode();
12621     }
12622
12623     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12624       assert(V->getNumOperands() == NumElts &&
12625              "BUILD_VECTOR has wrong number of operands");
12626       SDValue Base;
12627       bool AllSame = true;
12628       for (unsigned i = 0; i != NumElts; ++i) {
12629         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12630           Base = V->getOperand(i);
12631           break;
12632         }
12633       }
12634       // Splat of <u, u, u, u>, return <u, u, u, u>
12635       if (!Base.getNode())
12636         return N0;
12637       for (unsigned i = 0; i != NumElts; ++i) {
12638         if (V->getOperand(i) != Base) {
12639           AllSame = false;
12640           break;
12641         }
12642       }
12643       // Splat of <x, x, x, x>, return <x, x, x, x>
12644       if (AllSame)
12645         return N0;
12646
12647       // Canonicalize any other splat as a build_vector.
12648       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12649       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12650       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12651                                   V->getValueType(0), Ops);
12652
12653       // We may have jumped through bitcasts, so the type of the
12654       // BUILD_VECTOR may not match the type of the shuffle.
12655       if (V->getValueType(0) != VT)
12656         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12657       return NewBV;
12658     }
12659   }
12660
12661   // There are various patterns used to build up a vector from smaller vectors,
12662   // subvectors, or elements. Scan chains of these and replace unused insertions
12663   // or components with undef.
12664   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12665     return S;
12666
12667   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12668       Level < AfterLegalizeVectorOps &&
12669       (N1.getOpcode() == ISD::UNDEF ||
12670       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12671        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12672     SDValue V = partitionShuffleOfConcats(N, DAG);
12673
12674     if (V.getNode())
12675       return V;
12676   }
12677
12678   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12679   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12680   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12681     SmallVector<SDValue, 8> Ops;
12682     for (int M : SVN->getMask()) {
12683       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12684       if (M >= 0) {
12685         int Idx = M % NumElts;
12686         SDValue &S = (M < (int)NumElts ? N0 : N1);
12687         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12688           Op = S.getOperand(Idx);
12689         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12690           if (Idx == 0)
12691             Op = S.getOperand(0);
12692         } else {
12693           // Operand can't be combined - bail out.
12694           break;
12695         }
12696       }
12697       Ops.push_back(Op);
12698     }
12699     if (Ops.size() == VT.getVectorNumElements()) {
12700       // BUILD_VECTOR requires all inputs to be of the same type, find the
12701       // maximum type and extend them all.
12702       EVT SVT = VT.getScalarType();
12703       if (SVT.isInteger())
12704         for (SDValue &Op : Ops)
12705           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12706       if (SVT != VT.getScalarType())
12707         for (SDValue &Op : Ops)
12708           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12709                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12710                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12711       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12712     }
12713   }
12714
12715   // If this shuffle only has a single input that is a bitcasted shuffle,
12716   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12717   // back to their original types.
12718   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12719       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12720       TLI.isTypeLegal(VT)) {
12721
12722     // Peek through the bitcast only if there is one user.
12723     SDValue BC0 = N0;
12724     while (BC0.getOpcode() == ISD::BITCAST) {
12725       if (!BC0.hasOneUse())
12726         break;
12727       BC0 = BC0.getOperand(0);
12728     }
12729
12730     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12731       if (Scale == 1)
12732         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12733
12734       SmallVector<int, 8> NewMask;
12735       for (int M : Mask)
12736         for (int s = 0; s != Scale; ++s)
12737           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12738       return NewMask;
12739     };
12740
12741     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12742       EVT SVT = VT.getScalarType();
12743       EVT InnerVT = BC0->getValueType(0);
12744       EVT InnerSVT = InnerVT.getScalarType();
12745
12746       // Determine which shuffle works with the smaller scalar type.
12747       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12748       EVT ScaleSVT = ScaleVT.getScalarType();
12749
12750       if (TLI.isTypeLegal(ScaleVT) &&
12751           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12752           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12753
12754         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12755         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12756
12757         // Scale the shuffle masks to the smaller scalar type.
12758         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12759         SmallVector<int, 8> InnerMask =
12760             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12761         SmallVector<int, 8> OuterMask =
12762             ScaleShuffleMask(SVN->getMask(), OuterScale);
12763
12764         // Merge the shuffle masks.
12765         SmallVector<int, 8> NewMask;
12766         for (int M : OuterMask)
12767           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12768
12769         // Test for shuffle mask legality over both commutations.
12770         SDValue SV0 = BC0->getOperand(0);
12771         SDValue SV1 = BC0->getOperand(1);
12772         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12773         if (!LegalMask) {
12774           std::swap(SV0, SV1);
12775           ShuffleVectorSDNode::commuteMask(NewMask);
12776           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12777         }
12778
12779         if (LegalMask) {
12780           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12781           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12782           return DAG.getNode(
12783               ISD::BITCAST, SDLoc(N), VT,
12784               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12785         }
12786       }
12787     }
12788   }
12789
12790   // Canonicalize shuffles according to rules:
12791   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12792   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12793   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12794   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12795       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12796       TLI.isTypeLegal(VT)) {
12797     // The incoming shuffle must be of the same type as the result of the
12798     // current shuffle.
12799     assert(N1->getOperand(0).getValueType() == VT &&
12800            "Shuffle types don't match");
12801
12802     SDValue SV0 = N1->getOperand(0);
12803     SDValue SV1 = N1->getOperand(1);
12804     bool HasSameOp0 = N0 == SV0;
12805     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12806     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12807       // Commute the operands of this shuffle so that next rule
12808       // will trigger.
12809       return DAG.getCommutedVectorShuffle(*SVN);
12810   }
12811
12812   // Try to fold according to rules:
12813   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12814   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12815   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12816   // Don't try to fold shuffles with illegal type.
12817   // Only fold if this shuffle is the only user of the other shuffle.
12818   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12819       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12820     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12821
12822     // The incoming shuffle must be of the same type as the result of the
12823     // current shuffle.
12824     assert(OtherSV->getOperand(0).getValueType() == VT &&
12825            "Shuffle types don't match");
12826
12827     SDValue SV0, SV1;
12828     SmallVector<int, 4> Mask;
12829     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12830     // operand, and SV1 as the second operand.
12831     for (unsigned i = 0; i != NumElts; ++i) {
12832       int Idx = SVN->getMaskElt(i);
12833       if (Idx < 0) {
12834         // Propagate Undef.
12835         Mask.push_back(Idx);
12836         continue;
12837       }
12838
12839       SDValue CurrentVec;
12840       if (Idx < (int)NumElts) {
12841         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12842         // shuffle mask to identify which vector is actually referenced.
12843         Idx = OtherSV->getMaskElt(Idx);
12844         if (Idx < 0) {
12845           // Propagate Undef.
12846           Mask.push_back(Idx);
12847           continue;
12848         }
12849
12850         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12851                                            : OtherSV->getOperand(1);
12852       } else {
12853         // This shuffle index references an element within N1.
12854         CurrentVec = N1;
12855       }
12856
12857       // Simple case where 'CurrentVec' is UNDEF.
12858       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12859         Mask.push_back(-1);
12860         continue;
12861       }
12862
12863       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12864       // will be the first or second operand of the combined shuffle.
12865       Idx = Idx % NumElts;
12866       if (!SV0.getNode() || SV0 == CurrentVec) {
12867         // Ok. CurrentVec is the left hand side.
12868         // Update the mask accordingly.
12869         SV0 = CurrentVec;
12870         Mask.push_back(Idx);
12871         continue;
12872       }
12873
12874       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12875       if (SV1.getNode() && SV1 != CurrentVec)
12876         return SDValue();
12877
12878       // Ok. CurrentVec is the right hand side.
12879       // Update the mask accordingly.
12880       SV1 = CurrentVec;
12881       Mask.push_back(Idx + NumElts);
12882     }
12883
12884     // Check if all indices in Mask are Undef. In case, propagate Undef.
12885     bool isUndefMask = true;
12886     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12887       isUndefMask &= Mask[i] < 0;
12888
12889     if (isUndefMask)
12890       return DAG.getUNDEF(VT);
12891
12892     if (!SV0.getNode())
12893       SV0 = DAG.getUNDEF(VT);
12894     if (!SV1.getNode())
12895       SV1 = DAG.getUNDEF(VT);
12896
12897     // Avoid introducing shuffles with illegal mask.
12898     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12899       ShuffleVectorSDNode::commuteMask(Mask);
12900
12901       if (!TLI.isShuffleMaskLegal(Mask, VT))
12902         return SDValue();
12903
12904       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12905       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12906       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12907       std::swap(SV0, SV1);
12908     }
12909
12910     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12911     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12912     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12913     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12914   }
12915
12916   return SDValue();
12917 }
12918
12919 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12920   SDValue InVal = N->getOperand(0);
12921   EVT VT = N->getValueType(0);
12922
12923   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12924   // with a VECTOR_SHUFFLE.
12925   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12926     SDValue InVec = InVal->getOperand(0);
12927     SDValue EltNo = InVal->getOperand(1);
12928
12929     // FIXME: We could support implicit truncation if the shuffle can be
12930     // scaled to a smaller vector scalar type.
12931     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12932     if (C0 && VT == InVec.getValueType() &&
12933         VT.getScalarType() == InVal.getValueType()) {
12934       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12935       int Elt = C0->getZExtValue();
12936       NewMask[0] = Elt;
12937
12938       if (TLI.isShuffleMaskLegal(NewMask, VT))
12939         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12940                                     NewMask);
12941     }
12942   }
12943
12944   return SDValue();
12945 }
12946
12947 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12948   SDValue N0 = N->getOperand(0);
12949   SDValue N2 = N->getOperand(2);
12950
12951   // If the input vector is a concatenation, and the insert replaces
12952   // one of the halves, we can optimize into a single concat_vectors.
12953   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12954       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12955     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12956     EVT VT = N->getValueType(0);
12957
12958     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12959     // (concat_vectors Z, Y)
12960     if (InsIdx == 0)
12961       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12962                          N->getOperand(1), N0.getOperand(1));
12963
12964     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12965     // (concat_vectors X, Z)
12966     if (InsIdx == VT.getVectorNumElements()/2)
12967       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12968                          N0.getOperand(0), N->getOperand(1));
12969   }
12970
12971   return SDValue();
12972 }
12973
12974 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12975   SDValue N0 = N->getOperand(0);
12976
12977   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12978   if (N0->getOpcode() == ISD::FP16_TO_FP)
12979     return N0->getOperand(0);
12980
12981   return SDValue();
12982 }
12983
12984 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12985 /// with the destination vector and a zero vector.
12986 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12987 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12988 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12989   EVT VT = N->getValueType(0);
12990   SDValue LHS = N->getOperand(0);
12991   SDValue RHS = N->getOperand(1);
12992   SDLoc dl(N);
12993
12994   // Make sure we're not running after operation legalization where it
12995   // may have custom lowered the vector shuffles.
12996   if (LegalOperations)
12997     return SDValue();
12998
12999   if (N->getOpcode() != ISD::AND)
13000     return SDValue();
13001
13002   if (RHS.getOpcode() == ISD::BITCAST)
13003     RHS = RHS.getOperand(0);
13004
13005   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13006     return SDValue();
13007
13008   EVT RVT = RHS.getValueType();
13009   unsigned NumElts = RHS.getNumOperands();
13010
13011   // Attempt to create a valid clear mask, splitting the mask into
13012   // sub elements and checking to see if each is
13013   // all zeros or all ones - suitable for shuffle masking.
13014   auto BuildClearMask = [&](int Split) {
13015     int NumSubElts = NumElts * Split;
13016     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13017
13018     SmallVector<int, 8> Indices;
13019     for (int i = 0; i != NumSubElts; ++i) {
13020       int EltIdx = i / Split;
13021       int SubIdx = i % Split;
13022       SDValue Elt = RHS.getOperand(EltIdx);
13023       if (Elt.getOpcode() == ISD::UNDEF) {
13024         Indices.push_back(-1);
13025         continue;
13026       }
13027
13028       APInt Bits;
13029       if (isa<ConstantSDNode>(Elt))
13030         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13031       else if (isa<ConstantFPSDNode>(Elt))
13032         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13033       else
13034         return SDValue();
13035
13036       // Extract the sub element from the constant bit mask.
13037       if (DAG.getDataLayout().isBigEndian()) {
13038         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13039       } else {
13040         Bits = Bits.lshr(SubIdx * NumSubBits);
13041       }
13042
13043       if (Split > 1)
13044         Bits = Bits.trunc(NumSubBits);
13045
13046       if (Bits.isAllOnesValue())
13047         Indices.push_back(i);
13048       else if (Bits == 0)
13049         Indices.push_back(i + NumSubElts);
13050       else
13051         return SDValue();
13052     }
13053
13054     // Let's see if the target supports this vector_shuffle.
13055     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13056     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13057     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13058       return SDValue();
13059
13060     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13061     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13062                                                    DAG.getBitcast(ClearVT, LHS),
13063                                                    Zero, &Indices[0]));
13064   };
13065
13066   // Determine maximum split level (byte level masking).
13067   int MaxSplit = 1;
13068   if (RVT.getScalarSizeInBits() % 8 == 0)
13069     MaxSplit = RVT.getScalarSizeInBits() / 8;
13070
13071   for (int Split = 1; Split <= MaxSplit; ++Split)
13072     if (RVT.getScalarSizeInBits() % Split == 0)
13073       if (SDValue S = BuildClearMask(Split))
13074         return S;
13075
13076   return SDValue();
13077 }
13078
13079 /// Visit a binary vector operation, like ADD.
13080 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13081   assert(N->getValueType(0).isVector() &&
13082          "SimplifyVBinOp only works on vectors!");
13083
13084   SDValue LHS = N->getOperand(0);
13085   SDValue RHS = N->getOperand(1);
13086
13087   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13088   // this operation.
13089   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13090       RHS.getOpcode() == ISD::BUILD_VECTOR) {
13091     // Check if both vectors are constants. If not bail out.
13092     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13093           cast<BuildVectorSDNode>(RHS)->isConstant()))
13094       return SDValue();
13095
13096     SmallVector<SDValue, 8> Ops;
13097     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13098       SDValue LHSOp = LHS.getOperand(i);
13099       SDValue RHSOp = RHS.getOperand(i);
13100
13101       // Can't fold divide by zero.
13102       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13103           N->getOpcode() == ISD::FDIV) {
13104         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13105              cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13106           break;
13107       }
13108
13109       EVT VT = LHSOp.getValueType();
13110       EVT RVT = RHSOp.getValueType();
13111       if (RVT != VT) {
13112         // Integer BUILD_VECTOR operands may have types larger than the element
13113         // size (e.g., when the element type is not legal).  Prior to type
13114         // legalization, the types may not match between the two BUILD_VECTORS.
13115         // Truncate one of the operands to make them match.
13116         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13117           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13118         } else {
13119           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13120           VT = RVT;
13121         }
13122       }
13123       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13124                                    LHSOp, RHSOp);
13125       if (FoldOp.getOpcode() != ISD::UNDEF &&
13126           FoldOp.getOpcode() != ISD::Constant &&
13127           FoldOp.getOpcode() != ISD::ConstantFP)
13128         break;
13129       Ops.push_back(FoldOp);
13130       AddToWorklist(FoldOp.getNode());
13131     }
13132
13133     if (Ops.size() == LHS.getNumOperands())
13134       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13135   }
13136
13137   // Try to convert a constant mask AND into a shuffle clear mask.
13138   if (SDValue Shuffle = XformToShuffleWithZero(N))
13139     return Shuffle;
13140
13141   // Type legalization might introduce new shuffles in the DAG.
13142   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13143   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13144   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13145       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13146       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13147       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13148     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13149     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13150
13151     if (SVN0->getMask().equals(SVN1->getMask())) {
13152       EVT VT = N->getValueType(0);
13153       SDValue UndefVector = LHS.getOperand(1);
13154       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13155                                      LHS.getOperand(0), RHS.getOperand(0));
13156       AddUsersToWorklist(N);
13157       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13158                                   &SVN0->getMask()[0]);
13159     }
13160   }
13161
13162   return SDValue();
13163 }
13164
13165 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13166                                     SDValue N1, SDValue N2){
13167   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13168
13169   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13170                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13171
13172   // If we got a simplified select_cc node back from SimplifySelectCC, then
13173   // break it down into a new SETCC node, and a new SELECT node, and then return
13174   // the SELECT node, since we were called with a SELECT node.
13175   if (SCC.getNode()) {
13176     // Check to see if we got a select_cc back (to turn into setcc/select).
13177     // Otherwise, just return whatever node we got back, like fabs.
13178     if (SCC.getOpcode() == ISD::SELECT_CC) {
13179       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13180                                   N0.getValueType(),
13181                                   SCC.getOperand(0), SCC.getOperand(1),
13182                                   SCC.getOperand(4));
13183       AddToWorklist(SETCC.getNode());
13184       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13185                            SCC.getOperand(2), SCC.getOperand(3));
13186     }
13187
13188     return SCC;
13189   }
13190   return SDValue();
13191 }
13192
13193 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13194 /// being selected between, see if we can simplify the select.  Callers of this
13195 /// should assume that TheSelect is deleted if this returns true.  As such, they
13196 /// should return the appropriate thing (e.g. the node) back to the top-level of
13197 /// the DAG combiner loop to avoid it being looked at.
13198 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13199                                     SDValue RHS) {
13200
13201   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13202   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13203   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13204     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13205       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13206       SDValue Sqrt = RHS;
13207       ISD::CondCode CC;
13208       SDValue CmpLHS;
13209       const ConstantFPSDNode *NegZero = nullptr;
13210
13211       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13212         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13213         CmpLHS = TheSelect->getOperand(0);
13214         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13215       } else {
13216         // SELECT or VSELECT
13217         SDValue Cmp = TheSelect->getOperand(0);
13218         if (Cmp.getOpcode() == ISD::SETCC) {
13219           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13220           CmpLHS = Cmp.getOperand(0);
13221           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13222         }
13223       }
13224       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13225           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13226           CC == ISD::SETULT || CC == ISD::SETLT)) {
13227         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13228         CombineTo(TheSelect, Sqrt);
13229         return true;
13230       }
13231     }
13232   }
13233   // Cannot simplify select with vector condition
13234   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13235
13236   // If this is a select from two identical things, try to pull the operation
13237   // through the select.
13238   if (LHS.getOpcode() != RHS.getOpcode() ||
13239       !LHS.hasOneUse() || !RHS.hasOneUse())
13240     return false;
13241
13242   // If this is a load and the token chain is identical, replace the select
13243   // of two loads with a load through a select of the address to load from.
13244   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13245   // constants have been dropped into the constant pool.
13246   if (LHS.getOpcode() == ISD::LOAD) {
13247     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13248     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13249
13250     // Token chains must be identical.
13251     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13252         // Do not let this transformation reduce the number of volatile loads.
13253         LLD->isVolatile() || RLD->isVolatile() ||
13254         // FIXME: If either is a pre/post inc/dec load,
13255         // we'd need to split out the address adjustment.
13256         LLD->isIndexed() || RLD->isIndexed() ||
13257         // If this is an EXTLOAD, the VT's must match.
13258         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13259         // If this is an EXTLOAD, the kind of extension must match.
13260         (LLD->getExtensionType() != RLD->getExtensionType() &&
13261          // The only exception is if one of the extensions is anyext.
13262          LLD->getExtensionType() != ISD::EXTLOAD &&
13263          RLD->getExtensionType() != ISD::EXTLOAD) ||
13264         // FIXME: this discards src value information.  This is
13265         // over-conservative. It would be beneficial to be able to remember
13266         // both potential memory locations.  Since we are discarding
13267         // src value info, don't do the transformation if the memory
13268         // locations are not in the default address space.
13269         LLD->getPointerInfo().getAddrSpace() != 0 ||
13270         RLD->getPointerInfo().getAddrSpace() != 0 ||
13271         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13272                                       LLD->getBasePtr().getValueType()))
13273       return false;
13274
13275     // Check that the select condition doesn't reach either load.  If so,
13276     // folding this will induce a cycle into the DAG.  If not, this is safe to
13277     // xform, so create a select of the addresses.
13278     SDValue Addr;
13279     if (TheSelect->getOpcode() == ISD::SELECT) {
13280       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13281       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13282           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13283         return false;
13284       // The loads must not depend on one another.
13285       if (LLD->isPredecessorOf(RLD) ||
13286           RLD->isPredecessorOf(LLD))
13287         return false;
13288       Addr = DAG.getSelect(SDLoc(TheSelect),
13289                            LLD->getBasePtr().getValueType(),
13290                            TheSelect->getOperand(0), LLD->getBasePtr(),
13291                            RLD->getBasePtr());
13292     } else {  // Otherwise SELECT_CC
13293       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13294       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13295
13296       if ((LLD->hasAnyUseOfValue(1) &&
13297            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13298           (RLD->hasAnyUseOfValue(1) &&
13299            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13300         return false;
13301
13302       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13303                          LLD->getBasePtr().getValueType(),
13304                          TheSelect->getOperand(0),
13305                          TheSelect->getOperand(1),
13306                          LLD->getBasePtr(), RLD->getBasePtr(),
13307                          TheSelect->getOperand(4));
13308     }
13309
13310     SDValue Load;
13311     // It is safe to replace the two loads if they have different alignments,
13312     // but the new load must be the minimum (most restrictive) alignment of the
13313     // inputs.
13314     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13315     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13316     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13317       Load = DAG.getLoad(TheSelect->getValueType(0),
13318                          SDLoc(TheSelect),
13319                          // FIXME: Discards pointer and AA info.
13320                          LLD->getChain(), Addr, MachinePointerInfo(),
13321                          LLD->isVolatile(), LLD->isNonTemporal(),
13322                          isInvariant, Alignment);
13323     } else {
13324       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13325                             RLD->getExtensionType() : LLD->getExtensionType(),
13326                             SDLoc(TheSelect),
13327                             TheSelect->getValueType(0),
13328                             // FIXME: Discards pointer and AA info.
13329                             LLD->getChain(), Addr, MachinePointerInfo(),
13330                             LLD->getMemoryVT(), LLD->isVolatile(),
13331                             LLD->isNonTemporal(), isInvariant, Alignment);
13332     }
13333
13334     // Users of the select now use the result of the load.
13335     CombineTo(TheSelect, Load);
13336
13337     // Users of the old loads now use the new load's chain.  We know the
13338     // old-load value is dead now.
13339     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13340     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13341     return true;
13342   }
13343
13344   return false;
13345 }
13346
13347 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13348 /// where 'cond' is the comparison specified by CC.
13349 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13350                                       SDValue N2, SDValue N3,
13351                                       ISD::CondCode CC, bool NotExtCompare) {
13352   // (x ? y : y) -> y.
13353   if (N2 == N3) return N2;
13354
13355   EVT VT = N2.getValueType();
13356   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13357   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13358
13359   // Determine if the condition we're dealing with is constant
13360   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13361                               N0, N1, CC, DL, false);
13362   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13363
13364   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13365     // fold select_cc true, x, y -> x
13366     // fold select_cc false, x, y -> y
13367     return !SCCC->isNullValue() ? N2 : N3;
13368   }
13369
13370   // Check to see if we can simplify the select into an fabs node
13371   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13372     // Allow either -0.0 or 0.0
13373     if (CFP->isZero()) {
13374       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13375       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13376           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13377           N2 == N3.getOperand(0))
13378         return DAG.getNode(ISD::FABS, DL, VT, N0);
13379
13380       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13381       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13382           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13383           N2.getOperand(0) == N3)
13384         return DAG.getNode(ISD::FABS, DL, VT, N3);
13385     }
13386   }
13387
13388   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13389   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13390   // in it.  This is a win when the constant is not otherwise available because
13391   // it replaces two constant pool loads with one.  We only do this if the FP
13392   // type is known to be legal, because if it isn't, then we are before legalize
13393   // types an we want the other legalization to happen first (e.g. to avoid
13394   // messing with soft float) and if the ConstantFP is not legal, because if
13395   // it is legal, we may not need to store the FP constant in a constant pool.
13396   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13397     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13398       if (TLI.isTypeLegal(N2.getValueType()) &&
13399           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13400                TargetLowering::Legal &&
13401            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13402            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13403           // If both constants have multiple uses, then we won't need to do an
13404           // extra load, they are likely around in registers for other users.
13405           (TV->hasOneUse() || FV->hasOneUse())) {
13406         Constant *Elts[] = {
13407           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13408           const_cast<ConstantFP*>(TV->getConstantFPValue())
13409         };
13410         Type *FPTy = Elts[0]->getType();
13411         const DataLayout &TD = DAG.getDataLayout();
13412
13413         // Create a ConstantArray of the two constants.
13414         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13415         SDValue CPIdx =
13416             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13417                                 TD.getPrefTypeAlignment(FPTy));
13418         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13419
13420         // Get the offsets to the 0 and 1 element of the array so that we can
13421         // select between them.
13422         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13423         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13424         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13425
13426         SDValue Cond = DAG.getSetCC(DL,
13427                                     getSetCCResultType(N0.getValueType()),
13428                                     N0, N1, CC);
13429         AddToWorklist(Cond.getNode());
13430         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13431                                           Cond, One, Zero);
13432         AddToWorklist(CstOffset.getNode());
13433         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13434                             CstOffset);
13435         AddToWorklist(CPIdx.getNode());
13436         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13437                            MachinePointerInfo::getConstantPool(), false,
13438                            false, false, Alignment);
13439       }
13440     }
13441
13442   // Check to see if we can perform the "gzip trick", transforming
13443   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13444   if (isNullConstant(N3) && CC == ISD::SETLT &&
13445       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13446        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13447     EVT XType = N0.getValueType();
13448     EVT AType = N2.getValueType();
13449     if (XType.bitsGE(AType)) {
13450       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13451       // single-bit constant.
13452       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13453         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13454         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13455         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13456                                        getShiftAmountTy(N0.getValueType()));
13457         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13458                                     XType, N0, ShCt);
13459         AddToWorklist(Shift.getNode());
13460
13461         if (XType.bitsGT(AType)) {
13462           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13463           AddToWorklist(Shift.getNode());
13464         }
13465
13466         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13467       }
13468
13469       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13470                                   XType, N0,
13471                                   DAG.getConstant(XType.getSizeInBits() - 1,
13472                                                   SDLoc(N0),
13473                                          getShiftAmountTy(N0.getValueType())));
13474       AddToWorklist(Shift.getNode());
13475
13476       if (XType.bitsGT(AType)) {
13477         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13478         AddToWorklist(Shift.getNode());
13479       }
13480
13481       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13482     }
13483   }
13484
13485   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13486   // where y is has a single bit set.
13487   // A plaintext description would be, we can turn the SELECT_CC into an AND
13488   // when the condition can be materialized as an all-ones register.  Any
13489   // single bit-test can be materialized as an all-ones register with
13490   // shift-left and shift-right-arith.
13491   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13492       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13493     SDValue AndLHS = N0->getOperand(0);
13494     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13495     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13496       // Shift the tested bit over the sign bit.
13497       APInt AndMask = ConstAndRHS->getAPIntValue();
13498       SDValue ShlAmt =
13499         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13500                         getShiftAmountTy(AndLHS.getValueType()));
13501       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13502
13503       // Now arithmetic right shift it all the way over, so the result is either
13504       // all-ones, or zero.
13505       SDValue ShrAmt =
13506         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13507                         getShiftAmountTy(Shl.getValueType()));
13508       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13509
13510       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13511     }
13512   }
13513
13514   // fold select C, 16, 0 -> shl C, 4
13515   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13516       TLI.getBooleanContents(N0.getValueType()) ==
13517           TargetLowering::ZeroOrOneBooleanContent) {
13518
13519     // If the caller doesn't want us to simplify this into a zext of a compare,
13520     // don't do it.
13521     if (NotExtCompare && N2C->isOne())
13522       return SDValue();
13523
13524     // Get a SetCC of the condition
13525     // NOTE: Don't create a SETCC if it's not legal on this target.
13526     if (!LegalOperations ||
13527         TLI.isOperationLegal(ISD::SETCC,
13528           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13529       SDValue Temp, SCC;
13530       // cast from setcc result type to select result type
13531       if (LegalTypes) {
13532         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13533                             N0, N1, CC);
13534         if (N2.getValueType().bitsLT(SCC.getValueType()))
13535           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13536                                         N2.getValueType());
13537         else
13538           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13539                              N2.getValueType(), SCC);
13540       } else {
13541         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13542         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13543                            N2.getValueType(), SCC);
13544       }
13545
13546       AddToWorklist(SCC.getNode());
13547       AddToWorklist(Temp.getNode());
13548
13549       if (N2C->isOne())
13550         return Temp;
13551
13552       // shl setcc result by log2 n2c
13553       return DAG.getNode(
13554           ISD::SHL, DL, N2.getValueType(), Temp,
13555           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13556                           getShiftAmountTy(Temp.getValueType())));
13557     }
13558   }
13559
13560   // Check to see if this is the equivalent of setcc
13561   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13562   // otherwise, go ahead with the folds.
13563   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13564     EVT XType = N0.getValueType();
13565     if (!LegalOperations ||
13566         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13567       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13568       if (Res.getValueType() != VT)
13569         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13570       return Res;
13571     }
13572
13573     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13574     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13575         (!LegalOperations ||
13576          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13577       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13578       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13579                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13580                                          SDLoc(Ctlz),
13581                                        getShiftAmountTy(Ctlz.getValueType())));
13582     }
13583     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13584     if (isNullConstant(N1) && CC == ISD::SETGT) {
13585       SDLoc DL(N0);
13586       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13587                                   XType, DAG.getConstant(0, DL, XType), N0);
13588       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13589       return DAG.getNode(ISD::SRL, DL, XType,
13590                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13591                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13592                                          getShiftAmountTy(XType)));
13593     }
13594     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13595     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13596       SDLoc DL(N0);
13597       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13598                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13599                                          getShiftAmountTy(N0.getValueType())));
13600       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13601                                                                     XType));
13602     }
13603   }
13604
13605   // Check to see if this is an integer abs.
13606   // select_cc setg[te] X,  0,  X, -X ->
13607   // select_cc setgt    X, -1,  X, -X ->
13608   // select_cc setl[te] X,  0, -X,  X ->
13609   // select_cc setlt    X,  1, -X,  X ->
13610   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13611   if (N1C) {
13612     ConstantSDNode *SubC = nullptr;
13613     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13614          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13615         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13616       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13617     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13618               (N1C->isOne() && CC == ISD::SETLT)) &&
13619              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13620       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13621
13622     EVT XType = N0.getValueType();
13623     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13624       SDLoc DL(N0);
13625       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13626                                   N0,
13627                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13628                                          getShiftAmountTy(N0.getValueType())));
13629       SDValue Add = DAG.getNode(ISD::ADD, DL,
13630                                 XType, N0, Shift);
13631       AddToWorklist(Shift.getNode());
13632       AddToWorklist(Add.getNode());
13633       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13634     }
13635   }
13636
13637   return SDValue();
13638 }
13639
13640 /// This is a stub for TargetLowering::SimplifySetCC.
13641 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13642                                    SDValue N1, ISD::CondCode Cond,
13643                                    SDLoc DL, bool foldBooleans) {
13644   TargetLowering::DAGCombinerInfo
13645     DagCombineInfo(DAG, Level, false, this);
13646   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13647 }
13648
13649 /// Given an ISD::SDIV node expressing a divide by constant, return
13650 /// a DAG expression to select that will generate the same value by multiplying
13651 /// by a magic number.
13652 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13653 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13654   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13655   if (!C)
13656     return SDValue();
13657
13658   // Avoid division by zero.
13659   if (C->isNullValue())
13660     return SDValue();
13661
13662   std::vector<SDNode*> Built;
13663   SDValue S =
13664       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13665
13666   for (SDNode *N : Built)
13667     AddToWorklist(N);
13668   return S;
13669 }
13670
13671 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13672 /// DAG expression that will generate the same value by right shifting.
13673 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13674   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13675   if (!C)
13676     return SDValue();
13677
13678   // Avoid division by zero.
13679   if (C->isNullValue())
13680     return SDValue();
13681
13682   std::vector<SDNode *> Built;
13683   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13684
13685   for (SDNode *N : Built)
13686     AddToWorklist(N);
13687   return S;
13688 }
13689
13690 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13691 /// expression that will generate the same value by multiplying by a magic
13692 /// number.
13693 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13694 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13695   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13696   if (!C)
13697     return SDValue();
13698
13699   // Avoid division by zero.
13700   if (C->isNullValue())
13701     return SDValue();
13702
13703   std::vector<SDNode*> Built;
13704   SDValue S =
13705       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13706
13707   for (SDNode *N : Built)
13708     AddToWorklist(N);
13709   return S;
13710 }
13711
13712 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13713   if (Level >= AfterLegalizeDAG)
13714     return SDValue();
13715
13716   // Expose the DAG combiner to the target combiner implementations.
13717   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13718
13719   unsigned Iterations = 0;
13720   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13721     if (Iterations) {
13722       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13723       // For the reciprocal, we need to find the zero of the function:
13724       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13725       //     =>
13726       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13727       //     does not require additional intermediate precision]
13728       EVT VT = Op.getValueType();
13729       SDLoc DL(Op);
13730       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13731
13732       AddToWorklist(Est.getNode());
13733
13734       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13735       for (unsigned i = 0; i < Iterations; ++i) {
13736         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13737         AddToWorklist(NewEst.getNode());
13738
13739         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13740         AddToWorklist(NewEst.getNode());
13741
13742         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13743         AddToWorklist(NewEst.getNode());
13744
13745         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13746         AddToWorklist(Est.getNode());
13747       }
13748     }
13749     return Est;
13750   }
13751
13752   return SDValue();
13753 }
13754
13755 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13756 /// For the reciprocal sqrt, we need to find the zero of the function:
13757 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13758 ///     =>
13759 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13760 /// As a result, we precompute A/2 prior to the iteration loop.
13761 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13762                                           unsigned Iterations) {
13763   EVT VT = Arg.getValueType();
13764   SDLoc DL(Arg);
13765   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13766
13767   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13768   // this entire sequence requires only one FP constant.
13769   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13770   AddToWorklist(HalfArg.getNode());
13771
13772   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13773   AddToWorklist(HalfArg.getNode());
13774
13775   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13776   for (unsigned i = 0; i < Iterations; ++i) {
13777     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13778     AddToWorklist(NewEst.getNode());
13779
13780     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13781     AddToWorklist(NewEst.getNode());
13782
13783     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13784     AddToWorklist(NewEst.getNode());
13785
13786     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13787     AddToWorklist(Est.getNode());
13788   }
13789   return Est;
13790 }
13791
13792 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13793 /// For the reciprocal sqrt, we need to find the zero of the function:
13794 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13795 ///     =>
13796 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13797 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13798                                           unsigned Iterations) {
13799   EVT VT = Arg.getValueType();
13800   SDLoc DL(Arg);
13801   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13802   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13803
13804   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13805   for (unsigned i = 0; i < Iterations; ++i) {
13806     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13807     AddToWorklist(HalfEst.getNode());
13808
13809     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13810     AddToWorklist(Est.getNode());
13811
13812     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13813     AddToWorklist(Est.getNode());
13814
13815     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13816     AddToWorklist(Est.getNode());
13817
13818     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13819     AddToWorklist(Est.getNode());
13820   }
13821   return Est;
13822 }
13823
13824 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13825   if (Level >= AfterLegalizeDAG)
13826     return SDValue();
13827
13828   // Expose the DAG combiner to the target combiner implementations.
13829   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13830   unsigned Iterations = 0;
13831   bool UseOneConstNR = false;
13832   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13833     AddToWorklist(Est.getNode());
13834     if (Iterations) {
13835       Est = UseOneConstNR ?
13836         BuildRsqrtNROneConst(Op, Est, Iterations) :
13837         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13838     }
13839     return Est;
13840   }
13841
13842   return SDValue();
13843 }
13844
13845 /// Return true if base is a frame index, which is known not to alias with
13846 /// anything but itself.  Provides base object and offset as results.
13847 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13848                            const GlobalValue *&GV, const void *&CV) {
13849   // Assume it is a primitive operation.
13850   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13851
13852   // If it's an adding a simple constant then integrate the offset.
13853   if (Base.getOpcode() == ISD::ADD) {
13854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13855       Base = Base.getOperand(0);
13856       Offset += C->getZExtValue();
13857     }
13858   }
13859
13860   // Return the underlying GlobalValue, and update the Offset.  Return false
13861   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13862   // by multiple nodes with different offsets.
13863   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13864     GV = G->getGlobal();
13865     Offset += G->getOffset();
13866     return false;
13867   }
13868
13869   // Return the underlying Constant value, and update the Offset.  Return false
13870   // for ConstantSDNodes since the same constant pool entry may be represented
13871   // by multiple nodes with different offsets.
13872   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13873     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13874                                          : (const void *)C->getConstVal();
13875     Offset += C->getOffset();
13876     return false;
13877   }
13878   // If it's any of the following then it can't alias with anything but itself.
13879   return isa<FrameIndexSDNode>(Base);
13880 }
13881
13882 /// Return true if there is any possibility that the two addresses overlap.
13883 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13884   // If they are the same then they must be aliases.
13885   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13886
13887   // If they are both volatile then they cannot be reordered.
13888   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13889
13890   // If one operation reads from invariant memory, and the other may store, they
13891   // cannot alias. These should really be checking the equivalent of mayWrite,
13892   // but it only matters for memory nodes other than load /store.
13893   if (Op0->isInvariant() && Op1->writeMem())
13894     return false;
13895
13896   if (Op1->isInvariant() && Op0->writeMem())
13897     return false;
13898
13899   // Gather base node and offset information.
13900   SDValue Base1, Base2;
13901   int64_t Offset1, Offset2;
13902   const GlobalValue *GV1, *GV2;
13903   const void *CV1, *CV2;
13904   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13905                                       Base1, Offset1, GV1, CV1);
13906   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13907                                       Base2, Offset2, GV2, CV2);
13908
13909   // If they have a same base address then check to see if they overlap.
13910   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13911     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13912              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13913
13914   // It is possible for different frame indices to alias each other, mostly
13915   // when tail call optimization reuses return address slots for arguments.
13916   // To catch this case, look up the actual index of frame indices to compute
13917   // the real alias relationship.
13918   if (isFrameIndex1 && isFrameIndex2) {
13919     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13920     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13921     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13922     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13923              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13924   }
13925
13926   // Otherwise, if we know what the bases are, and they aren't identical, then
13927   // we know they cannot alias.
13928   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13929     return false;
13930
13931   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13932   // compared to the size and offset of the access, we may be able to prove they
13933   // do not alias.  This check is conservative for now to catch cases created by
13934   // splitting vector types.
13935   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13936       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13937       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13938        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13939       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13940     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13941     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13942
13943     // There is no overlap between these relatively aligned accesses of similar
13944     // size, return no alias.
13945     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13946         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13947       return false;
13948   }
13949
13950   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13951                    ? CombinerGlobalAA
13952                    : DAG.getSubtarget().useAA();
13953 #ifndef NDEBUG
13954   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13955       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13956     UseAA = false;
13957 #endif
13958   if (UseAA &&
13959       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13960     // Use alias analysis information.
13961     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13962                                  Op1->getSrcValueOffset());
13963     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13964         Op0->getSrcValueOffset() - MinOffset;
13965     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13966         Op1->getSrcValueOffset() - MinOffset;
13967     AliasResult AAResult =
13968         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
13969                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13970                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
13971                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13972     if (AAResult == NoAlias)
13973       return false;
13974   }
13975
13976   // Otherwise we have to assume they alias.
13977   return true;
13978 }
13979
13980 /// Walk up chain skipping non-aliasing memory nodes,
13981 /// looking for aliasing nodes and adding them to the Aliases vector.
13982 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13983                                    SmallVectorImpl<SDValue> &Aliases) {
13984   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13985   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13986
13987   // Get alias information for node.
13988   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13989
13990   // Starting off.
13991   Chains.push_back(OriginalChain);
13992   unsigned Depth = 0;
13993
13994   // Look at each chain and determine if it is an alias.  If so, add it to the
13995   // aliases list.  If not, then continue up the chain looking for the next
13996   // candidate.
13997   while (!Chains.empty()) {
13998     SDValue Chain = Chains.pop_back_val();
13999
14000     // For TokenFactor nodes, look at each operand and only continue up the
14001     // chain until we find two aliases.  If we've seen two aliases, assume we'll
14002     // find more and revert to original chain since the xform is unlikely to be
14003     // profitable.
14004     //
14005     // FIXME: The depth check could be made to return the last non-aliasing
14006     // chain we found before we hit a tokenfactor rather than the original
14007     // chain.
14008     if (Depth > 6 || Aliases.size() == 2) {
14009       Aliases.clear();
14010       Aliases.push_back(OriginalChain);
14011       return;
14012     }
14013
14014     // Don't bother if we've been before.
14015     if (!Visited.insert(Chain.getNode()).second)
14016       continue;
14017
14018     switch (Chain.getOpcode()) {
14019     case ISD::EntryToken:
14020       // Entry token is ideal chain operand, but handled in FindBetterChain.
14021       break;
14022
14023     case ISD::LOAD:
14024     case ISD::STORE: {
14025       // Get alias information for Chain.
14026       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14027           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14028
14029       // If chain is alias then stop here.
14030       if (!(IsLoad && IsOpLoad) &&
14031           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14032         Aliases.push_back(Chain);
14033       } else {
14034         // Look further up the chain.
14035         Chains.push_back(Chain.getOperand(0));
14036         ++Depth;
14037       }
14038       break;
14039     }
14040
14041     case ISD::TokenFactor:
14042       // We have to check each of the operands of the token factor for "small"
14043       // token factors, so we queue them up.  Adding the operands to the queue
14044       // (stack) in reverse order maintains the original order and increases the
14045       // likelihood that getNode will find a matching token factor (CSE.)
14046       if (Chain.getNumOperands() > 16) {
14047         Aliases.push_back(Chain);
14048         break;
14049       }
14050       for (unsigned n = Chain.getNumOperands(); n;)
14051         Chains.push_back(Chain.getOperand(--n));
14052       ++Depth;
14053       break;
14054
14055     default:
14056       // For all other instructions we will just have to take what we can get.
14057       Aliases.push_back(Chain);
14058       break;
14059     }
14060   }
14061
14062   // We need to be careful here to also search for aliases through the
14063   // value operand of a store, etc. Consider the following situation:
14064   //   Token1 = ...
14065   //   L1 = load Token1, %52
14066   //   S1 = store Token1, L1, %51
14067   //   L2 = load Token1, %52+8
14068   //   S2 = store Token1, L2, %51+8
14069   //   Token2 = Token(S1, S2)
14070   //   L3 = load Token2, %53
14071   //   S3 = store Token2, L3, %52
14072   //   L4 = load Token2, %53+8
14073   //   S4 = store Token2, L4, %52+8
14074   // If we search for aliases of S3 (which loads address %52), and we look
14075   // only through the chain, then we'll miss the trivial dependence on L1
14076   // (which also loads from %52). We then might change all loads and
14077   // stores to use Token1 as their chain operand, which could result in
14078   // copying %53 into %52 before copying %52 into %51 (which should
14079   // happen first).
14080   //
14081   // The problem is, however, that searching for such data dependencies
14082   // can become expensive, and the cost is not directly related to the
14083   // chain depth. Instead, we'll rule out such configurations here by
14084   // insisting that we've visited all chain users (except for users
14085   // of the original chain, which is not necessary). When doing this,
14086   // we need to look through nodes we don't care about (otherwise, things
14087   // like register copies will interfere with trivial cases).
14088
14089   SmallVector<const SDNode *, 16> Worklist;
14090   for (const SDNode *N : Visited)
14091     if (N != OriginalChain.getNode())
14092       Worklist.push_back(N);
14093
14094   while (!Worklist.empty()) {
14095     const SDNode *M = Worklist.pop_back_val();
14096
14097     // We have already visited M, and want to make sure we've visited any uses
14098     // of M that we care about. For uses that we've not visisted, and don't
14099     // care about, queue them to the worklist.
14100
14101     for (SDNode::use_iterator UI = M->use_begin(),
14102          UIE = M->use_end(); UI != UIE; ++UI)
14103       if (UI.getUse().getValueType() == MVT::Other &&
14104           Visited.insert(*UI).second) {
14105         if (isa<MemSDNode>(*UI)) {
14106           // We've not visited this use, and we care about it (it could have an
14107           // ordering dependency with the original node).
14108           Aliases.clear();
14109           Aliases.push_back(OriginalChain);
14110           return;
14111         }
14112
14113         // We've not visited this use, but we don't care about it. Mark it as
14114         // visited and enqueue it to the worklist.
14115         Worklist.push_back(*UI);
14116       }
14117   }
14118 }
14119
14120 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14121 /// (aliasing node.)
14122 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14123   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14124
14125   // Accumulate all the aliases to this node.
14126   GatherAllAliases(N, OldChain, Aliases);
14127
14128   // If no operands then chain to entry token.
14129   if (Aliases.size() == 0)
14130     return DAG.getEntryNode();
14131
14132   // If a single operand then chain to it.  We don't need to revisit it.
14133   if (Aliases.size() == 1)
14134     return Aliases[0];
14135
14136   // Construct a custom tailored token factor.
14137   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14138 }
14139
14140 /// This is the entry point for the file.
14141 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14142                            CodeGenOpt::Level OptLevel) {
14143   /// This is the main entry point to this class.
14144   DAGCombiner(*this, AA, OptLevel).Run(Level);
14145 }