Pass address space to isLegalAddressingMode in DAGCombiner
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
272     SDValue visitTRUNCATE(SDNode *N);
273     SDValue visitBITCAST(SDNode *N);
274     SDValue visitBUILD_PAIR(SDNode *N);
275     SDValue visitFADD(SDNode *N);
276     SDValue visitFSUB(SDNode *N);
277     SDValue visitFMUL(SDNode *N);
278     SDValue visitFMA(SDNode *N);
279     SDValue visitFDIV(SDNode *N);
280     SDValue visitFREM(SDNode *N);
281     SDValue visitFSQRT(SDNode *N);
282     SDValue visitFCOPYSIGN(SDNode *N);
283     SDValue visitSINT_TO_FP(SDNode *N);
284     SDValue visitUINT_TO_FP(SDNode *N);
285     SDValue visitFP_TO_SINT(SDNode *N);
286     SDValue visitFP_TO_UINT(SDNode *N);
287     SDValue visitFP_ROUND(SDNode *N);
288     SDValue visitFP_ROUND_INREG(SDNode *N);
289     SDValue visitFP_EXTEND(SDNode *N);
290     SDValue visitFNEG(SDNode *N);
291     SDValue visitFABS(SDNode *N);
292     SDValue visitFCEIL(SDNode *N);
293     SDValue visitFTRUNC(SDNode *N);
294     SDValue visitFFLOOR(SDNode *N);
295     SDValue visitFMINNUM(SDNode *N);
296     SDValue visitFMAXNUM(SDNode *N);
297     SDValue visitBRCOND(SDNode *N);
298     SDValue visitBR_CC(SDNode *N);
299     SDValue visitLOAD(SDNode *N);
300     SDValue visitSTORE(SDNode *N);
301     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303     SDValue visitBUILD_VECTOR(SDNode *N);
304     SDValue visitCONCAT_VECTORS(SDNode *N);
305     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
306     SDValue visitVECTOR_SHUFFLE(SDNode *N);
307     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
308     SDValue visitINSERT_SUBVECTOR(SDNode *N);
309     SDValue visitMLOAD(SDNode *N);
310     SDValue visitMSTORE(SDNode *N);
311     SDValue visitMGATHER(SDNode *N);
312     SDValue visitMSCATTER(SDNode *N);
313     SDValue visitFP_TO_FP16(SDNode *N);
314
315     SDValue visitFADDForFMACombine(SDNode *N);
316     SDValue visitFSUBForFMACombine(SDNode *N);
317
318     SDValue XformToShuffleWithZero(SDNode *N);
319     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
320
321     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
322
323     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
324     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
325     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
326     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
327                              SDValue N3, ISD::CondCode CC,
328                              bool NotExtCompare = false);
329     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
330                           SDLoc DL, bool foldBooleans = true);
331
332     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
333                            SDValue &CC) const;
334     bool isOneUseSetCC(SDValue N) const;
335
336     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
337                                          unsigned HiOp);
338     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
339     SDValue CombineExtLoad(SDNode *N);
340     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
341     SDValue BuildSDIV(SDNode *N);
342     SDValue BuildSDIVPow2(SDNode *N);
343     SDValue BuildUDIV(SDNode *N);
344     SDValue BuildReciprocalEstimate(SDValue Op);
345     SDValue BuildRsqrtEstimate(SDValue Op);
346     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
348     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
349                                bool DemandHighBits = true);
350     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
351     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
352                               SDValue InnerPos, SDValue InnerNeg,
353                               unsigned PosOpcode, unsigned NegOpcode,
354                               SDLoc DL);
355     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
356     SDValue ReduceLoadWidth(SDNode *N);
357     SDValue ReduceLoadOpStoreWidth(SDNode *N);
358     SDValue TransformFPLoadStorePair(SDNode *N);
359     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
360     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
361
362     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
363
364     /// Walk up chain skipping non-aliasing memory nodes,
365     /// looking for aliasing nodes and adding them to the Aliases vector.
366     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
367                           SmallVectorImpl<SDValue> &Aliases);
368
369     /// Return true if there is any possibility that the two addresses overlap.
370     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
371
372     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
373     /// chain (aliasing node.)
374     SDValue FindBetterChain(SDNode *N, SDValue Chain);
375
376     /// Holds a pointer to an LSBaseSDNode as well as information on where it
377     /// is located in a sequence of memory operations connected by a chain.
378     struct MemOpLink {
379       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
380       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
381       // Ptr to the mem node.
382       LSBaseSDNode *MemNode;
383       // Offset from the base ptr.
384       int64_t OffsetFromBase;
385       // What is the sequence number of this mem node.
386       // Lowest mem operand in the DAG starts at zero.
387       unsigned SequenceNum;
388     };
389
390     /// This is a helper function for MergeConsecutiveStores. When the source
391     /// elements of the consecutive stores are all constants or all extracted
392     /// vector elements, try to merge them into one larger store.
393     /// \return True if a merged store was created.
394     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
395                                          EVT MemVT, unsigned NumElem,
396                                          bool IsConstantSrc, bool UseVector);
397
398     /// Merge consecutive store operations into a wide store.
399     /// This optimization uses wide integers or vectors when possible.
400     /// \return True if some memory operations were changed.
401     bool MergeConsecutiveStores(StoreSDNode *N);
402
403     /// \brief Try to transform a truncation where C is a constant:
404     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
405     ///
406     /// \p N needs to be a truncation and its first operand an AND. Other
407     /// requirements are checked by the function (e.g. that trunc is
408     /// single-use) and if missed an empty SDValue is returned.
409     SDValue distributeTruncateThroughAnd(SDNode *N);
410
411   public:
412     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
413         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
414           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
415       auto *F = DAG.getMachineFunction().getFunction();
416       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
417                     F->hasFnAttribute(Attribute::MinSize);
418     }
419
420     /// Runs the dag combiner on all nodes in the work list
421     void Run(CombineLevel AtLevel);
422
423     SelectionDAG &getDAG() const { return DAG; }
424
425     /// Returns a type large enough to hold any valid shift amount - before type
426     /// legalization these can be huge.
427     EVT getShiftAmountTy(EVT LHSTy) {
428       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
429       if (LHSTy.isVector())
430         return LHSTy;
431       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
432                         : TLI.getPointerTy();
433     }
434
435     /// This method returns true if we are running before type legalization or
436     /// if the specified VT is legal.
437     bool isTypeLegal(const EVT &VT) {
438       if (!LegalTypes) return true;
439       return TLI.isTypeLegal(VT);
440     }
441
442     /// Convenience wrapper around TargetLowering::getSetCCResultType
443     EVT getSetCCResultType(EVT VT) const {
444       return TLI.getSetCCResultType(*DAG.getContext(), VT);
445     }
446   };
447 }
448
449
450 namespace {
451 /// This class is a DAGUpdateListener that removes any deleted
452 /// nodes from the worklist.
453 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
454   DAGCombiner &DC;
455 public:
456   explicit WorklistRemover(DAGCombiner &dc)
457     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
458
459   void NodeDeleted(SDNode *N, SDNode *E) override {
460     DC.removeFromWorklist(N);
461   }
462 };
463 }
464
465 //===----------------------------------------------------------------------===//
466 //  TargetLowering::DAGCombinerInfo implementation
467 //===----------------------------------------------------------------------===//
468
469 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
470   ((DAGCombiner*)DC)->AddToWorklist(N);
471 }
472
473 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
474   ((DAGCombiner*)DC)->removeFromWorklist(N);
475 }
476
477 SDValue TargetLowering::DAGCombinerInfo::
478 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
479   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
480 }
481
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
484   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
485 }
486
487
488 SDValue TargetLowering::DAGCombinerInfo::
489 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
490   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
491 }
492
493 void TargetLowering::DAGCombinerInfo::
494 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
495   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
496 }
497
498 //===----------------------------------------------------------------------===//
499 // Helper Functions
500 //===----------------------------------------------------------------------===//
501
502 void DAGCombiner::deleteAndRecombine(SDNode *N) {
503   removeFromWorklist(N);
504
505   // If the operands of this node are only used by the node, they will now be
506   // dead. Make sure to re-visit them and recursively delete dead nodes.
507   for (const SDValue &Op : N->ops())
508     // For an operand generating multiple values, one of the values may
509     // become dead allowing further simplification (e.g. split index
510     // arithmetic from an indexed load).
511     if (Op->hasOneUse() || Op->getNumValues() > 1)
512       AddToWorklist(Op.getNode());
513
514   DAG.DeleteNode(N);
515 }
516
517 /// Return 1 if we can compute the negated form of the specified expression for
518 /// the same cost as the expression itself, or 2 if we can compute the negated
519 /// form more cheaply than the expression itself.
520 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
521                                const TargetLowering &TLI,
522                                const TargetOptions *Options,
523                                unsigned Depth = 0) {
524   // fneg is removable even if it has multiple uses.
525   if (Op.getOpcode() == ISD::FNEG) return 2;
526
527   // Don't allow anything with multiple uses.
528   if (!Op.hasOneUse()) return 0;
529
530   // Don't recurse exponentially.
531   if (Depth > 6) return 0;
532
533   switch (Op.getOpcode()) {
534   default: return false;
535   case ISD::ConstantFP:
536     // Don't invert constant FP values after legalize.  The negated constant
537     // isn't necessarily legal.
538     return LegalOperations ? 0 : 1;
539   case ISD::FADD:
540     // FIXME: determine better conditions for this xform.
541     if (!Options->UnsafeFPMath) return 0;
542
543     // After operation legalization, it might not be legal to create new FSUBs.
544     if (LegalOperations &&
545         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
546       return 0;
547
548     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
549     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
550                                     Options, Depth + 1))
551       return V;
552     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
553     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
554                               Depth + 1);
555   case ISD::FSUB:
556     // We can't turn -(A-B) into B-A when we honor signed zeros.
557     if (!Options->UnsafeFPMath) return 0;
558
559     // fold (fneg (fsub A, B)) -> (fsub B, A)
560     return 1;
561
562   case ISD::FMUL:
563   case ISD::FDIV:
564     if (Options->HonorSignDependentRoundingFPMath()) return 0;
565
566     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
567     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
568                                     Options, Depth + 1))
569       return V;
570
571     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
572                               Depth + 1);
573
574   case ISD::FP_EXTEND:
575   case ISD::FP_ROUND:
576   case ISD::FSIN:
577     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
578                               Depth + 1);
579   }
580 }
581
582 /// If isNegatibleForFree returns true, return the newly negated expression.
583 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
584                                     bool LegalOperations, unsigned Depth = 0) {
585   const TargetOptions &Options = DAG.getTarget().Options;
586   // fneg is removable even if it has multiple uses.
587   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
588
589   // Don't allow anything with multiple uses.
590   assert(Op.hasOneUse() && "Unknown reuse!");
591
592   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
593   switch (Op.getOpcode()) {
594   default: llvm_unreachable("Unknown code");
595   case ISD::ConstantFP: {
596     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
597     V.changeSign();
598     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
599   }
600   case ISD::FADD:
601     // FIXME: determine better conditions for this xform.
602     assert(Options.UnsafeFPMath);
603
604     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
605     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
607       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
611     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
612     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
613                        GetNegatedExpression(Op.getOperand(1), DAG,
614                                             LegalOperations, Depth+1),
615                        Op.getOperand(0));
616   case ISD::FSUB:
617     // We can't turn -(A-B) into B-A when we honor signed zeros.
618     assert(Options.UnsafeFPMath);
619
620     // fold (fneg (fsub 0, B)) -> B
621     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
622       if (N0CFP->getValueAPF().isZero())
623         return Op.getOperand(1);
624
625     // fold (fneg (fsub A, B)) -> (fsub B, A)
626     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
627                        Op.getOperand(1), Op.getOperand(0));
628
629   case ISD::FMUL:
630   case ISD::FDIV:
631     assert(!Options.HonorSignDependentRoundingFPMath());
632
633     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
634     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
635                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
636       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637                          GetNegatedExpression(Op.getOperand(0), DAG,
638                                               LegalOperations, Depth+1),
639                          Op.getOperand(1));
640
641     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
642     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643                        Op.getOperand(0),
644                        GetNegatedExpression(Op.getOperand(1), DAG,
645                                             LegalOperations, Depth+1));
646
647   case ISD::FP_EXTEND:
648   case ISD::FSIN:
649     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
650                        GetNegatedExpression(Op.getOperand(0), DAG,
651                                             LegalOperations, Depth+1));
652   case ISD::FP_ROUND:
653       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
654                          GetNegatedExpression(Op.getOperand(0), DAG,
655                                               LegalOperations, Depth+1),
656                          Op.getOperand(1));
657   }
658 }
659
660 // Return true if this node is a setcc, or is a select_cc
661 // that selects between the target values used for true and false, making it
662 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
663 // the appropriate nodes based on the type of node we are checking. This
664 // simplifies life a bit for the callers.
665 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
666                                     SDValue &CC) const {
667   if (N.getOpcode() == ISD::SETCC) {
668     LHS = N.getOperand(0);
669     RHS = N.getOperand(1);
670     CC  = N.getOperand(2);
671     return true;
672   }
673
674   if (N.getOpcode() != ISD::SELECT_CC ||
675       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
676       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
677     return false;
678
679   if (TLI.getBooleanContents(N.getValueType()) ==
680       TargetLowering::UndefinedBooleanContent)
681     return false;
682
683   LHS = N.getOperand(0);
684   RHS = N.getOperand(1);
685   CC  = N.getOperand(4);
686   return true;
687 }
688
689 /// Return true if this is a SetCC-equivalent operation with only one use.
690 /// If this is true, it allows the users to invert the operation for free when
691 /// it is profitable to do so.
692 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
693   SDValue N0, N1, N2;
694   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
695     return true;
696   return false;
697 }
698
699 /// Returns true if N is a BUILD_VECTOR node whose
700 /// elements are all the same constant or undefined.
701 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
702   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
703   if (!C)
704     return false;
705
706   APInt SplatUndef;
707   unsigned SplatBitSize;
708   bool HasAnyUndefs;
709   EVT EltVT = N->getValueType(0).getVectorElementType();
710   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
711                              HasAnyUndefs) &&
712           EltVT.getSizeInBits() >= SplatBitSize);
713 }
714
715 // \brief Returns the SDNode if it is a constant integer BuildVector
716 // or constant integer.
717 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
718   if (isa<ConstantSDNode>(N))
719     return N.getNode();
720   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
721     return N.getNode();
722   return nullptr;
723 }
724
725 // \brief Returns the SDNode if it is a constant float BuildVector
726 // or constant float.
727 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
728   if (isa<ConstantFPSDNode>(N))
729     return N.getNode();
730   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
731     return N.getNode();
732   return nullptr;
733 }
734
735 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
736 // int.
737 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
738   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
739     return CN;
740
741   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
742     BitVector UndefElements;
743     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
744
745     // BuildVectors can truncate their operands. Ignore that case here.
746     // FIXME: We blindly ignore splats which include undef which is overly
747     // pessimistic.
748     if (CN && UndefElements.none() &&
749         CN->getValueType(0) == N.getValueType().getScalarType())
750       return CN;
751   }
752
753   return nullptr;
754 }
755
756 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
757 // float.
758 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
759   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
760     return CN;
761
762   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
763     BitVector UndefElements;
764     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
765
766     if (CN && UndefElements.none())
767       return CN;
768   }
769
770   return nullptr;
771 }
772
773 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
774                                     SDValue N0, SDValue N1) {
775   EVT VT = N0.getValueType();
776   if (N0.getOpcode() == Opc) {
777     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
778       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
779         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
780         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
781           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
782         return SDValue();
783       }
784       if (N0.hasOneUse()) {
785         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
786         // use
787         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
788         if (!OpNode.getNode())
789           return SDValue();
790         AddToWorklist(OpNode.getNode());
791         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
792       }
793     }
794   }
795
796   if (N1.getOpcode() == Opc) {
797     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
798       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
799         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
800         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
801           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
802         return SDValue();
803       }
804       if (N1.hasOneUse()) {
805         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
806         // use
807         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
808         if (!OpNode.getNode())
809           return SDValue();
810         AddToWorklist(OpNode.getNode());
811         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
812       }
813     }
814   }
815
816   return SDValue();
817 }
818
819 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
820                                bool AddTo) {
821   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
822   ++NodesCombined;
823   DEBUG(dbgs() << "\nReplacing.1 ";
824         N->dump(&DAG);
825         dbgs() << "\nWith: ";
826         To[0].getNode()->dump(&DAG);
827         dbgs() << " and " << NumTo-1 << " other values\n");
828   for (unsigned i = 0, e = NumTo; i != e; ++i)
829     assert((!To[i].getNode() ||
830             N->getValueType(i) == To[i].getValueType()) &&
831            "Cannot combine value to value of different type!");
832
833   WorklistRemover DeadNodes(*this);
834   DAG.ReplaceAllUsesWith(N, To);
835   if (AddTo) {
836     // Push the new nodes and any users onto the worklist
837     for (unsigned i = 0, e = NumTo; i != e; ++i) {
838       if (To[i].getNode()) {
839         AddToWorklist(To[i].getNode());
840         AddUsersToWorklist(To[i].getNode());
841       }
842     }
843   }
844
845   // Finally, if the node is now dead, remove it from the graph.  The node
846   // may not be dead if the replacement process recursively simplified to
847   // something else needing this node.
848   if (N->use_empty())
849     deleteAndRecombine(N);
850   return SDValue(N, 0);
851 }
852
853 void DAGCombiner::
854 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
855   // Replace all uses.  If any nodes become isomorphic to other nodes and
856   // are deleted, make sure to remove them from our worklist.
857   WorklistRemover DeadNodes(*this);
858   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
859
860   // Push the new node and any (possibly new) users onto the worklist.
861   AddToWorklist(TLO.New.getNode());
862   AddUsersToWorklist(TLO.New.getNode());
863
864   // Finally, if the node is now dead, remove it from the graph.  The node
865   // may not be dead if the replacement process recursively simplified to
866   // something else needing this node.
867   if (TLO.Old.getNode()->use_empty())
868     deleteAndRecombine(TLO.Old.getNode());
869 }
870
871 /// Check the specified integer node value to see if it can be simplified or if
872 /// things it uses can be simplified by bit propagation. If so, return true.
873 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
874   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
875   APInt KnownZero, KnownOne;
876   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
877     return false;
878
879   // Revisit the node.
880   AddToWorklist(Op.getNode());
881
882   // Replace the old value with the new one.
883   ++NodesCombined;
884   DEBUG(dbgs() << "\nReplacing.2 ";
885         TLO.Old.getNode()->dump(&DAG);
886         dbgs() << "\nWith: ";
887         TLO.New.getNode()->dump(&DAG);
888         dbgs() << '\n');
889
890   CommitTargetLoweringOpt(TLO);
891   return true;
892 }
893
894 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
895   SDLoc dl(Load);
896   EVT VT = Load->getValueType(0);
897   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
898
899   DEBUG(dbgs() << "\nReplacing.9 ";
900         Load->dump(&DAG);
901         dbgs() << "\nWith: ";
902         Trunc.getNode()->dump(&DAG);
903         dbgs() << '\n');
904   WorklistRemover DeadNodes(*this);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
906   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
907   deleteAndRecombine(Load);
908   AddToWorklist(Trunc.getNode());
909 }
910
911 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
912   Replace = false;
913   SDLoc dl(Op);
914   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
915     EVT MemVT = LD->getMemoryVT();
916     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
917       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
918                                                        : ISD::EXTLOAD)
919       : LD->getExtensionType();
920     Replace = true;
921     return DAG.getExtLoad(ExtType, dl, PVT,
922                           LD->getChain(), LD->getBasePtr(),
923                           MemVT, LD->getMemOperand());
924   }
925
926   unsigned Opc = Op.getOpcode();
927   switch (Opc) {
928   default: break;
929   case ISD::AssertSext:
930     return DAG.getNode(ISD::AssertSext, dl, PVT,
931                        SExtPromoteOperand(Op.getOperand(0), PVT),
932                        Op.getOperand(1));
933   case ISD::AssertZext:
934     return DAG.getNode(ISD::AssertZext, dl, PVT,
935                        ZExtPromoteOperand(Op.getOperand(0), PVT),
936                        Op.getOperand(1));
937   case ISD::Constant: {
938     unsigned ExtOpc =
939       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
940     return DAG.getNode(ExtOpc, dl, PVT, Op);
941   }
942   }
943
944   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
945     return SDValue();
946   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
947 }
948
949 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
950   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
951     return SDValue();
952   EVT OldVT = Op.getValueType();
953   SDLoc dl(Op);
954   bool Replace = false;
955   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
956   if (!NewOp.getNode())
957     return SDValue();
958   AddToWorklist(NewOp.getNode());
959
960   if (Replace)
961     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
962   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
963                      DAG.getValueType(OldVT));
964 }
965
966 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
967   EVT OldVT = Op.getValueType();
968   SDLoc dl(Op);
969   bool Replace = false;
970   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
971   if (!NewOp.getNode())
972     return SDValue();
973   AddToWorklist(NewOp.getNode());
974
975   if (Replace)
976     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
977   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
978 }
979
980 /// Promote the specified integer binary operation if the target indicates it is
981 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
982 /// i32 since i16 instructions are longer.
983 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
984   if (!LegalOperations)
985     return SDValue();
986
987   EVT VT = Op.getValueType();
988   if (VT.isVector() || !VT.isInteger())
989     return SDValue();
990
991   // If operation type is 'undesirable', e.g. i16 on x86, consider
992   // promoting it.
993   unsigned Opc = Op.getOpcode();
994   if (TLI.isTypeDesirableForOp(Opc, VT))
995     return SDValue();
996
997   EVT PVT = VT;
998   // Consult target whether it is a good idea to promote this operation and
999   // what's the right type to promote it to.
1000   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001     assert(PVT != VT && "Don't know what type to promote to!");
1002
1003     bool Replace0 = false;
1004     SDValue N0 = Op.getOperand(0);
1005     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1006     if (!NN0.getNode())
1007       return SDValue();
1008
1009     bool Replace1 = false;
1010     SDValue N1 = Op.getOperand(1);
1011     SDValue NN1;
1012     if (N0 == N1)
1013       NN1 = NN0;
1014     else {
1015       NN1 = PromoteOperand(N1, PVT, Replace1);
1016       if (!NN1.getNode())
1017         return SDValue();
1018     }
1019
1020     AddToWorklist(NN0.getNode());
1021     if (NN1.getNode())
1022       AddToWorklist(NN1.getNode());
1023
1024     if (Replace0)
1025       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1026     if (Replace1)
1027       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1028
1029     DEBUG(dbgs() << "\nPromoting ";
1030           Op.getNode()->dump(&DAG));
1031     SDLoc dl(Op);
1032     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1034   }
1035   return SDValue();
1036 }
1037
1038 /// Promote the specified integer shift operation if the target indicates it is
1039 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1040 /// i32 since i16 instructions are longer.
1041 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1042   if (!LegalOperations)
1043     return SDValue();
1044
1045   EVT VT = Op.getValueType();
1046   if (VT.isVector() || !VT.isInteger())
1047     return SDValue();
1048
1049   // If operation type is 'undesirable', e.g. i16 on x86, consider
1050   // promoting it.
1051   unsigned Opc = Op.getOpcode();
1052   if (TLI.isTypeDesirableForOp(Opc, VT))
1053     return SDValue();
1054
1055   EVT PVT = VT;
1056   // Consult target whether it is a good idea to promote this operation and
1057   // what's the right type to promote it to.
1058   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1059     assert(PVT != VT && "Don't know what type to promote to!");
1060
1061     bool Replace = false;
1062     SDValue N0 = Op.getOperand(0);
1063     if (Opc == ISD::SRA)
1064       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1065     else if (Opc == ISD::SRL)
1066       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1067     else
1068       N0 = PromoteOperand(N0, PVT, Replace);
1069     if (!N0.getNode())
1070       return SDValue();
1071
1072     AddToWorklist(N0.getNode());
1073     if (Replace)
1074       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1075
1076     DEBUG(dbgs() << "\nPromoting ";
1077           Op.getNode()->dump(&DAG));
1078     SDLoc dl(Op);
1079     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1080                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1081   }
1082   return SDValue();
1083 }
1084
1085 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1086   if (!LegalOperations)
1087     return SDValue();
1088
1089   EVT VT = Op.getValueType();
1090   if (VT.isVector() || !VT.isInteger())
1091     return SDValue();
1092
1093   // If operation type is 'undesirable', e.g. i16 on x86, consider
1094   // promoting it.
1095   unsigned Opc = Op.getOpcode();
1096   if (TLI.isTypeDesirableForOp(Opc, VT))
1097     return SDValue();
1098
1099   EVT PVT = VT;
1100   // Consult target whether it is a good idea to promote this operation and
1101   // what's the right type to promote it to.
1102   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1103     assert(PVT != VT && "Don't know what type to promote to!");
1104     // fold (aext (aext x)) -> (aext x)
1105     // fold (aext (zext x)) -> (zext x)
1106     // fold (aext (sext x)) -> (sext x)
1107     DEBUG(dbgs() << "\nPromoting ";
1108           Op.getNode()->dump(&DAG));
1109     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1110   }
1111   return SDValue();
1112 }
1113
1114 bool DAGCombiner::PromoteLoad(SDValue Op) {
1115   if (!LegalOperations)
1116     return false;
1117
1118   EVT VT = Op.getValueType();
1119   if (VT.isVector() || !VT.isInteger())
1120     return false;
1121
1122   // If operation type is 'undesirable', e.g. i16 on x86, consider
1123   // promoting it.
1124   unsigned Opc = Op.getOpcode();
1125   if (TLI.isTypeDesirableForOp(Opc, VT))
1126     return false;
1127
1128   EVT PVT = VT;
1129   // Consult target whether it is a good idea to promote this operation and
1130   // what's the right type to promote it to.
1131   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1132     assert(PVT != VT && "Don't know what type to promote to!");
1133
1134     SDLoc dl(Op);
1135     SDNode *N = Op.getNode();
1136     LoadSDNode *LD = cast<LoadSDNode>(N);
1137     EVT MemVT = LD->getMemoryVT();
1138     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1139       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1140                                                        : ISD::EXTLOAD)
1141       : LD->getExtensionType();
1142     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1143                                    LD->getChain(), LD->getBasePtr(),
1144                                    MemVT, LD->getMemOperand());
1145     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1146
1147     DEBUG(dbgs() << "\nPromoting ";
1148           N->dump(&DAG);
1149           dbgs() << "\nTo: ";
1150           Result.getNode()->dump(&DAG);
1151           dbgs() << '\n');
1152     WorklistRemover DeadNodes(*this);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1154     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1155     deleteAndRecombine(N);
1156     AddToWorklist(Result.getNode());
1157     return true;
1158   }
1159   return false;
1160 }
1161
1162 /// \brief Recursively delete a node which has no uses and any operands for
1163 /// which it is the only use.
1164 ///
1165 /// Note that this both deletes the nodes and removes them from the worklist.
1166 /// It also adds any nodes who have had a user deleted to the worklist as they
1167 /// may now have only one use and subject to other combines.
1168 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1169   if (!N->use_empty())
1170     return false;
1171
1172   SmallSetVector<SDNode *, 16> Nodes;
1173   Nodes.insert(N);
1174   do {
1175     N = Nodes.pop_back_val();
1176     if (!N)
1177       continue;
1178
1179     if (N->use_empty()) {
1180       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1181         Nodes.insert(N->getOperand(i).getNode());
1182
1183       removeFromWorklist(N);
1184       DAG.DeleteNode(N);
1185     } else {
1186       AddToWorklist(N);
1187     }
1188   } while (!Nodes.empty());
1189   return true;
1190 }
1191
1192 //===----------------------------------------------------------------------===//
1193 //  Main DAG Combiner implementation
1194 //===----------------------------------------------------------------------===//
1195
1196 void DAGCombiner::Run(CombineLevel AtLevel) {
1197   // set the instance variables, so that the various visit routines may use it.
1198   Level = AtLevel;
1199   LegalOperations = Level >= AfterLegalizeVectorOps;
1200   LegalTypes = Level >= AfterLegalizeTypes;
1201
1202   // Add all the dag nodes to the worklist.
1203   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1204        E = DAG.allnodes_end(); I != E; ++I)
1205     AddToWorklist(I);
1206
1207   // Create a dummy node (which is not added to allnodes), that adds a reference
1208   // to the root node, preventing it from being deleted, and tracking any
1209   // changes of the root.
1210   HandleSDNode Dummy(DAG.getRoot());
1211
1212   // while the worklist isn't empty, find a node and
1213   // try and combine it.
1214   while (!WorklistMap.empty()) {
1215     SDNode *N;
1216     // The Worklist holds the SDNodes in order, but it may contain null entries.
1217     do {
1218       N = Worklist.pop_back_val();
1219     } while (!N);
1220
1221     bool GoodWorklistEntry = WorklistMap.erase(N);
1222     (void)GoodWorklistEntry;
1223     assert(GoodWorklistEntry &&
1224            "Found a worklist entry without a corresponding map entry!");
1225
1226     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1227     // N is deleted from the DAG, since they too may now be dead or may have a
1228     // reduced number of uses, allowing other xforms.
1229     if (recursivelyDeleteUnusedNodes(N))
1230       continue;
1231
1232     WorklistRemover DeadNodes(*this);
1233
1234     // If this combine is running after legalizing the DAG, re-legalize any
1235     // nodes pulled off the worklist.
1236     if (Level == AfterLegalizeDAG) {
1237       SmallSetVector<SDNode *, 16> UpdatedNodes;
1238       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1239
1240       for (SDNode *LN : UpdatedNodes) {
1241         AddToWorklist(LN);
1242         AddUsersToWorklist(LN);
1243       }
1244       if (!NIsValid)
1245         continue;
1246     }
1247
1248     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1249
1250     // Add any operands of the new node which have not yet been combined to the
1251     // worklist as well. Because the worklist uniques things already, this
1252     // won't repeatedly process the same operand.
1253     CombinedNodes.insert(N);
1254     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1255       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1256         AddToWorklist(N->getOperand(i).getNode());
1257
1258     SDValue RV = combine(N);
1259
1260     if (!RV.getNode())
1261       continue;
1262
1263     ++NodesCombined;
1264
1265     // If we get back the same node we passed in, rather than a new node or
1266     // zero, we know that the node must have defined multiple values and
1267     // CombineTo was used.  Since CombineTo takes care of the worklist
1268     // mechanics for us, we have no work to do in this case.
1269     if (RV.getNode() == N)
1270       continue;
1271
1272     assert(N->getOpcode() != ISD::DELETED_NODE &&
1273            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1274            "Node was deleted but visit returned new node!");
1275
1276     DEBUG(dbgs() << " ... into: ";
1277           RV.getNode()->dump(&DAG));
1278
1279     // Transfer debug value.
1280     DAG.TransferDbgValues(SDValue(N, 0), RV);
1281     if (N->getNumValues() == RV.getNode()->getNumValues())
1282       DAG.ReplaceAllUsesWith(N, RV.getNode());
1283     else {
1284       assert(N->getValueType(0) == RV.getValueType() &&
1285              N->getNumValues() == 1 && "Type mismatch");
1286       SDValue OpV = RV;
1287       DAG.ReplaceAllUsesWith(N, &OpV);
1288     }
1289
1290     // Push the new node and any users onto the worklist
1291     AddToWorklist(RV.getNode());
1292     AddUsersToWorklist(RV.getNode());
1293
1294     // Finally, if the node is now dead, remove it from the graph.  The node
1295     // may not be dead if the replacement process recursively simplified to
1296     // something else needing this node. This will also take care of adding any
1297     // operands which have lost a user to the worklist.
1298     recursivelyDeleteUnusedNodes(N);
1299   }
1300
1301   // If the root changed (e.g. it was a dead load, update the root).
1302   DAG.setRoot(Dummy.getValue());
1303   DAG.RemoveDeadNodes();
1304 }
1305
1306 SDValue DAGCombiner::visit(SDNode *N) {
1307   switch (N->getOpcode()) {
1308   default: break;
1309   case ISD::TokenFactor:        return visitTokenFactor(N);
1310   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1311   case ISD::ADD:                return visitADD(N);
1312   case ISD::SUB:                return visitSUB(N);
1313   case ISD::ADDC:               return visitADDC(N);
1314   case ISD::SUBC:               return visitSUBC(N);
1315   case ISD::ADDE:               return visitADDE(N);
1316   case ISD::SUBE:               return visitSUBE(N);
1317   case ISD::MUL:                return visitMUL(N);
1318   case ISD::SDIV:               return visitSDIV(N);
1319   case ISD::UDIV:               return visitUDIV(N);
1320   case ISD::SREM:               return visitSREM(N);
1321   case ISD::UREM:               return visitUREM(N);
1322   case ISD::MULHU:              return visitMULHU(N);
1323   case ISD::MULHS:              return visitMULHS(N);
1324   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1325   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1326   case ISD::SMULO:              return visitSMULO(N);
1327   case ISD::UMULO:              return visitUMULO(N);
1328   case ISD::SDIVREM:            return visitSDIVREM(N);
1329   case ISD::UDIVREM:            return visitUDIVREM(N);
1330   case ISD::AND:                return visitAND(N);
1331   case ISD::OR:                 return visitOR(N);
1332   case ISD::XOR:                return visitXOR(N);
1333   case ISD::SHL:                return visitSHL(N);
1334   case ISD::SRA:                return visitSRA(N);
1335   case ISD::SRL:                return visitSRL(N);
1336   case ISD::ROTR:
1337   case ISD::ROTL:               return visitRotate(N);
1338   case ISD::CTLZ:               return visitCTLZ(N);
1339   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1340   case ISD::CTTZ:               return visitCTTZ(N);
1341   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1342   case ISD::CTPOP:              return visitCTPOP(N);
1343   case ISD::SELECT:             return visitSELECT(N);
1344   case ISD::VSELECT:            return visitVSELECT(N);
1345   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1346   case ISD::SETCC:              return visitSETCC(N);
1347   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1348   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1349   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1350   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1351   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1352   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1353   case ISD::BITCAST:            return visitBITCAST(N);
1354   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1355   case ISD::FADD:               return visitFADD(N);
1356   case ISD::FSUB:               return visitFSUB(N);
1357   case ISD::FMUL:               return visitFMUL(N);
1358   case ISD::FMA:                return visitFMA(N);
1359   case ISD::FDIV:               return visitFDIV(N);
1360   case ISD::FREM:               return visitFREM(N);
1361   case ISD::FSQRT:              return visitFSQRT(N);
1362   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1363   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1364   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1365   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1366   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1367   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1368   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1369   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1370   case ISD::FNEG:               return visitFNEG(N);
1371   case ISD::FABS:               return visitFABS(N);
1372   case ISD::FFLOOR:             return visitFFLOOR(N);
1373   case ISD::FMINNUM:            return visitFMINNUM(N);
1374   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1375   case ISD::FCEIL:              return visitFCEIL(N);
1376   case ISD::FTRUNC:             return visitFTRUNC(N);
1377   case ISD::BRCOND:             return visitBRCOND(N);
1378   case ISD::BR_CC:              return visitBR_CC(N);
1379   case ISD::LOAD:               return visitLOAD(N);
1380   case ISD::STORE:              return visitSTORE(N);
1381   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1382   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1383   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1384   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1385   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1386   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1387   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1388   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1389   case ISD::MGATHER:            return visitMGATHER(N);
1390   case ISD::MLOAD:              return visitMLOAD(N);
1391   case ISD::MSCATTER:           return visitMSCATTER(N);
1392   case ISD::MSTORE:             return visitMSTORE(N);
1393   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1394   }
1395   return SDValue();
1396 }
1397
1398 SDValue DAGCombiner::combine(SDNode *N) {
1399   SDValue RV = visit(N);
1400
1401   // If nothing happened, try a target-specific DAG combine.
1402   if (!RV.getNode()) {
1403     assert(N->getOpcode() != ISD::DELETED_NODE &&
1404            "Node was deleted but visit returned NULL!");
1405
1406     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1407         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1408
1409       // Expose the DAG combiner to the target combiner impls.
1410       TargetLowering::DAGCombinerInfo
1411         DagCombineInfo(DAG, Level, false, this);
1412
1413       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1414     }
1415   }
1416
1417   // If nothing happened still, try promoting the operation.
1418   if (!RV.getNode()) {
1419     switch (N->getOpcode()) {
1420     default: break;
1421     case ISD::ADD:
1422     case ISD::SUB:
1423     case ISD::MUL:
1424     case ISD::AND:
1425     case ISD::OR:
1426     case ISD::XOR:
1427       RV = PromoteIntBinOp(SDValue(N, 0));
1428       break;
1429     case ISD::SHL:
1430     case ISD::SRA:
1431     case ISD::SRL:
1432       RV = PromoteIntShiftOp(SDValue(N, 0));
1433       break;
1434     case ISD::SIGN_EXTEND:
1435     case ISD::ZERO_EXTEND:
1436     case ISD::ANY_EXTEND:
1437       RV = PromoteExtend(SDValue(N, 0));
1438       break;
1439     case ISD::LOAD:
1440       if (PromoteLoad(SDValue(N, 0)))
1441         RV = SDValue(N, 0);
1442       break;
1443     }
1444   }
1445
1446   // If N is a commutative binary node, try commuting it to enable more
1447   // sdisel CSE.
1448   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1449       N->getNumValues() == 1) {
1450     SDValue N0 = N->getOperand(0);
1451     SDValue N1 = N->getOperand(1);
1452
1453     // Constant operands are canonicalized to RHS.
1454     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1455       SDValue Ops[] = {N1, N0};
1456       SDNode *CSENode;
1457       if (const BinaryWithFlagsSDNode *BinNode =
1458               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1459         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1460                                       BinNode->Flags.hasNoUnsignedWrap(),
1461                                       BinNode->Flags.hasNoSignedWrap(),
1462                                       BinNode->Flags.hasExact());
1463       } else {
1464         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1465       }
1466       if (CSENode)
1467         return SDValue(CSENode, 0);
1468     }
1469   }
1470
1471   return RV;
1472 }
1473
1474 /// Given a node, return its input chain if it has one, otherwise return a null
1475 /// sd operand.
1476 static SDValue getInputChainForNode(SDNode *N) {
1477   if (unsigned NumOps = N->getNumOperands()) {
1478     if (N->getOperand(0).getValueType() == MVT::Other)
1479       return N->getOperand(0);
1480     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1481       return N->getOperand(NumOps-1);
1482     for (unsigned i = 1; i < NumOps-1; ++i)
1483       if (N->getOperand(i).getValueType() == MVT::Other)
1484         return N->getOperand(i);
1485   }
1486   return SDValue();
1487 }
1488
1489 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1490   // If N has two operands, where one has an input chain equal to the other,
1491   // the 'other' chain is redundant.
1492   if (N->getNumOperands() == 2) {
1493     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1494       return N->getOperand(0);
1495     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1496       return N->getOperand(1);
1497   }
1498
1499   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1500   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1501   SmallPtrSet<SDNode*, 16> SeenOps;
1502   bool Changed = false;             // If we should replace this token factor.
1503
1504   // Start out with this token factor.
1505   TFs.push_back(N);
1506
1507   // Iterate through token factors.  The TFs grows when new token factors are
1508   // encountered.
1509   for (unsigned i = 0; i < TFs.size(); ++i) {
1510     SDNode *TF = TFs[i];
1511
1512     // Check each of the operands.
1513     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1514       SDValue Op = TF->getOperand(i);
1515
1516       switch (Op.getOpcode()) {
1517       case ISD::EntryToken:
1518         // Entry tokens don't need to be added to the list. They are
1519         // redundant.
1520         Changed = true;
1521         break;
1522
1523       case ISD::TokenFactor:
1524         if (Op.hasOneUse() &&
1525             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1526           // Queue up for processing.
1527           TFs.push_back(Op.getNode());
1528           // Clean up in case the token factor is removed.
1529           AddToWorklist(Op.getNode());
1530           Changed = true;
1531           break;
1532         }
1533         // Fall thru
1534
1535       default:
1536         // Only add if it isn't already in the list.
1537         if (SeenOps.insert(Op.getNode()).second)
1538           Ops.push_back(Op);
1539         else
1540           Changed = true;
1541         break;
1542       }
1543     }
1544   }
1545
1546   SDValue Result;
1547
1548   // If we've changed things around then replace token factor.
1549   if (Changed) {
1550     if (Ops.empty()) {
1551       // The entry token is the only possible outcome.
1552       Result = DAG.getEntryNode();
1553     } else {
1554       // New and improved token factor.
1555       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1556     }
1557
1558     // Add users to worklist if AA is enabled, since it may introduce
1559     // a lot of new chained token factors while removing memory deps.
1560     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1561       : DAG.getSubtarget().useAA();
1562     return CombineTo(N, Result, UseAA /*add to worklist*/);
1563   }
1564
1565   return Result;
1566 }
1567
1568 /// MERGE_VALUES can always be eliminated.
1569 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1570   WorklistRemover DeadNodes(*this);
1571   // Replacing results may cause a different MERGE_VALUES to suddenly
1572   // be CSE'd with N, and carry its uses with it. Iterate until no
1573   // uses remain, to ensure that the node can be safely deleted.
1574   // First add the users of this node to the work list so that they
1575   // can be tried again once they have new operands.
1576   AddUsersToWorklist(N);
1577   do {
1578     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1579       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1580   } while (!N->use_empty());
1581   deleteAndRecombine(N);
1582   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1583 }
1584
1585 static bool isNullConstant(SDValue V) {
1586   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1587   return Const != nullptr && Const->isNullValue();
1588 }
1589
1590 static bool isAllOnesConstant(SDValue V) {
1591   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1592   return Const != nullptr && Const->isAllOnesValue();
1593 }
1594
1595 static bool isOneConstant(SDValue V) {
1596   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1597   return Const != nullptr && Const->isOne();
1598 }
1599
1600 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1601 /// ContantSDNode pointer else nullptr.
1602 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1603   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1604   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1605 }
1606
1607 SDValue DAGCombiner::visitADD(SDNode *N) {
1608   SDValue N0 = N->getOperand(0);
1609   SDValue N1 = N->getOperand(1);
1610   EVT VT = N0.getValueType();
1611
1612   // fold vector ops
1613   if (VT.isVector()) {
1614     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1615       return FoldedVOp;
1616
1617     // fold (add x, 0) -> x, vector edition
1618     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1619       return N0;
1620     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1621       return N1;
1622   }
1623
1624   // fold (add x, undef) -> undef
1625   if (N0.getOpcode() == ISD::UNDEF)
1626     return N0;
1627   if (N1.getOpcode() == ISD::UNDEF)
1628     return N1;
1629   // fold (add c1, c2) -> c1+c2
1630   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1631   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1632   if (N0C && N1C)
1633     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1634   // canonicalize constant to RHS
1635   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1636      !isConstantIntBuildVectorOrConstantInt(N1))
1637     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1638   // fold (add x, 0) -> x
1639   if (isNullConstant(N1))
1640     return N0;
1641   // fold (add Sym, c) -> Sym+c
1642   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1643     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1644         GA->getOpcode() == ISD::GlobalAddress)
1645       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1646                                   GA->getOffset() +
1647                                     (uint64_t)N1C->getSExtValue());
1648   // fold ((c1-A)+c2) -> (c1+c2)-A
1649   if (N1C && N0.getOpcode() == ISD::SUB)
1650     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1651       SDLoc DL(N);
1652       return DAG.getNode(ISD::SUB, DL, VT,
1653                          DAG.getConstant(N1C->getAPIntValue()+
1654                                          N0C->getAPIntValue(), DL, VT),
1655                          N0.getOperand(1));
1656     }
1657   // reassociate add
1658   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1659     return RADD;
1660   // fold ((0-A) + B) -> B-A
1661   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1662     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1663   // fold (A + (0-B)) -> A-B
1664   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1665     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1666   // fold (A+(B-A)) -> B
1667   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1668     return N1.getOperand(0);
1669   // fold ((B-A)+A) -> B
1670   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1671     return N0.getOperand(0);
1672   // fold (A+(B-(A+C))) to (B-C)
1673   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1674       N0 == N1.getOperand(1).getOperand(0))
1675     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1676                        N1.getOperand(1).getOperand(1));
1677   // fold (A+(B-(C+A))) to (B-C)
1678   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1679       N0 == N1.getOperand(1).getOperand(1))
1680     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1681                        N1.getOperand(1).getOperand(0));
1682   // fold (A+((B-A)+or-C)) to (B+or-C)
1683   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1684       N1.getOperand(0).getOpcode() == ISD::SUB &&
1685       N0 == N1.getOperand(0).getOperand(1))
1686     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1687                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1688
1689   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1690   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1691     SDValue N00 = N0.getOperand(0);
1692     SDValue N01 = N0.getOperand(1);
1693     SDValue N10 = N1.getOperand(0);
1694     SDValue N11 = N1.getOperand(1);
1695
1696     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1697       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1698                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1699                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1700   }
1701
1702   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1703     return SDValue(N, 0);
1704
1705   // fold (a+b) -> (a|b) iff a and b share no bits.
1706   if (VT.isInteger() && !VT.isVector()) {
1707     APInt LHSZero, LHSOne;
1708     APInt RHSZero, RHSOne;
1709     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1710
1711     if (LHSZero.getBoolValue()) {
1712       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1713
1714       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1715       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1716       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1717         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1718           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1719       }
1720     }
1721   }
1722
1723   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1724   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1725       isNullConstant(N1.getOperand(0).getOperand(0)))
1726     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1727                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1728                                    N1.getOperand(0).getOperand(1),
1729                                    N1.getOperand(1)));
1730   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1731       isNullConstant(N0.getOperand(0).getOperand(0)))
1732     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1733                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1734                                    N0.getOperand(0).getOperand(1),
1735                                    N0.getOperand(1)));
1736
1737   if (N1.getOpcode() == ISD::AND) {
1738     SDValue AndOp0 = N1.getOperand(0);
1739     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1740     unsigned DestBits = VT.getScalarType().getSizeInBits();
1741
1742     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1743     // and similar xforms where the inner op is either ~0 or 0.
1744     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1745       SDLoc DL(N);
1746       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1747     }
1748   }
1749
1750   // add (sext i1), X -> sub X, (zext i1)
1751   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1752       N0.getOperand(0).getValueType() == MVT::i1 &&
1753       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1754     SDLoc DL(N);
1755     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1756     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1757   }
1758
1759   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1760   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1761     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1762     if (TN->getVT() == MVT::i1) {
1763       SDLoc DL(N);
1764       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1765                                  DAG.getConstant(1, DL, VT));
1766       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1767     }
1768   }
1769
1770   return SDValue();
1771 }
1772
1773 SDValue DAGCombiner::visitADDC(SDNode *N) {
1774   SDValue N0 = N->getOperand(0);
1775   SDValue N1 = N->getOperand(1);
1776   EVT VT = N0.getValueType();
1777
1778   // If the flag result is dead, turn this into an ADD.
1779   if (!N->hasAnyUseOfValue(1))
1780     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1781                      DAG.getNode(ISD::CARRY_FALSE,
1782                                  SDLoc(N), MVT::Glue));
1783
1784   // canonicalize constant to RHS.
1785   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1786   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1787   if (N0C && !N1C)
1788     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1789
1790   // fold (addc x, 0) -> x + no carry out
1791   if (isNullConstant(N1))
1792     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1793                                         SDLoc(N), MVT::Glue));
1794
1795   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1796   APInt LHSZero, LHSOne;
1797   APInt RHSZero, RHSOne;
1798   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1799
1800   if (LHSZero.getBoolValue()) {
1801     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1802
1803     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1804     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1805     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1806       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1807                        DAG.getNode(ISD::CARRY_FALSE,
1808                                    SDLoc(N), MVT::Glue));
1809   }
1810
1811   return SDValue();
1812 }
1813
1814 SDValue DAGCombiner::visitADDE(SDNode *N) {
1815   SDValue N0 = N->getOperand(0);
1816   SDValue N1 = N->getOperand(1);
1817   SDValue CarryIn = N->getOperand(2);
1818
1819   // canonicalize constant to RHS
1820   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1821   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1822   if (N0C && !N1C)
1823     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1824                        N1, N0, CarryIn);
1825
1826   // fold (adde x, y, false) -> (addc x, y)
1827   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1828     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1829
1830   return SDValue();
1831 }
1832
1833 // Since it may not be valid to emit a fold to zero for vector initializers
1834 // check if we can before folding.
1835 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1836                              SelectionDAG &DAG,
1837                              bool LegalOperations, bool LegalTypes) {
1838   if (!VT.isVector())
1839     return DAG.getConstant(0, DL, VT);
1840   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1841     return DAG.getConstant(0, DL, VT);
1842   return SDValue();
1843 }
1844
1845 SDValue DAGCombiner::visitSUB(SDNode *N) {
1846   SDValue N0 = N->getOperand(0);
1847   SDValue N1 = N->getOperand(1);
1848   EVT VT = N0.getValueType();
1849
1850   // fold vector ops
1851   if (VT.isVector()) {
1852     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1853       return FoldedVOp;
1854
1855     // fold (sub x, 0) -> x, vector edition
1856     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1857       return N0;
1858   }
1859
1860   // fold (sub x, x) -> 0
1861   // FIXME: Refactor this and xor and other similar operations together.
1862   if (N0 == N1)
1863     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1864   // fold (sub c1, c2) -> c1-c2
1865   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1866   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1867   if (N0C && N1C)
1868     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1869   // fold (sub x, c) -> (add x, -c)
1870   if (N1C) {
1871     SDLoc DL(N);
1872     return DAG.getNode(ISD::ADD, DL, VT, N0,
1873                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1874   }
1875   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1876   if (isAllOnesConstant(N0))
1877     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1878   // fold A-(A-B) -> B
1879   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1880     return N1.getOperand(1);
1881   // fold (A+B)-A -> B
1882   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1883     return N0.getOperand(1);
1884   // fold (A+B)-B -> A
1885   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1886     return N0.getOperand(0);
1887   // fold C2-(A+C1) -> (C2-C1)-A
1888   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1889     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1890   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1891     SDLoc DL(N);
1892     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1893                                    DL, VT);
1894     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1895                        N1.getOperand(0));
1896   }
1897   // fold ((A+(B+or-C))-B) -> A+or-C
1898   if (N0.getOpcode() == ISD::ADD &&
1899       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1900        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1901       N0.getOperand(1).getOperand(0) == N1)
1902     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1903                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1904   // fold ((A+(C+B))-B) -> A+C
1905   if (N0.getOpcode() == ISD::ADD &&
1906       N0.getOperand(1).getOpcode() == ISD::ADD &&
1907       N0.getOperand(1).getOperand(1) == N1)
1908     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1909                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1910   // fold ((A-(B-C))-C) -> A-B
1911   if (N0.getOpcode() == ISD::SUB &&
1912       N0.getOperand(1).getOpcode() == ISD::SUB &&
1913       N0.getOperand(1).getOperand(1) == N1)
1914     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1915                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1916
1917   // If either operand of a sub is undef, the result is undef
1918   if (N0.getOpcode() == ISD::UNDEF)
1919     return N0;
1920   if (N1.getOpcode() == ISD::UNDEF)
1921     return N1;
1922
1923   // If the relocation model supports it, consider symbol offsets.
1924   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1925     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1926       // fold (sub Sym, c) -> Sym-c
1927       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1928         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1929                                     GA->getOffset() -
1930                                       (uint64_t)N1C->getSExtValue());
1931       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1932       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1933         if (GA->getGlobal() == GB->getGlobal())
1934           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1935                                  SDLoc(N), VT);
1936     }
1937
1938   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1939   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1940     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1941     if (TN->getVT() == MVT::i1) {
1942       SDLoc DL(N);
1943       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1944                                  DAG.getConstant(1, DL, VT));
1945       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1946     }
1947   }
1948
1949   return SDValue();
1950 }
1951
1952 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1953   SDValue N0 = N->getOperand(0);
1954   SDValue N1 = N->getOperand(1);
1955   EVT VT = N0.getValueType();
1956
1957   // If the flag result is dead, turn this into an SUB.
1958   if (!N->hasAnyUseOfValue(1))
1959     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1960                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1961                                  MVT::Glue));
1962
1963   // fold (subc x, x) -> 0 + no borrow
1964   if (N0 == N1) {
1965     SDLoc DL(N);
1966     return CombineTo(N, DAG.getConstant(0, DL, VT),
1967                      DAG.getNode(ISD::CARRY_FALSE, DL,
1968                                  MVT::Glue));
1969   }
1970
1971   // fold (subc x, 0) -> x + no borrow
1972   if (isNullConstant(N1))
1973     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1974                                         MVT::Glue));
1975
1976   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1977   if (isAllOnesConstant(N0))
1978     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1979                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1980                                  MVT::Glue));
1981
1982   return SDValue();
1983 }
1984
1985 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1986   SDValue N0 = N->getOperand(0);
1987   SDValue N1 = N->getOperand(1);
1988   SDValue CarryIn = N->getOperand(2);
1989
1990   // fold (sube x, y, false) -> (subc x, y)
1991   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1992     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1993
1994   return SDValue();
1995 }
1996
1997 SDValue DAGCombiner::visitMUL(SDNode *N) {
1998   SDValue N0 = N->getOperand(0);
1999   SDValue N1 = N->getOperand(1);
2000   EVT VT = N0.getValueType();
2001
2002   // fold (mul x, undef) -> 0
2003   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2004     return DAG.getConstant(0, SDLoc(N), VT);
2005
2006   bool N0IsConst = false;
2007   bool N1IsConst = false;
2008   bool N1IsOpaqueConst = false;
2009   bool N0IsOpaqueConst = false;
2010   APInt ConstValue0, ConstValue1;
2011   // fold vector ops
2012   if (VT.isVector()) {
2013     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2014       return FoldedVOp;
2015
2016     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2017     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2018   } else {
2019     N0IsConst = isa<ConstantSDNode>(N0);
2020     if (N0IsConst) {
2021       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2022       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2023     }
2024     N1IsConst = isa<ConstantSDNode>(N1);
2025     if (N1IsConst) {
2026       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2027       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2028     }
2029   }
2030
2031   // fold (mul c1, c2) -> c1*c2
2032   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2033     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2034                                       N0.getNode(), N1.getNode());
2035
2036   // canonicalize constant to RHS (vector doesn't have to splat)
2037   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2038      !isConstantIntBuildVectorOrConstantInt(N1))
2039     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2040   // fold (mul x, 0) -> 0
2041   if (N1IsConst && ConstValue1 == 0)
2042     return N1;
2043   // We require a splat of the entire scalar bit width for non-contiguous
2044   // bit patterns.
2045   bool IsFullSplat =
2046     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2047   // fold (mul x, 1) -> x
2048   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2049     return N0;
2050   // fold (mul x, -1) -> 0-x
2051   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2052     SDLoc DL(N);
2053     return DAG.getNode(ISD::SUB, DL, VT,
2054                        DAG.getConstant(0, DL, VT), N0);
2055   }
2056   // fold (mul x, (1 << c)) -> x << c
2057   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2058       IsFullSplat) {
2059     SDLoc DL(N);
2060     return DAG.getNode(ISD::SHL, DL, VT, N0,
2061                        DAG.getConstant(ConstValue1.logBase2(), DL,
2062                                        getShiftAmountTy(N0.getValueType())));
2063   }
2064   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2065   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2066       IsFullSplat) {
2067     unsigned Log2Val = (-ConstValue1).logBase2();
2068     SDLoc DL(N);
2069     // FIXME: If the input is something that is easily negated (e.g. a
2070     // single-use add), we should put the negate there.
2071     return DAG.getNode(ISD::SUB, DL, VT,
2072                        DAG.getConstant(0, DL, VT),
2073                        DAG.getNode(ISD::SHL, DL, VT, N0,
2074                             DAG.getConstant(Log2Val, DL,
2075                                       getShiftAmountTy(N0.getValueType()))));
2076   }
2077
2078   APInt Val;
2079   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2080   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2081       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2082                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2083     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2084                              N1, N0.getOperand(1));
2085     AddToWorklist(C3.getNode());
2086     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2087                        N0.getOperand(0), C3);
2088   }
2089
2090   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2091   // use.
2092   {
2093     SDValue Sh(nullptr,0), Y(nullptr,0);
2094     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2095     if (N0.getOpcode() == ISD::SHL &&
2096         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2097                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2098         N0.getNode()->hasOneUse()) {
2099       Sh = N0; Y = N1;
2100     } else if (N1.getOpcode() == ISD::SHL &&
2101                isa<ConstantSDNode>(N1.getOperand(1)) &&
2102                N1.getNode()->hasOneUse()) {
2103       Sh = N1; Y = N0;
2104     }
2105
2106     if (Sh.getNode()) {
2107       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2108                                 Sh.getOperand(0), Y);
2109       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2110                          Mul, Sh.getOperand(1));
2111     }
2112   }
2113
2114   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2115   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2116       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2117                      isa<ConstantSDNode>(N0.getOperand(1))))
2118     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2119                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2120                                    N0.getOperand(0), N1),
2121                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2122                                    N0.getOperand(1), N1));
2123
2124   // reassociate mul
2125   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2126     return RMUL;
2127
2128   return SDValue();
2129 }
2130
2131 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2132   SDValue N0 = N->getOperand(0);
2133   SDValue N1 = N->getOperand(1);
2134   EVT VT = N->getValueType(0);
2135
2136   // fold vector ops
2137   if (VT.isVector())
2138     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2139       return FoldedVOp;
2140
2141   // fold (sdiv c1, c2) -> c1/c2
2142   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2143   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2144   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2145     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2146   // fold (sdiv X, 1) -> X
2147   if (N1C && N1C->isOne())
2148     return N0;
2149   // fold (sdiv X, -1) -> 0-X
2150   if (N1C && N1C->isAllOnesValue()) {
2151     SDLoc DL(N);
2152     return DAG.getNode(ISD::SUB, DL, VT,
2153                        DAG.getConstant(0, DL, VT), N0);
2154   }
2155   // If we know the sign bits of both operands are zero, strength reduce to a
2156   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2157   if (!VT.isVector()) {
2158     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2159       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2160                          N0, N1);
2161   }
2162
2163   // fold (sdiv X, pow2) -> simple ops after legalize
2164   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2165       (N1C->getAPIntValue().isPowerOf2() ||
2166        (-N1C->getAPIntValue()).isPowerOf2())) {
2167     // If dividing by powers of two is cheap, then don't perform the following
2168     // fold.
2169     if (TLI.isPow2SDivCheap())
2170       return SDValue();
2171
2172     // Target-specific implementation of sdiv x, pow2.
2173     SDValue Res = BuildSDIVPow2(N);
2174     if (Res.getNode())
2175       return Res;
2176
2177     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2178     SDLoc DL(N);
2179
2180     // Splat the sign bit into the register
2181     SDValue SGN =
2182         DAG.getNode(ISD::SRA, DL, VT, N0,
2183                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2184                                     getShiftAmountTy(N0.getValueType())));
2185     AddToWorklist(SGN.getNode());
2186
2187     // Add (N0 < 0) ? abs2 - 1 : 0;
2188     SDValue SRL =
2189         DAG.getNode(ISD::SRL, DL, VT, SGN,
2190                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2191                                     getShiftAmountTy(SGN.getValueType())));
2192     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2193     AddToWorklist(SRL.getNode());
2194     AddToWorklist(ADD.getNode());    // Divide by pow2
2195     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2196                   DAG.getConstant(lg2, DL,
2197                                   getShiftAmountTy(ADD.getValueType())));
2198
2199     // If we're dividing by a positive value, we're done.  Otherwise, we must
2200     // negate the result.
2201     if (N1C->getAPIntValue().isNonNegative())
2202       return SRA;
2203
2204     AddToWorklist(SRA.getNode());
2205     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2206   }
2207
2208   // If integer divide is expensive and we satisfy the requirements, emit an
2209   // alternate sequence.
2210   if (N1C && !TLI.isIntDivCheap()) {
2211     SDValue Op = BuildSDIV(N);
2212     if (Op.getNode()) return Op;
2213   }
2214
2215   // undef / X -> 0
2216   if (N0.getOpcode() == ISD::UNDEF)
2217     return DAG.getConstant(0, SDLoc(N), VT);
2218   // X / undef -> undef
2219   if (N1.getOpcode() == ISD::UNDEF)
2220     return N1;
2221
2222   return SDValue();
2223 }
2224
2225 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2226   SDValue N0 = N->getOperand(0);
2227   SDValue N1 = N->getOperand(1);
2228   EVT VT = N->getValueType(0);
2229
2230   // fold vector ops
2231   if (VT.isVector())
2232     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2233       return FoldedVOp;
2234
2235   // fold (udiv c1, c2) -> c1/c2
2236   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2237   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2238   if (N0C && N1C)
2239     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2240                                                     N0C, N1C))
2241       return Folded;
2242   // fold (udiv x, (1 << c)) -> x >>u c
2243   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2244     SDLoc DL(N);
2245     return DAG.getNode(ISD::SRL, DL, VT, N0,
2246                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2247                                        getShiftAmountTy(N0.getValueType())));
2248   }
2249   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2250   if (N1.getOpcode() == ISD::SHL) {
2251     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2252       if (SHC->getAPIntValue().isPowerOf2()) {
2253         EVT ADDVT = N1.getOperand(1).getValueType();
2254         SDLoc DL(N);
2255         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2256                                   N1.getOperand(1),
2257                                   DAG.getConstant(SHC->getAPIntValue()
2258                                                                   .logBase2(),
2259                                                   DL, ADDVT));
2260         AddToWorklist(Add.getNode());
2261         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2262       }
2263     }
2264   }
2265   // fold (udiv x, c) -> alternate
2266   if (N1C && !TLI.isIntDivCheap()) {
2267     SDValue Op = BuildUDIV(N);
2268     if (Op.getNode()) return Op;
2269   }
2270
2271   // undef / X -> 0
2272   if (N0.getOpcode() == ISD::UNDEF)
2273     return DAG.getConstant(0, SDLoc(N), VT);
2274   // X / undef -> undef
2275   if (N1.getOpcode() == ISD::UNDEF)
2276     return N1;
2277
2278   return SDValue();
2279 }
2280
2281 SDValue DAGCombiner::visitSREM(SDNode *N) {
2282   SDValue N0 = N->getOperand(0);
2283   SDValue N1 = N->getOperand(1);
2284   EVT VT = N->getValueType(0);
2285
2286   // fold (srem c1, c2) -> c1%c2
2287   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2288   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2289   if (N0C && N1C)
2290     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2291                                                     N0C, N1C))
2292       return Folded;
2293   // If we know the sign bits of both operands are zero, strength reduce to a
2294   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2295   if (!VT.isVector()) {
2296     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2297       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2298   }
2299
2300   // If X/C can be simplified by the division-by-constant logic, lower
2301   // X%C to the equivalent of X-X/C*C.
2302   if (N1C && !N1C->isNullValue()) {
2303     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2304     AddToWorklist(Div.getNode());
2305     SDValue OptimizedDiv = combine(Div.getNode());
2306     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2307       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2308                                 OptimizedDiv, N1);
2309       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2310       AddToWorklist(Mul.getNode());
2311       return Sub;
2312     }
2313   }
2314
2315   // undef % X -> 0
2316   if (N0.getOpcode() == ISD::UNDEF)
2317     return DAG.getConstant(0, SDLoc(N), VT);
2318   // X % undef -> undef
2319   if (N1.getOpcode() == ISD::UNDEF)
2320     return N1;
2321
2322   return SDValue();
2323 }
2324
2325 SDValue DAGCombiner::visitUREM(SDNode *N) {
2326   SDValue N0 = N->getOperand(0);
2327   SDValue N1 = N->getOperand(1);
2328   EVT VT = N->getValueType(0);
2329
2330   // fold (urem c1, c2) -> c1%c2
2331   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2332   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2333   if (N0C && N1C)
2334     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2335                                                     N0C, N1C))
2336       return Folded;
2337   // fold (urem x, pow2) -> (and x, pow2-1)
2338   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2339       N1C->getAPIntValue().isPowerOf2()) {
2340     SDLoc DL(N);
2341     return DAG.getNode(ISD::AND, DL, VT, N0,
2342                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2343   }
2344   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2345   if (N1.getOpcode() == ISD::SHL) {
2346     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2347       if (SHC->getAPIntValue().isPowerOf2()) {
2348         SDLoc DL(N);
2349         SDValue Add =
2350           DAG.getNode(ISD::ADD, DL, VT, N1,
2351                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2352                                  VT));
2353         AddToWorklist(Add.getNode());
2354         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2355       }
2356     }
2357   }
2358
2359   // If X/C can be simplified by the division-by-constant logic, lower
2360   // X%C to the equivalent of X-X/C*C.
2361   if (N1C && !N1C->isNullValue()) {
2362     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2363     AddToWorklist(Div.getNode());
2364     SDValue OptimizedDiv = combine(Div.getNode());
2365     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2366       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2367                                 OptimizedDiv, N1);
2368       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2369       AddToWorklist(Mul.getNode());
2370       return Sub;
2371     }
2372   }
2373
2374   // undef % X -> 0
2375   if (N0.getOpcode() == ISD::UNDEF)
2376     return DAG.getConstant(0, SDLoc(N), VT);
2377   // X % undef -> undef
2378   if (N1.getOpcode() == ISD::UNDEF)
2379     return N1;
2380
2381   return SDValue();
2382 }
2383
2384 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2385   SDValue N0 = N->getOperand(0);
2386   SDValue N1 = N->getOperand(1);
2387   EVT VT = N->getValueType(0);
2388   SDLoc DL(N);
2389
2390   // fold (mulhs x, 0) -> 0
2391   if (isNullConstant(N1))
2392     return N1;
2393   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2394   if (isOneConstant(N1)) {
2395     SDLoc DL(N);
2396     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2397                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2398                                        DL,
2399                                        getShiftAmountTy(N0.getValueType())));
2400   }
2401   // fold (mulhs x, undef) -> 0
2402   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2403     return DAG.getConstant(0, SDLoc(N), VT);
2404
2405   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2406   // plus a shift.
2407   if (VT.isSimple() && !VT.isVector()) {
2408     MVT Simple = VT.getSimpleVT();
2409     unsigned SimpleSize = Simple.getSizeInBits();
2410     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2411     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2412       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2413       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2414       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2415       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2416             DAG.getConstant(SimpleSize, DL,
2417                             getShiftAmountTy(N1.getValueType())));
2418       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2419     }
2420   }
2421
2422   return SDValue();
2423 }
2424
2425 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2426   SDValue N0 = N->getOperand(0);
2427   SDValue N1 = N->getOperand(1);
2428   EVT VT = N->getValueType(0);
2429   SDLoc DL(N);
2430
2431   // fold (mulhu x, 0) -> 0
2432   if (isNullConstant(N1))
2433     return N1;
2434   // fold (mulhu x, 1) -> 0
2435   if (isOneConstant(N1))
2436     return DAG.getConstant(0, DL, N0.getValueType());
2437   // fold (mulhu x, undef) -> 0
2438   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2439     return DAG.getConstant(0, DL, VT);
2440
2441   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2442   // plus a shift.
2443   if (VT.isSimple() && !VT.isVector()) {
2444     MVT Simple = VT.getSimpleVT();
2445     unsigned SimpleSize = Simple.getSizeInBits();
2446     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2447     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2448       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2449       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2450       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2451       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2452             DAG.getConstant(SimpleSize, DL,
2453                             getShiftAmountTy(N1.getValueType())));
2454       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2455     }
2456   }
2457
2458   return SDValue();
2459 }
2460
2461 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2462 /// give the opcodes for the two computations that are being performed. Return
2463 /// true if a simplification was made.
2464 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2465                                                 unsigned HiOp) {
2466   // If the high half is not needed, just compute the low half.
2467   bool HiExists = N->hasAnyUseOfValue(1);
2468   if (!HiExists &&
2469       (!LegalOperations ||
2470        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2471     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2472     return CombineTo(N, Res, Res);
2473   }
2474
2475   // If the low half is not needed, just compute the high half.
2476   bool LoExists = N->hasAnyUseOfValue(0);
2477   if (!LoExists &&
2478       (!LegalOperations ||
2479        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2480     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2481     return CombineTo(N, Res, Res);
2482   }
2483
2484   // If both halves are used, return as it is.
2485   if (LoExists && HiExists)
2486     return SDValue();
2487
2488   // If the two computed results can be simplified separately, separate them.
2489   if (LoExists) {
2490     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2491     AddToWorklist(Lo.getNode());
2492     SDValue LoOpt = combine(Lo.getNode());
2493     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2494         (!LegalOperations ||
2495          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2496       return CombineTo(N, LoOpt, LoOpt);
2497   }
2498
2499   if (HiExists) {
2500     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2501     AddToWorklist(Hi.getNode());
2502     SDValue HiOpt = combine(Hi.getNode());
2503     if (HiOpt.getNode() && HiOpt != Hi &&
2504         (!LegalOperations ||
2505          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2506       return CombineTo(N, HiOpt, HiOpt);
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2513   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2514   if (Res.getNode()) return Res;
2515
2516   EVT VT = N->getValueType(0);
2517   SDLoc DL(N);
2518
2519   // If the type is twice as wide is legal, transform the mulhu to a wider
2520   // multiply plus a shift.
2521   if (VT.isSimple() && !VT.isVector()) {
2522     MVT Simple = VT.getSimpleVT();
2523     unsigned SimpleSize = Simple.getSizeInBits();
2524     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2525     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2526       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2527       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2528       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2529       // Compute the high part as N1.
2530       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2531             DAG.getConstant(SimpleSize, DL,
2532                             getShiftAmountTy(Lo.getValueType())));
2533       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2534       // Compute the low part as N0.
2535       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2536       return CombineTo(N, Lo, Hi);
2537     }
2538   }
2539
2540   return SDValue();
2541 }
2542
2543 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2544   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2545   if (Res.getNode()) return Res;
2546
2547   EVT VT = N->getValueType(0);
2548   SDLoc DL(N);
2549
2550   // If the type is twice as wide is legal, transform the mulhu to a wider
2551   // multiply plus a shift.
2552   if (VT.isSimple() && !VT.isVector()) {
2553     MVT Simple = VT.getSimpleVT();
2554     unsigned SimpleSize = Simple.getSizeInBits();
2555     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2556     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2557       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2558       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2559       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2560       // Compute the high part as N1.
2561       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2562             DAG.getConstant(SimpleSize, DL,
2563                             getShiftAmountTy(Lo.getValueType())));
2564       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2565       // Compute the low part as N0.
2566       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2567       return CombineTo(N, Lo, Hi);
2568     }
2569   }
2570
2571   return SDValue();
2572 }
2573
2574 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2575   // (smulo x, 2) -> (saddo x, x)
2576   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2577     if (C2->getAPIntValue() == 2)
2578       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2579                          N->getOperand(0), N->getOperand(0));
2580
2581   return SDValue();
2582 }
2583
2584 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2585   // (umulo x, 2) -> (uaddo x, x)
2586   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2587     if (C2->getAPIntValue() == 2)
2588       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2589                          N->getOperand(0), N->getOperand(0));
2590
2591   return SDValue();
2592 }
2593
2594 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2595   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2596   if (Res.getNode()) return Res;
2597
2598   return SDValue();
2599 }
2600
2601 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2602   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2603   if (Res.getNode()) return Res;
2604
2605   return SDValue();
2606 }
2607
2608 /// If this is a binary operator with two operands of the same opcode, try to
2609 /// simplify it.
2610 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2611   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2612   EVT VT = N0.getValueType();
2613   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2614
2615   // Bail early if none of these transforms apply.
2616   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2617
2618   // For each of OP in AND/OR/XOR:
2619   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2620   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2621   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2622   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2623   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2624   //
2625   // do not sink logical op inside of a vector extend, since it may combine
2626   // into a vsetcc.
2627   EVT Op0VT = N0.getOperand(0).getValueType();
2628   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2629        N0.getOpcode() == ISD::SIGN_EXTEND ||
2630        N0.getOpcode() == ISD::BSWAP ||
2631        // Avoid infinite looping with PromoteIntBinOp.
2632        (N0.getOpcode() == ISD::ANY_EXTEND &&
2633         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2634        (N0.getOpcode() == ISD::TRUNCATE &&
2635         (!TLI.isZExtFree(VT, Op0VT) ||
2636          !TLI.isTruncateFree(Op0VT, VT)) &&
2637         TLI.isTypeLegal(Op0VT))) &&
2638       !VT.isVector() &&
2639       Op0VT == N1.getOperand(0).getValueType() &&
2640       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2641     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2642                                  N0.getOperand(0).getValueType(),
2643                                  N0.getOperand(0), N1.getOperand(0));
2644     AddToWorklist(ORNode.getNode());
2645     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2646   }
2647
2648   // For each of OP in SHL/SRL/SRA/AND...
2649   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2650   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2651   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2652   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2653        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2654       N0.getOperand(1) == N1.getOperand(1)) {
2655     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2656                                  N0.getOperand(0).getValueType(),
2657                                  N0.getOperand(0), N1.getOperand(0));
2658     AddToWorklist(ORNode.getNode());
2659     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2660                        ORNode, N0.getOperand(1));
2661   }
2662
2663   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2664   // Only perform this optimization after type legalization and before
2665   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2666   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2667   // we don't want to undo this promotion.
2668   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2669   // on scalars.
2670   if ((N0.getOpcode() == ISD::BITCAST ||
2671        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2672       Level == AfterLegalizeTypes) {
2673     SDValue In0 = N0.getOperand(0);
2674     SDValue In1 = N1.getOperand(0);
2675     EVT In0Ty = In0.getValueType();
2676     EVT In1Ty = In1.getValueType();
2677     SDLoc DL(N);
2678     // If both incoming values are integers, and the original types are the
2679     // same.
2680     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2681       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2682       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2683       AddToWorklist(Op.getNode());
2684       return BC;
2685     }
2686   }
2687
2688   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2689   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2690   // If both shuffles use the same mask, and both shuffle within a single
2691   // vector, then it is worthwhile to move the swizzle after the operation.
2692   // The type-legalizer generates this pattern when loading illegal
2693   // vector types from memory. In many cases this allows additional shuffle
2694   // optimizations.
2695   // There are other cases where moving the shuffle after the xor/and/or
2696   // is profitable even if shuffles don't perform a swizzle.
2697   // If both shuffles use the same mask, and both shuffles have the same first
2698   // or second operand, then it might still be profitable to move the shuffle
2699   // after the xor/and/or operation.
2700   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2701     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2702     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2703
2704     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2705            "Inputs to shuffles are not the same type");
2706
2707     // Check that both shuffles use the same mask. The masks are known to be of
2708     // the same length because the result vector type is the same.
2709     // Check also that shuffles have only one use to avoid introducing extra
2710     // instructions.
2711     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2712         SVN0->getMask().equals(SVN1->getMask())) {
2713       SDValue ShOp = N0->getOperand(1);
2714
2715       // Don't try to fold this node if it requires introducing a
2716       // build vector of all zeros that might be illegal at this stage.
2717       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2718         if (!LegalTypes)
2719           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2720         else
2721           ShOp = SDValue();
2722       }
2723
2724       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2725       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2726       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2727       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2728         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2729                                       N0->getOperand(0), N1->getOperand(0));
2730         AddToWorklist(NewNode.getNode());
2731         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2732                                     &SVN0->getMask()[0]);
2733       }
2734
2735       // Don't try to fold this node if it requires introducing a
2736       // build vector of all zeros that might be illegal at this stage.
2737       ShOp = N0->getOperand(0);
2738       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2739         if (!LegalTypes)
2740           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2741         else
2742           ShOp = SDValue();
2743       }
2744
2745       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2746       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2747       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2748       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2749         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2750                                       N0->getOperand(1), N1->getOperand(1));
2751         AddToWorklist(NewNode.getNode());
2752         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2753                                     &SVN0->getMask()[0]);
2754       }
2755     }
2756   }
2757
2758   return SDValue();
2759 }
2760
2761 /// This contains all DAGCombine rules which reduce two values combined by
2762 /// an And operation to a single value. This makes them reusable in the context
2763 /// of visitSELECT(). Rules involving constants are not included as
2764 /// visitSELECT() already handles those cases.
2765 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2766                                   SDNode *LocReference) {
2767   EVT VT = N1.getValueType();
2768
2769   // fold (and x, undef) -> 0
2770   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2771     return DAG.getConstant(0, SDLoc(LocReference), VT);
2772   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2773   SDValue LL, LR, RL, RR, CC0, CC1;
2774   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2775     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2776     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2777
2778     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2779         LL.getValueType().isInteger()) {
2780       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2781       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2782         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2783                                      LR.getValueType(), LL, RL);
2784         AddToWorklist(ORNode.getNode());
2785         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2786       }
2787       if (isAllOnesConstant(LR)) {
2788         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2789         if (Op1 == ISD::SETEQ) {
2790           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2791                                         LR.getValueType(), LL, RL);
2792           AddToWorklist(ANDNode.getNode());
2793           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2794         }
2795         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2796         if (Op1 == ISD::SETGT) {
2797           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2798                                        LR.getValueType(), LL, RL);
2799           AddToWorklist(ORNode.getNode());
2800           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2801         }
2802       }
2803     }
2804     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2805     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2806         Op0 == Op1 && LL.getValueType().isInteger() &&
2807       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2808                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2809       SDLoc DL(N0);
2810       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2811                                     LL, DAG.getConstant(1, DL,
2812                                                         LL.getValueType()));
2813       AddToWorklist(ADDNode.getNode());
2814       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2815                           DAG.getConstant(2, DL, LL.getValueType()),
2816                           ISD::SETUGE);
2817     }
2818     // canonicalize equivalent to ll == rl
2819     if (LL == RR && LR == RL) {
2820       Op1 = ISD::getSetCCSwappedOperands(Op1);
2821       std::swap(RL, RR);
2822     }
2823     if (LL == RL && LR == RR) {
2824       bool isInteger = LL.getValueType().isInteger();
2825       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2826       if (Result != ISD::SETCC_INVALID &&
2827           (!LegalOperations ||
2828            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2829             TLI.isOperationLegal(ISD::SETCC,
2830                             getSetCCResultType(N0.getSimpleValueType())))))
2831         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2832                             LL, LR, Result);
2833     }
2834   }
2835
2836   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2837       VT.getSizeInBits() <= 64) {
2838     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2839       APInt ADDC = ADDI->getAPIntValue();
2840       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2841         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2842         // immediate for an add, but it is legal if its top c2 bits are set,
2843         // transform the ADD so the immediate doesn't need to be materialized
2844         // in a register.
2845         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2846           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2847                                              SRLI->getZExtValue());
2848           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2849             ADDC |= Mask;
2850             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2851               SDLoc DL(N0);
2852               SDValue NewAdd =
2853                 DAG.getNode(ISD::ADD, DL, VT,
2854                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2855               CombineTo(N0.getNode(), NewAdd);
2856               // Return N so it doesn't get rechecked!
2857               return SDValue(LocReference, 0);
2858             }
2859           }
2860         }
2861       }
2862     }
2863   }
2864
2865   return SDValue();
2866 }
2867
2868 SDValue DAGCombiner::visitAND(SDNode *N) {
2869   SDValue N0 = N->getOperand(0);
2870   SDValue N1 = N->getOperand(1);
2871   EVT VT = N1.getValueType();
2872
2873   // fold vector ops
2874   if (VT.isVector()) {
2875     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2876       return FoldedVOp;
2877
2878     // fold (and x, 0) -> 0, vector edition
2879     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2880       // do not return N0, because undef node may exist in N0
2881       return DAG.getConstant(
2882           APInt::getNullValue(
2883               N0.getValueType().getScalarType().getSizeInBits()),
2884           SDLoc(N), N0.getValueType());
2885     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2886       // do not return N1, because undef node may exist in N1
2887       return DAG.getConstant(
2888           APInt::getNullValue(
2889               N1.getValueType().getScalarType().getSizeInBits()),
2890           SDLoc(N), N1.getValueType());
2891
2892     // fold (and x, -1) -> x, vector edition
2893     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2894       return N1;
2895     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2896       return N0;
2897   }
2898
2899   // fold (and c1, c2) -> c1&c2
2900   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2901   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2902   if (N0C && N1C && !N1C->isOpaque())
2903     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2904   // canonicalize constant to RHS
2905   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2906      !isConstantIntBuildVectorOrConstantInt(N1))
2907     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2908   // fold (and x, -1) -> x
2909   if (isAllOnesConstant(N1))
2910     return N0;
2911   // if (and x, c) is known to be zero, return 0
2912   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2913   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2914                                    APInt::getAllOnesValue(BitWidth)))
2915     return DAG.getConstant(0, SDLoc(N), VT);
2916   // reassociate and
2917   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2918     return RAND;
2919   // fold (and (or x, C), D) -> D if (C & D) == D
2920   if (N1C && N0.getOpcode() == ISD::OR)
2921     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2922       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2923         return N1;
2924   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2925   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2926     SDValue N0Op0 = N0.getOperand(0);
2927     APInt Mask = ~N1C->getAPIntValue();
2928     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2929     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2930       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2931                                  N0.getValueType(), N0Op0);
2932
2933       // Replace uses of the AND with uses of the Zero extend node.
2934       CombineTo(N, Zext);
2935
2936       // We actually want to replace all uses of the any_extend with the
2937       // zero_extend, to avoid duplicating things.  This will later cause this
2938       // AND to be folded.
2939       CombineTo(N0.getNode(), Zext);
2940       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2941     }
2942   }
2943   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2944   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2945   // already be zero by virtue of the width of the base type of the load.
2946   //
2947   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2948   // more cases.
2949   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2950        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2951       N0.getOpcode() == ISD::LOAD) {
2952     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2953                                          N0 : N0.getOperand(0) );
2954
2955     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2956     // This can be a pure constant or a vector splat, in which case we treat the
2957     // vector as a scalar and use the splat value.
2958     APInt Constant = APInt::getNullValue(1);
2959     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2960       Constant = C->getAPIntValue();
2961     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2962       APInt SplatValue, SplatUndef;
2963       unsigned SplatBitSize;
2964       bool HasAnyUndefs;
2965       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2966                                              SplatBitSize, HasAnyUndefs);
2967       if (IsSplat) {
2968         // Undef bits can contribute to a possible optimisation if set, so
2969         // set them.
2970         SplatValue |= SplatUndef;
2971
2972         // The splat value may be something like "0x00FFFFFF", which means 0 for
2973         // the first vector value and FF for the rest, repeating. We need a mask
2974         // that will apply equally to all members of the vector, so AND all the
2975         // lanes of the constant together.
2976         EVT VT = Vector->getValueType(0);
2977         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2978
2979         // If the splat value has been compressed to a bitlength lower
2980         // than the size of the vector lane, we need to re-expand it to
2981         // the lane size.
2982         if (BitWidth > SplatBitSize)
2983           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2984                SplatBitSize < BitWidth;
2985                SplatBitSize = SplatBitSize * 2)
2986             SplatValue |= SplatValue.shl(SplatBitSize);
2987
2988         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2989         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2990         if (SplatBitSize % BitWidth == 0) {
2991           Constant = APInt::getAllOnesValue(BitWidth);
2992           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2993             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2994         }
2995       }
2996     }
2997
2998     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2999     // actually legal and isn't going to get expanded, else this is a false
3000     // optimisation.
3001     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3002                                                     Load->getValueType(0),
3003                                                     Load->getMemoryVT());
3004
3005     // Resize the constant to the same size as the original memory access before
3006     // extension. If it is still the AllOnesValue then this AND is completely
3007     // unneeded.
3008     Constant =
3009       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3010
3011     bool B;
3012     switch (Load->getExtensionType()) {
3013     default: B = false; break;
3014     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3015     case ISD::ZEXTLOAD:
3016     case ISD::NON_EXTLOAD: B = true; break;
3017     }
3018
3019     if (B && Constant.isAllOnesValue()) {
3020       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3021       // preserve semantics once we get rid of the AND.
3022       SDValue NewLoad(Load, 0);
3023       if (Load->getExtensionType() == ISD::EXTLOAD) {
3024         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3025                               Load->getValueType(0), SDLoc(Load),
3026                               Load->getChain(), Load->getBasePtr(),
3027                               Load->getOffset(), Load->getMemoryVT(),
3028                               Load->getMemOperand());
3029         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3030         if (Load->getNumValues() == 3) {
3031           // PRE/POST_INC loads have 3 values.
3032           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3033                            NewLoad.getValue(2) };
3034           CombineTo(Load, To, 3, true);
3035         } else {
3036           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3037         }
3038       }
3039
3040       // Fold the AND away, taking care not to fold to the old load node if we
3041       // replaced it.
3042       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3043
3044       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3045     }
3046   }
3047
3048   // fold (and (load x), 255) -> (zextload x, i8)
3049   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3050   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3051   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3052               (N0.getOpcode() == ISD::ANY_EXTEND &&
3053                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3054     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3055     LoadSDNode *LN0 = HasAnyExt
3056       ? cast<LoadSDNode>(N0.getOperand(0))
3057       : cast<LoadSDNode>(N0);
3058     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3059         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3060       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3061       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3062         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3063         EVT LoadedVT = LN0->getMemoryVT();
3064         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3065
3066         if (ExtVT == LoadedVT &&
3067             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3068                                                     ExtVT))) {
3069
3070           SDValue NewLoad =
3071             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3072                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3073                            LN0->getMemOperand());
3074           AddToWorklist(N);
3075           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3076           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3077         }
3078
3079         // Do not change the width of a volatile load.
3080         // Do not generate loads of non-round integer types since these can
3081         // be expensive (and would be wrong if the type is not byte sized).
3082         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3083             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3084                                                     ExtVT))) {
3085           EVT PtrType = LN0->getOperand(1).getValueType();
3086
3087           unsigned Alignment = LN0->getAlignment();
3088           SDValue NewPtr = LN0->getBasePtr();
3089
3090           // For big endian targets, we need to add an offset to the pointer
3091           // to load the correct bytes.  For little endian systems, we merely
3092           // need to read fewer bytes from the same pointer.
3093           if (TLI.isBigEndian()) {
3094             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3095             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3096             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3097             SDLoc DL(LN0);
3098             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3099                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3100             Alignment = MinAlign(Alignment, PtrOff);
3101           }
3102
3103           AddToWorklist(NewPtr.getNode());
3104
3105           SDValue Load =
3106             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3107                            LN0->getChain(), NewPtr,
3108                            LN0->getPointerInfo(),
3109                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3110                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3111           AddToWorklist(N);
3112           CombineTo(LN0, Load, Load.getValue(1));
3113           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3114         }
3115       }
3116     }
3117   }
3118
3119   if (SDValue Combined = visitANDLike(N0, N1, N))
3120     return Combined;
3121
3122   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3123   if (N0.getOpcode() == N1.getOpcode()) {
3124     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3125     if (Tmp.getNode()) return Tmp;
3126   }
3127
3128   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3129   // fold (and (sra)) -> (and (srl)) when possible.
3130   if (!VT.isVector() &&
3131       SimplifyDemandedBits(SDValue(N, 0)))
3132     return SDValue(N, 0);
3133
3134   // fold (zext_inreg (extload x)) -> (zextload x)
3135   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3136     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3137     EVT MemVT = LN0->getMemoryVT();
3138     // If we zero all the possible extended bits, then we can turn this into
3139     // a zextload if we are running before legalize or the operation is legal.
3140     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3141     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3142                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3143         ((!LegalOperations && !LN0->isVolatile()) ||
3144          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3145       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3146                                        LN0->getChain(), LN0->getBasePtr(),
3147                                        MemVT, LN0->getMemOperand());
3148       AddToWorklist(N);
3149       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3150       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3151     }
3152   }
3153   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3154   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3155       N0.hasOneUse()) {
3156     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3157     EVT MemVT = LN0->getMemoryVT();
3158     // If we zero all the possible extended bits, then we can turn this into
3159     // a zextload if we are running before legalize or the operation is legal.
3160     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3161     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3162                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3163         ((!LegalOperations && !LN0->isVolatile()) ||
3164          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3165       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3166                                        LN0->getChain(), LN0->getBasePtr(),
3167                                        MemVT, LN0->getMemOperand());
3168       AddToWorklist(N);
3169       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3170       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3171     }
3172   }
3173   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3174   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3175     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3176                                        N0.getOperand(1), false);
3177     if (BSwap.getNode())
3178       return BSwap;
3179   }
3180
3181   return SDValue();
3182 }
3183
3184 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3185 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3186                                         bool DemandHighBits) {
3187   if (!LegalOperations)
3188     return SDValue();
3189
3190   EVT VT = N->getValueType(0);
3191   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3192     return SDValue();
3193   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3194     return SDValue();
3195
3196   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3197   bool LookPassAnd0 = false;
3198   bool LookPassAnd1 = false;
3199   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3200       std::swap(N0, N1);
3201   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3202       std::swap(N0, N1);
3203   if (N0.getOpcode() == ISD::AND) {
3204     if (!N0.getNode()->hasOneUse())
3205       return SDValue();
3206     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207     if (!N01C || N01C->getZExtValue() != 0xFF00)
3208       return SDValue();
3209     N0 = N0.getOperand(0);
3210     LookPassAnd0 = true;
3211   }
3212
3213   if (N1.getOpcode() == ISD::AND) {
3214     if (!N1.getNode()->hasOneUse())
3215       return SDValue();
3216     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3217     if (!N11C || N11C->getZExtValue() != 0xFF)
3218       return SDValue();
3219     N1 = N1.getOperand(0);
3220     LookPassAnd1 = true;
3221   }
3222
3223   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3224     std::swap(N0, N1);
3225   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3226     return SDValue();
3227   if (!N0.getNode()->hasOneUse() ||
3228       !N1.getNode()->hasOneUse())
3229     return SDValue();
3230
3231   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3232   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3233   if (!N01C || !N11C)
3234     return SDValue();
3235   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3236     return SDValue();
3237
3238   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3239   SDValue N00 = N0->getOperand(0);
3240   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3241     if (!N00.getNode()->hasOneUse())
3242       return SDValue();
3243     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3244     if (!N001C || N001C->getZExtValue() != 0xFF)
3245       return SDValue();
3246     N00 = N00.getOperand(0);
3247     LookPassAnd0 = true;
3248   }
3249
3250   SDValue N10 = N1->getOperand(0);
3251   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3252     if (!N10.getNode()->hasOneUse())
3253       return SDValue();
3254     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3255     if (!N101C || N101C->getZExtValue() != 0xFF00)
3256       return SDValue();
3257     N10 = N10.getOperand(0);
3258     LookPassAnd1 = true;
3259   }
3260
3261   if (N00 != N10)
3262     return SDValue();
3263
3264   // Make sure everything beyond the low halfword gets set to zero since the SRL
3265   // 16 will clear the top bits.
3266   unsigned OpSizeInBits = VT.getSizeInBits();
3267   if (DemandHighBits && OpSizeInBits > 16) {
3268     // If the left-shift isn't masked out then the only way this is a bswap is
3269     // if all bits beyond the low 8 are 0. In that case the entire pattern
3270     // reduces to a left shift anyway: leave it for other parts of the combiner.
3271     if (!LookPassAnd0)
3272       return SDValue();
3273
3274     // However, if the right shift isn't masked out then it might be because
3275     // it's not needed. See if we can spot that too.
3276     if (!LookPassAnd1 &&
3277         !DAG.MaskedValueIsZero(
3278             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3279       return SDValue();
3280   }
3281
3282   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3283   if (OpSizeInBits > 16) {
3284     SDLoc DL(N);
3285     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3286                       DAG.getConstant(OpSizeInBits - 16, DL,
3287                                       getShiftAmountTy(VT)));
3288   }
3289   return Res;
3290 }
3291
3292 /// Return true if the specified node is an element that makes up a 32-bit
3293 /// packed halfword byteswap.
3294 /// ((x & 0x000000ff) << 8) |
3295 /// ((x & 0x0000ff00) >> 8) |
3296 /// ((x & 0x00ff0000) << 8) |
3297 /// ((x & 0xff000000) >> 8)
3298 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3299   if (!N.getNode()->hasOneUse())
3300     return false;
3301
3302   unsigned Opc = N.getOpcode();
3303   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3304     return false;
3305
3306   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3307   if (!N1C)
3308     return false;
3309
3310   unsigned Num;
3311   switch (N1C->getZExtValue()) {
3312   default:
3313     return false;
3314   case 0xFF:       Num = 0; break;
3315   case 0xFF00:     Num = 1; break;
3316   case 0xFF0000:   Num = 2; break;
3317   case 0xFF000000: Num = 3; break;
3318   }
3319
3320   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3321   SDValue N0 = N.getOperand(0);
3322   if (Opc == ISD::AND) {
3323     if (Num == 0 || Num == 2) {
3324       // (x >> 8) & 0xff
3325       // (x >> 8) & 0xff0000
3326       if (N0.getOpcode() != ISD::SRL)
3327         return false;
3328       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3329       if (!C || C->getZExtValue() != 8)
3330         return false;
3331     } else {
3332       // (x << 8) & 0xff00
3333       // (x << 8) & 0xff000000
3334       if (N0.getOpcode() != ISD::SHL)
3335         return false;
3336       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3337       if (!C || C->getZExtValue() != 8)
3338         return false;
3339     }
3340   } else if (Opc == ISD::SHL) {
3341     // (x & 0xff) << 8
3342     // (x & 0xff0000) << 8
3343     if (Num != 0 && Num != 2)
3344       return false;
3345     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3346     if (!C || C->getZExtValue() != 8)
3347       return false;
3348   } else { // Opc == ISD::SRL
3349     // (x & 0xff00) >> 8
3350     // (x & 0xff000000) >> 8
3351     if (Num != 1 && Num != 3)
3352       return false;
3353     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3354     if (!C || C->getZExtValue() != 8)
3355       return false;
3356   }
3357
3358   if (Parts[Num])
3359     return false;
3360
3361   Parts[Num] = N0.getOperand(0).getNode();
3362   return true;
3363 }
3364
3365 /// Match a 32-bit packed halfword bswap. That is
3366 /// ((x & 0x000000ff) << 8) |
3367 /// ((x & 0x0000ff00) >> 8) |
3368 /// ((x & 0x00ff0000) << 8) |
3369 /// ((x & 0xff000000) >> 8)
3370 /// => (rotl (bswap x), 16)
3371 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3372   if (!LegalOperations)
3373     return SDValue();
3374
3375   EVT VT = N->getValueType(0);
3376   if (VT != MVT::i32)
3377     return SDValue();
3378   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3379     return SDValue();
3380
3381   // Look for either
3382   // (or (or (and), (and)), (or (and), (and)))
3383   // (or (or (or (and), (and)), (and)), (and))
3384   if (N0.getOpcode() != ISD::OR)
3385     return SDValue();
3386   SDValue N00 = N0.getOperand(0);
3387   SDValue N01 = N0.getOperand(1);
3388   SDNode *Parts[4] = {};
3389
3390   if (N1.getOpcode() == ISD::OR &&
3391       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3392     // (or (or (and), (and)), (or (and), (and)))
3393     SDValue N000 = N00.getOperand(0);
3394     if (!isBSwapHWordElement(N000, Parts))
3395       return SDValue();
3396
3397     SDValue N001 = N00.getOperand(1);
3398     if (!isBSwapHWordElement(N001, Parts))
3399       return SDValue();
3400     SDValue N010 = N01.getOperand(0);
3401     if (!isBSwapHWordElement(N010, Parts))
3402       return SDValue();
3403     SDValue N011 = N01.getOperand(1);
3404     if (!isBSwapHWordElement(N011, Parts))
3405       return SDValue();
3406   } else {
3407     // (or (or (or (and), (and)), (and)), (and))
3408     if (!isBSwapHWordElement(N1, Parts))
3409       return SDValue();
3410     if (!isBSwapHWordElement(N01, Parts))
3411       return SDValue();
3412     if (N00.getOpcode() != ISD::OR)
3413       return SDValue();
3414     SDValue N000 = N00.getOperand(0);
3415     if (!isBSwapHWordElement(N000, Parts))
3416       return SDValue();
3417     SDValue N001 = N00.getOperand(1);
3418     if (!isBSwapHWordElement(N001, Parts))
3419       return SDValue();
3420   }
3421
3422   // Make sure the parts are all coming from the same node.
3423   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3424     return SDValue();
3425
3426   SDLoc DL(N);
3427   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3428                               SDValue(Parts[0], 0));
3429
3430   // Result of the bswap should be rotated by 16. If it's not legal, then
3431   // do  (x << 16) | (x >> 16).
3432   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3433   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3434     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3435   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3436     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3437   return DAG.getNode(ISD::OR, DL, VT,
3438                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3439                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3440 }
3441
3442 /// This contains all DAGCombine rules which reduce two values combined by
3443 /// an Or operation to a single value \see visitANDLike().
3444 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3445   EVT VT = N1.getValueType();
3446   // fold (or x, undef) -> -1
3447   if (!LegalOperations &&
3448       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3449     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3450     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3451                            SDLoc(LocReference), VT);
3452   }
3453   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3454   SDValue LL, LR, RL, RR, CC0, CC1;
3455   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3456     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3457     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3458
3459     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3460       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3461       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3462       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3463         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3464                                      LR.getValueType(), LL, RL);
3465         AddToWorklist(ORNode.getNode());
3466         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3467       }
3468       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3469       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3470       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3471         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3472                                       LR.getValueType(), LL, RL);
3473         AddToWorklist(ANDNode.getNode());
3474         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3475       }
3476     }
3477     // canonicalize equivalent to ll == rl
3478     if (LL == RR && LR == RL) {
3479       Op1 = ISD::getSetCCSwappedOperands(Op1);
3480       std::swap(RL, RR);
3481     }
3482     if (LL == RL && LR == RR) {
3483       bool isInteger = LL.getValueType().isInteger();
3484       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3485       if (Result != ISD::SETCC_INVALID &&
3486           (!LegalOperations ||
3487            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3488             TLI.isOperationLegal(ISD::SETCC,
3489               getSetCCResultType(N0.getValueType())))))
3490         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3491                             LL, LR, Result);
3492     }
3493   }
3494
3495   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3496   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3497       // Don't increase # computations.
3498       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3499     // We can only do this xform if we know that bits from X that are set in C2
3500     // but not in C1 are already zero.  Likewise for Y.
3501     if (const ConstantSDNode *N0O1C =
3502         getAsNonOpaqueConstant(N0.getOperand(1))) {
3503       if (const ConstantSDNode *N1O1C =
3504           getAsNonOpaqueConstant(N1.getOperand(1))) {
3505         // We can only do this xform if we know that bits from X that are set in
3506         // C2 but not in C1 are already zero.  Likewise for Y.
3507         const APInt &LHSMask = N0O1C->getAPIntValue();
3508         const APInt &RHSMask = N1O1C->getAPIntValue();
3509
3510         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3511             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3512           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3513                                   N0.getOperand(0), N1.getOperand(0));
3514           SDLoc DL(LocReference);
3515           return DAG.getNode(ISD::AND, DL, VT, X,
3516                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3517         }
3518       }
3519     }
3520   }
3521
3522   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3523   if (N0.getOpcode() == ISD::AND &&
3524       N1.getOpcode() == ISD::AND &&
3525       N0.getOperand(0) == N1.getOperand(0) &&
3526       // Don't increase # computations.
3527       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3528     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3529                             N0.getOperand(1), N1.getOperand(1));
3530     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3531   }
3532
3533   return SDValue();
3534 }
3535
3536 SDValue DAGCombiner::visitOR(SDNode *N) {
3537   SDValue N0 = N->getOperand(0);
3538   SDValue N1 = N->getOperand(1);
3539   EVT VT = N1.getValueType();
3540
3541   // fold vector ops
3542   if (VT.isVector()) {
3543     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3544       return FoldedVOp;
3545
3546     // fold (or x, 0) -> x, vector edition
3547     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3548       return N1;
3549     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3550       return N0;
3551
3552     // fold (or x, -1) -> -1, vector edition
3553     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3554       // do not return N0, because undef node may exist in N0
3555       return DAG.getConstant(
3556           APInt::getAllOnesValue(
3557               N0.getValueType().getScalarType().getSizeInBits()),
3558           SDLoc(N), N0.getValueType());
3559     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3560       // do not return N1, because undef node may exist in N1
3561       return DAG.getConstant(
3562           APInt::getAllOnesValue(
3563               N1.getValueType().getScalarType().getSizeInBits()),
3564           SDLoc(N), N1.getValueType());
3565
3566     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3567     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3568     // Do this only if the resulting shuffle is legal.
3569     if (isa<ShuffleVectorSDNode>(N0) &&
3570         isa<ShuffleVectorSDNode>(N1) &&
3571         // Avoid folding a node with illegal type.
3572         TLI.isTypeLegal(VT) &&
3573         N0->getOperand(1) == N1->getOperand(1) &&
3574         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3575       bool CanFold = true;
3576       unsigned NumElts = VT.getVectorNumElements();
3577       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3578       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3579       // We construct two shuffle masks:
3580       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3581       // and N1 as the second operand.
3582       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3583       // and N0 as the second operand.
3584       // We do this because OR is commutable and therefore there might be
3585       // two ways to fold this node into a shuffle.
3586       SmallVector<int,4> Mask1;
3587       SmallVector<int,4> Mask2;
3588
3589       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3590         int M0 = SV0->getMaskElt(i);
3591         int M1 = SV1->getMaskElt(i);
3592
3593         // Both shuffle indexes are undef. Propagate Undef.
3594         if (M0 < 0 && M1 < 0) {
3595           Mask1.push_back(M0);
3596           Mask2.push_back(M0);
3597           continue;
3598         }
3599
3600         if (M0 < 0 || M1 < 0 ||
3601             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3602             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3603           CanFold = false;
3604           break;
3605         }
3606
3607         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3608         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3609       }
3610
3611       if (CanFold) {
3612         // Fold this sequence only if the resulting shuffle is 'legal'.
3613         if (TLI.isShuffleMaskLegal(Mask1, VT))
3614           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3615                                       N1->getOperand(0), &Mask1[0]);
3616         if (TLI.isShuffleMaskLegal(Mask2, VT))
3617           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3618                                       N0->getOperand(0), &Mask2[0]);
3619       }
3620     }
3621   }
3622
3623   // fold (or c1, c2) -> c1|c2
3624   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3625   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3626   if (N0C && N1C && !N1C->isOpaque())
3627     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3628   // canonicalize constant to RHS
3629   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3630      !isConstantIntBuildVectorOrConstantInt(N1))
3631     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3632   // fold (or x, 0) -> x
3633   if (isNullConstant(N1))
3634     return N0;
3635   // fold (or x, -1) -> -1
3636   if (isAllOnesConstant(N1))
3637     return N1;
3638   // fold (or x, c) -> c iff (x & ~c) == 0
3639   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3640     return N1;
3641
3642   if (SDValue Combined = visitORLike(N0, N1, N))
3643     return Combined;
3644
3645   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3646   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3647   if (BSwap.getNode())
3648     return BSwap;
3649   BSwap = MatchBSwapHWordLow(N, N0, N1);
3650   if (BSwap.getNode())
3651     return BSwap;
3652
3653   // reassociate or
3654   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3655     return ROR;
3656   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3657   // iff (c1 & c2) == 0.
3658   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3659              isa<ConstantSDNode>(N0.getOperand(1))) {
3660     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3661     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3662       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3663                                                    N1C, C1))
3664         return DAG.getNode(
3665             ISD::AND, SDLoc(N), VT,
3666             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3667       return SDValue();
3668     }
3669   }
3670   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3671   if (N0.getOpcode() == N1.getOpcode()) {
3672     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3673     if (Tmp.getNode()) return Tmp;
3674   }
3675
3676   // See if this is some rotate idiom.
3677   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3678     return SDValue(Rot, 0);
3679
3680   // Simplify the operands using demanded-bits information.
3681   if (!VT.isVector() &&
3682       SimplifyDemandedBits(SDValue(N, 0)))
3683     return SDValue(N, 0);
3684
3685   return SDValue();
3686 }
3687
3688 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3689 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3690   if (Op.getOpcode() == ISD::AND) {
3691     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3692       Mask = Op.getOperand(1);
3693       Op = Op.getOperand(0);
3694     } else {
3695       return false;
3696     }
3697   }
3698
3699   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3700     Shift = Op;
3701     return true;
3702   }
3703
3704   return false;
3705 }
3706
3707 // Return true if we can prove that, whenever Neg and Pos are both in the
3708 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3709 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3710 //
3711 //     (or (shift1 X, Neg), (shift2 X, Pos))
3712 //
3713 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3714 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3715 // to consider shift amounts with defined behavior.
3716 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3717   // If OpSize is a power of 2 then:
3718   //
3719   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3720   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3721   //
3722   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3723   // for the stronger condition:
3724   //
3725   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3726   //
3727   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3728   // we can just replace Neg with Neg' for the rest of the function.
3729   //
3730   // In other cases we check for the even stronger condition:
3731   //
3732   //     Neg == OpSize - Pos                                    [B]
3733   //
3734   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3735   // behavior if Pos == 0 (and consequently Neg == OpSize).
3736   //
3737   // We could actually use [A] whenever OpSize is a power of 2, but the
3738   // only extra cases that it would match are those uninteresting ones
3739   // where Neg and Pos are never in range at the same time.  E.g. for
3740   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3741   // as well as (sub 32, Pos), but:
3742   //
3743   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3744   //
3745   // always invokes undefined behavior for 32-bit X.
3746   //
3747   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3748   unsigned MaskLoBits = 0;
3749   if (Neg.getOpcode() == ISD::AND &&
3750       isPowerOf2_64(OpSize) &&
3751       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3752       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3753     Neg = Neg.getOperand(0);
3754     MaskLoBits = Log2_64(OpSize);
3755   }
3756
3757   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3758   if (Neg.getOpcode() != ISD::SUB)
3759     return 0;
3760   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3761   if (!NegC)
3762     return 0;
3763   SDValue NegOp1 = Neg.getOperand(1);
3764
3765   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3766   // Pos'.  The truncation is redundant for the purpose of the equality.
3767   if (MaskLoBits &&
3768       Pos.getOpcode() == ISD::AND &&
3769       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3770       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3771     Pos = Pos.getOperand(0);
3772
3773   // The condition we need is now:
3774   //
3775   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3776   //
3777   // If NegOp1 == Pos then we need:
3778   //
3779   //              OpSize & Mask == NegC & Mask
3780   //
3781   // (because "x & Mask" is a truncation and distributes through subtraction).
3782   APInt Width;
3783   if (Pos == NegOp1)
3784     Width = NegC->getAPIntValue();
3785   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3786   // Then the condition we want to prove becomes:
3787   //
3788   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3789   //
3790   // which, again because "x & Mask" is a truncation, becomes:
3791   //
3792   //                NegC & Mask == (OpSize - PosC) & Mask
3793   //              OpSize & Mask == (NegC + PosC) & Mask
3794   else if (Pos.getOpcode() == ISD::ADD &&
3795            Pos.getOperand(0) == NegOp1 &&
3796            Pos.getOperand(1).getOpcode() == ISD::Constant)
3797     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3798              NegC->getAPIntValue());
3799   else
3800     return false;
3801
3802   // Now we just need to check that OpSize & Mask == Width & Mask.
3803   if (MaskLoBits)
3804     // Opsize & Mask is 0 since Mask is Opsize - 1.
3805     return Width.getLoBits(MaskLoBits) == 0;
3806   return Width == OpSize;
3807 }
3808
3809 // A subroutine of MatchRotate used once we have found an OR of two opposite
3810 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3811 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3812 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3813 // Neg with outer conversions stripped away.
3814 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3815                                        SDValue Neg, SDValue InnerPos,
3816                                        SDValue InnerNeg, unsigned PosOpcode,
3817                                        unsigned NegOpcode, SDLoc DL) {
3818   // fold (or (shl x, (*ext y)),
3819   //          (srl x, (*ext (sub 32, y)))) ->
3820   //   (rotl x, y) or (rotr x, (sub 32, y))
3821   //
3822   // fold (or (shl x, (*ext (sub 32, y))),
3823   //          (srl x, (*ext y))) ->
3824   //   (rotr x, y) or (rotl x, (sub 32, y))
3825   EVT VT = Shifted.getValueType();
3826   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3827     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3828     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3829                        HasPos ? Pos : Neg).getNode();
3830   }
3831
3832   return nullptr;
3833 }
3834
3835 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3836 // idioms for rotate, and if the target supports rotation instructions, generate
3837 // a rot[lr].
3838 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3839   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3840   EVT VT = LHS.getValueType();
3841   if (!TLI.isTypeLegal(VT)) return nullptr;
3842
3843   // The target must have at least one rotate flavor.
3844   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3845   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3846   if (!HasROTL && !HasROTR) return nullptr;
3847
3848   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3849   SDValue LHSShift;   // The shift.
3850   SDValue LHSMask;    // AND value if any.
3851   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3852     return nullptr; // Not part of a rotate.
3853
3854   SDValue RHSShift;   // The shift.
3855   SDValue RHSMask;    // AND value if any.
3856   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3857     return nullptr; // Not part of a rotate.
3858
3859   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3860     return nullptr;   // Not shifting the same value.
3861
3862   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3863     return nullptr;   // Shifts must disagree.
3864
3865   // Canonicalize shl to left side in a shl/srl pair.
3866   if (RHSShift.getOpcode() == ISD::SHL) {
3867     std::swap(LHS, RHS);
3868     std::swap(LHSShift, RHSShift);
3869     std::swap(LHSMask , RHSMask );
3870   }
3871
3872   unsigned OpSizeInBits = VT.getSizeInBits();
3873   SDValue LHSShiftArg = LHSShift.getOperand(0);
3874   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3875   SDValue RHSShiftArg = RHSShift.getOperand(0);
3876   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3877
3878   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3879   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3880   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3881       RHSShiftAmt.getOpcode() == ISD::Constant) {
3882     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3883     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3884     if ((LShVal + RShVal) != OpSizeInBits)
3885       return nullptr;
3886
3887     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3888                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3889
3890     // If there is an AND of either shifted operand, apply it to the result.
3891     if (LHSMask.getNode() || RHSMask.getNode()) {
3892       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3893
3894       if (LHSMask.getNode()) {
3895         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3896         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3897       }
3898       if (RHSMask.getNode()) {
3899         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3900         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3901       }
3902
3903       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3904     }
3905
3906     return Rot.getNode();
3907   }
3908
3909   // If there is a mask here, and we have a variable shift, we can't be sure
3910   // that we're masking out the right stuff.
3911   if (LHSMask.getNode() || RHSMask.getNode())
3912     return nullptr;
3913
3914   // If the shift amount is sign/zext/any-extended just peel it off.
3915   SDValue LExtOp0 = LHSShiftAmt;
3916   SDValue RExtOp0 = RHSShiftAmt;
3917   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3918        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3919        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3920        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3921       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3922        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3923        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3924        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3925     LExtOp0 = LHSShiftAmt.getOperand(0);
3926     RExtOp0 = RHSShiftAmt.getOperand(0);
3927   }
3928
3929   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3930                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3931   if (TryL)
3932     return TryL;
3933
3934   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3935                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3936   if (TryR)
3937     return TryR;
3938
3939   return nullptr;
3940 }
3941
3942 SDValue DAGCombiner::visitXOR(SDNode *N) {
3943   SDValue N0 = N->getOperand(0);
3944   SDValue N1 = N->getOperand(1);
3945   EVT VT = N0.getValueType();
3946
3947   // fold vector ops
3948   if (VT.isVector()) {
3949     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3950       return FoldedVOp;
3951
3952     // fold (xor x, 0) -> x, vector edition
3953     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3954       return N1;
3955     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3956       return N0;
3957   }
3958
3959   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3960   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3961     return DAG.getConstant(0, SDLoc(N), VT);
3962   // fold (xor x, undef) -> undef
3963   if (N0.getOpcode() == ISD::UNDEF)
3964     return N0;
3965   if (N1.getOpcode() == ISD::UNDEF)
3966     return N1;
3967   // fold (xor c1, c2) -> c1^c2
3968   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3969   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3970   if (N0C && N1C)
3971     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3972   // canonicalize constant to RHS
3973   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3974      !isConstantIntBuildVectorOrConstantInt(N1))
3975     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3976   // fold (xor x, 0) -> x
3977   if (isNullConstant(N1))
3978     return N0;
3979   // reassociate xor
3980   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3981     return RXOR;
3982
3983   // fold !(x cc y) -> (x !cc y)
3984   SDValue LHS, RHS, CC;
3985   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3986     bool isInt = LHS.getValueType().isInteger();
3987     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3988                                                isInt);
3989
3990     if (!LegalOperations ||
3991         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3992       switch (N0.getOpcode()) {
3993       default:
3994         llvm_unreachable("Unhandled SetCC Equivalent!");
3995       case ISD::SETCC:
3996         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3997       case ISD::SELECT_CC:
3998         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3999                                N0.getOperand(3), NotCC);
4000       }
4001     }
4002   }
4003
4004   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4005   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4006       N0.getNode()->hasOneUse() &&
4007       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4008     SDValue V = N0.getOperand(0);
4009     SDLoc DL(N0);
4010     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4011                     DAG.getConstant(1, DL, V.getValueType()));
4012     AddToWorklist(V.getNode());
4013     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4014   }
4015
4016   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4017   if (isOneConstant(N1) && VT == MVT::i1 &&
4018       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4019     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4020     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4021       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4022       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4023       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4024       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4025       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4026     }
4027   }
4028   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4029   if (isAllOnesConstant(N1) &&
4030       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4031     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4032     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4033       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4034       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4035       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4036       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4037       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4038     }
4039   }
4040   // fold (xor (and x, y), y) -> (and (not x), y)
4041   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4042       N0->getOperand(1) == N1) {
4043     SDValue X = N0->getOperand(0);
4044     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4045     AddToWorklist(NotX.getNode());
4046     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4047   }
4048   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4049   if (N1C && N0.getOpcode() == ISD::XOR) {
4050     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4051       SDLoc DL(N);
4052       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4053                          DAG.getConstant(N1C->getAPIntValue() ^
4054                                          N00C->getAPIntValue(), DL, VT));
4055     }
4056     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4057       SDLoc DL(N);
4058       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4059                          DAG.getConstant(N1C->getAPIntValue() ^
4060                                          N01C->getAPIntValue(), DL, VT));
4061     }
4062   }
4063   // fold (xor x, x) -> 0
4064   if (N0 == N1)
4065     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4066
4067   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4068   // Here is a concrete example of this equivalence:
4069   // i16   x ==  14
4070   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4071   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4072   //
4073   // =>
4074   //
4075   // i16     ~1      == 0b1111111111111110
4076   // i16 rol(~1, 14) == 0b1011111111111111
4077   //
4078   // Some additional tips to help conceptualize this transform:
4079   // - Try to see the operation as placing a single zero in a value of all ones.
4080   // - There exists no value for x which would allow the result to contain zero.
4081   // - Values of x larger than the bitwidth are undefined and do not require a
4082   //   consistent result.
4083   // - Pushing the zero left requires shifting one bits in from the right.
4084   // A rotate left of ~1 is a nice way of achieving the desired result.
4085   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4086       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4087     SDLoc DL(N);
4088     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4089                        N0.getOperand(1));
4090   }
4091
4092   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4093   if (N0.getOpcode() == N1.getOpcode()) {
4094     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4095     if (Tmp.getNode()) return Tmp;
4096   }
4097
4098   // Simplify the expression using non-local knowledge.
4099   if (!VT.isVector() &&
4100       SimplifyDemandedBits(SDValue(N, 0)))
4101     return SDValue(N, 0);
4102
4103   return SDValue();
4104 }
4105
4106 /// Handle transforms common to the three shifts, when the shift amount is a
4107 /// constant.
4108 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4109   SDNode *LHS = N->getOperand(0).getNode();
4110   if (!LHS->hasOneUse()) return SDValue();
4111
4112   // We want to pull some binops through shifts, so that we have (and (shift))
4113   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4114   // thing happens with address calculations, so it's important to canonicalize
4115   // it.
4116   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4117
4118   switch (LHS->getOpcode()) {
4119   default: return SDValue();
4120   case ISD::OR:
4121   case ISD::XOR:
4122     HighBitSet = false; // We can only transform sra if the high bit is clear.
4123     break;
4124   case ISD::AND:
4125     HighBitSet = true;  // We can only transform sra if the high bit is set.
4126     break;
4127   case ISD::ADD:
4128     if (N->getOpcode() != ISD::SHL)
4129       return SDValue(); // only shl(add) not sr[al](add).
4130     HighBitSet = false; // We can only transform sra if the high bit is clear.
4131     break;
4132   }
4133
4134   // We require the RHS of the binop to be a constant and not opaque as well.
4135   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4136   if (!BinOpCst) return SDValue();
4137
4138   // FIXME: disable this unless the input to the binop is a shift by a constant.
4139   // If it is not a shift, it pessimizes some common cases like:
4140   //
4141   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4142   //    int bar(int *X, int i) { return X[i & 255]; }
4143   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4144   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4145        BinOpLHSVal->getOpcode() != ISD::SRA &&
4146        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4147       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4148     return SDValue();
4149
4150   EVT VT = N->getValueType(0);
4151
4152   // If this is a signed shift right, and the high bit is modified by the
4153   // logical operation, do not perform the transformation. The highBitSet
4154   // boolean indicates the value of the high bit of the constant which would
4155   // cause it to be modified for this operation.
4156   if (N->getOpcode() == ISD::SRA) {
4157     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4158     if (BinOpRHSSignSet != HighBitSet)
4159       return SDValue();
4160   }
4161
4162   if (!TLI.isDesirableToCommuteWithShift(LHS))
4163     return SDValue();
4164
4165   // Fold the constants, shifting the binop RHS by the shift amount.
4166   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4167                                N->getValueType(0),
4168                                LHS->getOperand(1), N->getOperand(1));
4169   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4170
4171   // Create the new shift.
4172   SDValue NewShift = DAG.getNode(N->getOpcode(),
4173                                  SDLoc(LHS->getOperand(0)),
4174                                  VT, LHS->getOperand(0), N->getOperand(1));
4175
4176   // Create the new binop.
4177   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4178 }
4179
4180 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4181   assert(N->getOpcode() == ISD::TRUNCATE);
4182   assert(N->getOperand(0).getOpcode() == ISD::AND);
4183
4184   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4185   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4186     SDValue N01 = N->getOperand(0).getOperand(1);
4187
4188     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4189       if (!N01C->isOpaque()) {
4190         EVT TruncVT = N->getValueType(0);
4191         SDValue N00 = N->getOperand(0).getOperand(0);
4192         APInt TruncC = N01C->getAPIntValue();
4193         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4194         SDLoc DL(N);
4195
4196         return DAG.getNode(ISD::AND, DL, TruncVT,
4197                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4198                            DAG.getConstant(TruncC, DL, TruncVT));
4199       }
4200     }
4201   }
4202
4203   return SDValue();
4204 }
4205
4206 SDValue DAGCombiner::visitRotate(SDNode *N) {
4207   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4208   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4209       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4210     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4211     if (NewOp1.getNode())
4212       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4213                          N->getOperand(0), NewOp1);
4214   }
4215   return SDValue();
4216 }
4217
4218 SDValue DAGCombiner::visitSHL(SDNode *N) {
4219   SDValue N0 = N->getOperand(0);
4220   SDValue N1 = N->getOperand(1);
4221   EVT VT = N0.getValueType();
4222   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4223
4224   // fold vector ops
4225   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4226   if (VT.isVector()) {
4227     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4228       return FoldedVOp;
4229
4230     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4231     // If setcc produces all-one true value then:
4232     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4233     if (N1CV && N1CV->isConstant()) {
4234       if (N0.getOpcode() == ISD::AND) {
4235         SDValue N00 = N0->getOperand(0);
4236         SDValue N01 = N0->getOperand(1);
4237         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4238
4239         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4240             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4241                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4242           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4243                                                      N01CV, N1CV))
4244             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4245         }
4246       } else {
4247         N1C = isConstOrConstSplat(N1);
4248       }
4249     }
4250   }
4251
4252   // fold (shl c1, c2) -> c1<<c2
4253   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4254   if (N0C && N1C && !N1C->isOpaque())
4255     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4256   // fold (shl 0, x) -> 0
4257   if (isNullConstant(N0))
4258     return N0;
4259   // fold (shl x, c >= size(x)) -> undef
4260   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4261     return DAG.getUNDEF(VT);
4262   // fold (shl x, 0) -> x
4263   if (N1C && N1C->isNullValue())
4264     return N0;
4265   // fold (shl undef, x) -> 0
4266   if (N0.getOpcode() == ISD::UNDEF)
4267     return DAG.getConstant(0, SDLoc(N), VT);
4268   // if (shl x, c) is known to be zero, return 0
4269   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4270                             APInt::getAllOnesValue(OpSizeInBits)))
4271     return DAG.getConstant(0, SDLoc(N), VT);
4272   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4273   if (N1.getOpcode() == ISD::TRUNCATE &&
4274       N1.getOperand(0).getOpcode() == ISD::AND) {
4275     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4276     if (NewOp1.getNode())
4277       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4278   }
4279
4280   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4281     return SDValue(N, 0);
4282
4283   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4284   if (N1C && N0.getOpcode() == ISD::SHL) {
4285     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4286       uint64_t c1 = N0C1->getZExtValue();
4287       uint64_t c2 = N1C->getZExtValue();
4288       SDLoc DL(N);
4289       if (c1 + c2 >= OpSizeInBits)
4290         return DAG.getConstant(0, DL, VT);
4291       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4292                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4293     }
4294   }
4295
4296   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4297   // For this to be valid, the second form must not preserve any of the bits
4298   // that are shifted out by the inner shift in the first form.  This means
4299   // the outer shift size must be >= the number of bits added by the ext.
4300   // As a corollary, we don't care what kind of ext it is.
4301   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4302               N0.getOpcode() == ISD::ANY_EXTEND ||
4303               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4304       N0.getOperand(0).getOpcode() == ISD::SHL) {
4305     SDValue N0Op0 = N0.getOperand(0);
4306     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4307       uint64_t c1 = N0Op0C1->getZExtValue();
4308       uint64_t c2 = N1C->getZExtValue();
4309       EVT InnerShiftVT = N0Op0.getValueType();
4310       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4311       if (c2 >= OpSizeInBits - InnerShiftSize) {
4312         SDLoc DL(N0);
4313         if (c1 + c2 >= OpSizeInBits)
4314           return DAG.getConstant(0, DL, VT);
4315         return DAG.getNode(ISD::SHL, DL, VT,
4316                            DAG.getNode(N0.getOpcode(), DL, VT,
4317                                        N0Op0->getOperand(0)),
4318                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4319       }
4320     }
4321   }
4322
4323   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4324   // Only fold this if the inner zext has no other uses to avoid increasing
4325   // the total number of instructions.
4326   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4327       N0.getOperand(0).getOpcode() == ISD::SRL) {
4328     SDValue N0Op0 = N0.getOperand(0);
4329     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4330       uint64_t c1 = N0Op0C1->getZExtValue();
4331       if (c1 < VT.getScalarSizeInBits()) {
4332         uint64_t c2 = N1C->getZExtValue();
4333         if (c1 == c2) {
4334           SDValue NewOp0 = N0.getOperand(0);
4335           EVT CountVT = NewOp0.getOperand(1).getValueType();
4336           SDLoc DL(N);
4337           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4338                                        NewOp0,
4339                                        DAG.getConstant(c2, DL, CountVT));
4340           AddToWorklist(NewSHL.getNode());
4341           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4342         }
4343       }
4344     }
4345   }
4346
4347   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4348   //                               (and (srl x, (sub c1, c2), MASK)
4349   // Only fold this if the inner shift has no other uses -- if it does, folding
4350   // this will increase the total number of instructions.
4351   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4352     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4353       uint64_t c1 = N0C1->getZExtValue();
4354       if (c1 < OpSizeInBits) {
4355         uint64_t c2 = N1C->getZExtValue();
4356         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4357         SDValue Shift;
4358         if (c2 > c1) {
4359           Mask = Mask.shl(c2 - c1);
4360           SDLoc DL(N);
4361           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4362                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4363         } else {
4364           Mask = Mask.lshr(c1 - c2);
4365           SDLoc DL(N);
4366           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4367                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4368         }
4369         SDLoc DL(N0);
4370         return DAG.getNode(ISD::AND, DL, VT, Shift,
4371                            DAG.getConstant(Mask, DL, VT));
4372       }
4373     }
4374   }
4375   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4376   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4377     unsigned BitSize = VT.getScalarSizeInBits();
4378     SDLoc DL(N);
4379     SDValue HiBitsMask =
4380       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4381                                             BitSize - N1C->getZExtValue()),
4382                       DL, VT);
4383     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4384                        HiBitsMask);
4385   }
4386
4387   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4388   // Variant of version done on multiply, except mul by a power of 2 is turned
4389   // into a shift.
4390   APInt Val;
4391   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4392       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4393        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4394     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4395     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4396     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4397   }
4398
4399   if (N1C && !N1C->isOpaque()) {
4400     SDValue NewSHL = visitShiftByConstant(N, N1C);
4401     if (NewSHL.getNode())
4402       return NewSHL;
4403   }
4404
4405   return SDValue();
4406 }
4407
4408 SDValue DAGCombiner::visitSRA(SDNode *N) {
4409   SDValue N0 = N->getOperand(0);
4410   SDValue N1 = N->getOperand(1);
4411   EVT VT = N0.getValueType();
4412   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4413
4414   // fold vector ops
4415   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4416   if (VT.isVector()) {
4417     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4418       return FoldedVOp;
4419
4420     N1C = isConstOrConstSplat(N1);
4421   }
4422
4423   // fold (sra c1, c2) -> (sra c1, c2)
4424   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4425   if (N0C && N1C && !N1C->isOpaque())
4426     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4427   // fold (sra 0, x) -> 0
4428   if (isNullConstant(N0))
4429     return N0;
4430   // fold (sra -1, x) -> -1
4431   if (isAllOnesConstant(N0))
4432     return N0;
4433   // fold (sra x, (setge c, size(x))) -> undef
4434   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4435     return DAG.getUNDEF(VT);
4436   // fold (sra x, 0) -> x
4437   if (N1C && N1C->isNullValue())
4438     return N0;
4439   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4440   // sext_inreg.
4441   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4442     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4443     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4444     if (VT.isVector())
4445       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4446                                ExtVT, VT.getVectorNumElements());
4447     if ((!LegalOperations ||
4448          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4449       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4450                          N0.getOperand(0), DAG.getValueType(ExtVT));
4451   }
4452
4453   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4454   if (N1C && N0.getOpcode() == ISD::SRA) {
4455     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4456       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4457       if (Sum >= OpSizeInBits)
4458         Sum = OpSizeInBits - 1;
4459       SDLoc DL(N);
4460       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4461                          DAG.getConstant(Sum, DL, N1.getValueType()));
4462     }
4463   }
4464
4465   // fold (sra (shl X, m), (sub result_size, n))
4466   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4467   // result_size - n != m.
4468   // If truncate is free for the target sext(shl) is likely to result in better
4469   // code.
4470   if (N0.getOpcode() == ISD::SHL && N1C) {
4471     // Get the two constanst of the shifts, CN0 = m, CN = n.
4472     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4473     if (N01C) {
4474       LLVMContext &Ctx = *DAG.getContext();
4475       // Determine what the truncate's result bitsize and type would be.
4476       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4477
4478       if (VT.isVector())
4479         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4480
4481       // Determine the residual right-shift amount.
4482       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4483
4484       // If the shift is not a no-op (in which case this should be just a sign
4485       // extend already), the truncated to type is legal, sign_extend is legal
4486       // on that type, and the truncate to that type is both legal and free,
4487       // perform the transform.
4488       if ((ShiftAmt > 0) &&
4489           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4490           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4491           TLI.isTruncateFree(VT, TruncVT)) {
4492
4493         SDLoc DL(N);
4494         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4495             getShiftAmountTy(N0.getOperand(0).getValueType()));
4496         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4497                                     N0.getOperand(0), Amt);
4498         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4499                                     Shift);
4500         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4501                            N->getValueType(0), Trunc);
4502       }
4503     }
4504   }
4505
4506   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4507   if (N1.getOpcode() == ISD::TRUNCATE &&
4508       N1.getOperand(0).getOpcode() == ISD::AND) {
4509     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4510     if (NewOp1.getNode())
4511       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4512   }
4513
4514   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4515   //      if c1 is equal to the number of bits the trunc removes
4516   if (N0.getOpcode() == ISD::TRUNCATE &&
4517       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4518        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4519       N0.getOperand(0).hasOneUse() &&
4520       N0.getOperand(0).getOperand(1).hasOneUse() &&
4521       N1C) {
4522     SDValue N0Op0 = N0.getOperand(0);
4523     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4524       unsigned LargeShiftVal = LargeShift->getZExtValue();
4525       EVT LargeVT = N0Op0.getValueType();
4526
4527       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4528         SDLoc DL(N);
4529         SDValue Amt =
4530           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4531                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4532         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4533                                   N0Op0.getOperand(0), Amt);
4534         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4535       }
4536     }
4537   }
4538
4539   // Simplify, based on bits shifted out of the LHS.
4540   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4541     return SDValue(N, 0);
4542
4543
4544   // If the sign bit is known to be zero, switch this to a SRL.
4545   if (DAG.SignBitIsZero(N0))
4546     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4547
4548   if (N1C && !N1C->isOpaque()) {
4549     SDValue NewSRA = visitShiftByConstant(N, N1C);
4550     if (NewSRA.getNode())
4551       return NewSRA;
4552   }
4553
4554   return SDValue();
4555 }
4556
4557 SDValue DAGCombiner::visitSRL(SDNode *N) {
4558   SDValue N0 = N->getOperand(0);
4559   SDValue N1 = N->getOperand(1);
4560   EVT VT = N0.getValueType();
4561   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4562
4563   // fold vector ops
4564   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4565   if (VT.isVector()) {
4566     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4567       return FoldedVOp;
4568
4569     N1C = isConstOrConstSplat(N1);
4570   }
4571
4572   // fold (srl c1, c2) -> c1 >>u c2
4573   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4574   if (N0C && N1C && !N1C->isOpaque())
4575     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4576   // fold (srl 0, x) -> 0
4577   if (isNullConstant(N0))
4578     return N0;
4579   // fold (srl x, c >= size(x)) -> undef
4580   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4581     return DAG.getUNDEF(VT);
4582   // fold (srl x, 0) -> x
4583   if (N1C && N1C->isNullValue())
4584     return N0;
4585   // if (srl x, c) is known to be zero, return 0
4586   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4587                                    APInt::getAllOnesValue(OpSizeInBits)))
4588     return DAG.getConstant(0, SDLoc(N), VT);
4589
4590   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4591   if (N1C && N0.getOpcode() == ISD::SRL) {
4592     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4593       uint64_t c1 = N01C->getZExtValue();
4594       uint64_t c2 = N1C->getZExtValue();
4595       SDLoc DL(N);
4596       if (c1 + c2 >= OpSizeInBits)
4597         return DAG.getConstant(0, DL, VT);
4598       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4599                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4600     }
4601   }
4602
4603   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4604   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4605       N0.getOperand(0).getOpcode() == ISD::SRL &&
4606       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4607     uint64_t c1 =
4608       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4609     uint64_t c2 = N1C->getZExtValue();
4610     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4611     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4612     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4613     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4614     if (c1 + OpSizeInBits == InnerShiftSize) {
4615       SDLoc DL(N0);
4616       if (c1 + c2 >= InnerShiftSize)
4617         return DAG.getConstant(0, DL, VT);
4618       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4619                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4620                                      N0.getOperand(0)->getOperand(0),
4621                                      DAG.getConstant(c1 + c2, DL,
4622                                                      ShiftCountVT)));
4623     }
4624   }
4625
4626   // fold (srl (shl x, c), c) -> (and x, cst2)
4627   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4628     unsigned BitSize = N0.getScalarValueSizeInBits();
4629     if (BitSize <= 64) {
4630       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4631       SDLoc DL(N);
4632       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4633                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4634     }
4635   }
4636
4637   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4638   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4639     // Shifting in all undef bits?
4640     EVT SmallVT = N0.getOperand(0).getValueType();
4641     unsigned BitSize = SmallVT.getScalarSizeInBits();
4642     if (N1C->getZExtValue() >= BitSize)
4643       return DAG.getUNDEF(VT);
4644
4645     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4646       uint64_t ShiftAmt = N1C->getZExtValue();
4647       SDLoc DL0(N0);
4648       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4649                                        N0.getOperand(0),
4650                           DAG.getConstant(ShiftAmt, DL0,
4651                                           getShiftAmountTy(SmallVT)));
4652       AddToWorklist(SmallShift.getNode());
4653       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4654       SDLoc DL(N);
4655       return DAG.getNode(ISD::AND, DL, VT,
4656                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4657                          DAG.getConstant(Mask, DL, VT));
4658     }
4659   }
4660
4661   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4662   // bit, which is unmodified by sra.
4663   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4664     if (N0.getOpcode() == ISD::SRA)
4665       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4666   }
4667
4668   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4669   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4670       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4671     APInt KnownZero, KnownOne;
4672     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4673
4674     // If any of the input bits are KnownOne, then the input couldn't be all
4675     // zeros, thus the result of the srl will always be zero.
4676     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4677
4678     // If all of the bits input the to ctlz node are known to be zero, then
4679     // the result of the ctlz is "32" and the result of the shift is one.
4680     APInt UnknownBits = ~KnownZero;
4681     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4682
4683     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4684     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4685       // Okay, we know that only that the single bit specified by UnknownBits
4686       // could be set on input to the CTLZ node. If this bit is set, the SRL
4687       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4688       // to an SRL/XOR pair, which is likely to simplify more.
4689       unsigned ShAmt = UnknownBits.countTrailingZeros();
4690       SDValue Op = N0.getOperand(0);
4691
4692       if (ShAmt) {
4693         SDLoc DL(N0);
4694         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4695                   DAG.getConstant(ShAmt, DL,
4696                                   getShiftAmountTy(Op.getValueType())));
4697         AddToWorklist(Op.getNode());
4698       }
4699
4700       SDLoc DL(N);
4701       return DAG.getNode(ISD::XOR, DL, VT,
4702                          Op, DAG.getConstant(1, DL, VT));
4703     }
4704   }
4705
4706   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4707   if (N1.getOpcode() == ISD::TRUNCATE &&
4708       N1.getOperand(0).getOpcode() == ISD::AND) {
4709     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4710     if (NewOp1.getNode())
4711       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4712   }
4713
4714   // fold operands of srl based on knowledge that the low bits are not
4715   // demanded.
4716   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4717     return SDValue(N, 0);
4718
4719   if (N1C && !N1C->isOpaque()) {
4720     SDValue NewSRL = visitShiftByConstant(N, N1C);
4721     if (NewSRL.getNode())
4722       return NewSRL;
4723   }
4724
4725   // Attempt to convert a srl of a load into a narrower zero-extending load.
4726   SDValue NarrowLoad = ReduceLoadWidth(N);
4727   if (NarrowLoad.getNode())
4728     return NarrowLoad;
4729
4730   // Here is a common situation. We want to optimize:
4731   //
4732   //   %a = ...
4733   //   %b = and i32 %a, 2
4734   //   %c = srl i32 %b, 1
4735   //   brcond i32 %c ...
4736   //
4737   // into
4738   //
4739   //   %a = ...
4740   //   %b = and %a, 2
4741   //   %c = setcc eq %b, 0
4742   //   brcond %c ...
4743   //
4744   // However when after the source operand of SRL is optimized into AND, the SRL
4745   // itself may not be optimized further. Look for it and add the BRCOND into
4746   // the worklist.
4747   if (N->hasOneUse()) {
4748     SDNode *Use = *N->use_begin();
4749     if (Use->getOpcode() == ISD::BRCOND)
4750       AddToWorklist(Use);
4751     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4752       // Also look pass the truncate.
4753       Use = *Use->use_begin();
4754       if (Use->getOpcode() == ISD::BRCOND)
4755         AddToWorklist(Use);
4756     }
4757   }
4758
4759   return SDValue();
4760 }
4761
4762 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4763   SDValue N0 = N->getOperand(0);
4764   EVT VT = N->getValueType(0);
4765
4766   // fold (ctlz c1) -> c2
4767   if (isa<ConstantSDNode>(N0))
4768     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4769   return SDValue();
4770 }
4771
4772 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4773   SDValue N0 = N->getOperand(0);
4774   EVT VT = N->getValueType(0);
4775
4776   // fold (ctlz_zero_undef c1) -> c2
4777   if (isa<ConstantSDNode>(N0))
4778     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4779   return SDValue();
4780 }
4781
4782 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4783   SDValue N0 = N->getOperand(0);
4784   EVT VT = N->getValueType(0);
4785
4786   // fold (cttz c1) -> c2
4787   if (isa<ConstantSDNode>(N0))
4788     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4789   return SDValue();
4790 }
4791
4792 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4793   SDValue N0 = N->getOperand(0);
4794   EVT VT = N->getValueType(0);
4795
4796   // fold (cttz_zero_undef c1) -> c2
4797   if (isa<ConstantSDNode>(N0))
4798     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4799   return SDValue();
4800 }
4801
4802 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4803   SDValue N0 = N->getOperand(0);
4804   EVT VT = N->getValueType(0);
4805
4806   // fold (ctpop c1) -> c2
4807   if (isa<ConstantSDNode>(N0))
4808     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4809   return SDValue();
4810 }
4811
4812
4813 /// \brief Generate Min/Max node
4814 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4815                                    SDValue True, SDValue False,
4816                                    ISD::CondCode CC, const TargetLowering &TLI,
4817                                    SelectionDAG &DAG) {
4818   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4819     return SDValue();
4820
4821   switch (CC) {
4822   case ISD::SETOLT:
4823   case ISD::SETOLE:
4824   case ISD::SETLT:
4825   case ISD::SETLE:
4826   case ISD::SETULT:
4827   case ISD::SETULE: {
4828     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4829     if (TLI.isOperationLegal(Opcode, VT))
4830       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4831     return SDValue();
4832   }
4833   case ISD::SETOGT:
4834   case ISD::SETOGE:
4835   case ISD::SETGT:
4836   case ISD::SETGE:
4837   case ISD::SETUGT:
4838   case ISD::SETUGE: {
4839     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4840     if (TLI.isOperationLegal(Opcode, VT))
4841       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4842     return SDValue();
4843   }
4844   default:
4845     return SDValue();
4846   }
4847 }
4848
4849 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4850   SDValue N0 = N->getOperand(0);
4851   SDValue N1 = N->getOperand(1);
4852   SDValue N2 = N->getOperand(2);
4853   EVT VT = N->getValueType(0);
4854   EVT VT0 = N0.getValueType();
4855
4856   // fold (select C, X, X) -> X
4857   if (N1 == N2)
4858     return N1;
4859   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4860     // fold (select true, X, Y) -> X
4861     // fold (select false, X, Y) -> Y
4862     return !N0C->isNullValue() ? N1 : N2;
4863   }
4864   // fold (select C, 1, X) -> (or C, X)
4865   if (VT == MVT::i1 && isOneConstant(N1))
4866     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4867   // fold (select C, 0, 1) -> (xor C, 1)
4868   // We can't do this reliably if integer based booleans have different contents
4869   // to floating point based booleans. This is because we can't tell whether we
4870   // have an integer-based boolean or a floating-point-based boolean unless we
4871   // can find the SETCC that produced it and inspect its operands. This is
4872   // fairly easy if C is the SETCC node, but it can potentially be
4873   // undiscoverable (or not reasonably discoverable). For example, it could be
4874   // in another basic block or it could require searching a complicated
4875   // expression.
4876   if (VT.isInteger() &&
4877       (VT0 == MVT::i1 || (VT0.isInteger() &&
4878                           TLI.getBooleanContents(false, false) ==
4879                               TLI.getBooleanContents(false, true) &&
4880                           TLI.getBooleanContents(false, false) ==
4881                               TargetLowering::ZeroOrOneBooleanContent)) &&
4882       isNullConstant(N1) && isOneConstant(N2)) {
4883     SDValue XORNode;
4884     if (VT == VT0) {
4885       SDLoc DL(N);
4886       return DAG.getNode(ISD::XOR, DL, VT0,
4887                          N0, DAG.getConstant(1, DL, VT0));
4888     }
4889     SDLoc DL0(N0);
4890     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4891                           N0, DAG.getConstant(1, DL0, VT0));
4892     AddToWorklist(XORNode.getNode());
4893     if (VT.bitsGT(VT0))
4894       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4895     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4896   }
4897   // fold (select C, 0, X) -> (and (not C), X)
4898   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4899     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4900     AddToWorklist(NOTNode.getNode());
4901     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4902   }
4903   // fold (select C, X, 1) -> (or (not C), X)
4904   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4905     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4906     AddToWorklist(NOTNode.getNode());
4907     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4908   }
4909   // fold (select C, X, 0) -> (and C, X)
4910   if (VT == MVT::i1 && isNullConstant(N2))
4911     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4912   // fold (select X, X, Y) -> (or X, Y)
4913   // fold (select X, 1, Y) -> (or X, Y)
4914   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4915     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4916   // fold (select X, Y, X) -> (and X, Y)
4917   // fold (select X, Y, 0) -> (and X, Y)
4918   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4919     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4920
4921   // If we can fold this based on the true/false value, do so.
4922   if (SimplifySelectOps(N, N1, N2))
4923     return SDValue(N, 0);  // Don't revisit N.
4924
4925   // fold selects based on a setcc into other things, such as min/max/abs
4926   if (N0.getOpcode() == ISD::SETCC) {
4927     // select x, y (fcmp lt x, y) -> fminnum x, y
4928     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4929     //
4930     // This is OK if we don't care about what happens if either operand is a
4931     // NaN.
4932     //
4933
4934     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4935     // no signed zeros as well as no nans.
4936     const TargetOptions &Options = DAG.getTarget().Options;
4937     if (Options.UnsafeFPMath &&
4938         VT.isFloatingPoint() && N0.hasOneUse() &&
4939         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4940       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4941
4942       SDValue FMinMax =
4943           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4944                               N1, N2, CC, TLI, DAG);
4945       if (FMinMax)
4946         return FMinMax;
4947     }
4948
4949     if ((!LegalOperations &&
4950          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4951         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4952       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4953                          N0.getOperand(0), N0.getOperand(1),
4954                          N1, N2, N0.getOperand(2));
4955     return SimplifySelect(SDLoc(N), N0, N1, N2);
4956   }
4957
4958   if (VT0 == MVT::i1) {
4959     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4960       // select (and Cond0, Cond1), X, Y
4961       //   -> select Cond0, (select Cond1, X, Y), Y
4962       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4963         SDValue Cond0 = N0->getOperand(0);
4964         SDValue Cond1 = N0->getOperand(1);
4965         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4966                                           N1.getValueType(), Cond1, N1, N2);
4967         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4968                            InnerSelect, N2);
4969       }
4970       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4971       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4972         SDValue Cond0 = N0->getOperand(0);
4973         SDValue Cond1 = N0->getOperand(1);
4974         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4975                                           N1.getValueType(), Cond1, N1, N2);
4976         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4977                            InnerSelect);
4978       }
4979     }
4980
4981     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4982     if (N1->getOpcode() == ISD::SELECT) {
4983       SDValue N1_0 = N1->getOperand(0);
4984       SDValue N1_1 = N1->getOperand(1);
4985       SDValue N1_2 = N1->getOperand(2);
4986       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4987         // Create the actual and node if we can generate good code for it.
4988         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4989           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4990                                     N0, N1_0);
4991           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4992                              N1_1, N2);
4993         }
4994         // Otherwise see if we can optimize the "and" to a better pattern.
4995         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4996           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4997                              N1_1, N2);
4998       }
4999     }
5000     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5001     if (N2->getOpcode() == ISD::SELECT) {
5002       SDValue N2_0 = N2->getOperand(0);
5003       SDValue N2_1 = N2->getOperand(1);
5004       SDValue N2_2 = N2->getOperand(2);
5005       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5006         // Create the actual or node if we can generate good code for it.
5007         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5008           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5009                                    N0, N2_0);
5010           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5011                              N1, N2_2);
5012         }
5013         // Otherwise see if we can optimize to a better pattern.
5014         if (SDValue Combined = visitORLike(N0, N2_0, N))
5015           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5016                              N1, N2_2);
5017       }
5018     }
5019   }
5020
5021   return SDValue();
5022 }
5023
5024 static
5025 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5026   SDLoc DL(N);
5027   EVT LoVT, HiVT;
5028   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5029
5030   // Split the inputs.
5031   SDValue Lo, Hi, LL, LH, RL, RH;
5032   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5033   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5034
5035   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5036   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5037
5038   return std::make_pair(Lo, Hi);
5039 }
5040
5041 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5042 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5043 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5044   SDLoc dl(N);
5045   SDValue Cond = N->getOperand(0);
5046   SDValue LHS = N->getOperand(1);
5047   SDValue RHS = N->getOperand(2);
5048   EVT VT = N->getValueType(0);
5049   int NumElems = VT.getVectorNumElements();
5050   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5051          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5052          Cond.getOpcode() == ISD::BUILD_VECTOR);
5053
5054   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5055   // binary ones here.
5056   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5057     return SDValue();
5058
5059   // We're sure we have an even number of elements due to the
5060   // concat_vectors we have as arguments to vselect.
5061   // Skip BV elements until we find one that's not an UNDEF
5062   // After we find an UNDEF element, keep looping until we get to half the
5063   // length of the BV and see if all the non-undef nodes are the same.
5064   ConstantSDNode *BottomHalf = nullptr;
5065   for (int i = 0; i < NumElems / 2; ++i) {
5066     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5067       continue;
5068
5069     if (BottomHalf == nullptr)
5070       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5071     else if (Cond->getOperand(i).getNode() != BottomHalf)
5072       return SDValue();
5073   }
5074
5075   // Do the same for the second half of the BuildVector
5076   ConstantSDNode *TopHalf = nullptr;
5077   for (int i = NumElems / 2; i < NumElems; ++i) {
5078     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5079       continue;
5080
5081     if (TopHalf == nullptr)
5082       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5083     else if (Cond->getOperand(i).getNode() != TopHalf)
5084       return SDValue();
5085   }
5086
5087   assert(TopHalf && BottomHalf &&
5088          "One half of the selector was all UNDEFs and the other was all the "
5089          "same value. This should have been addressed before this function.");
5090   return DAG.getNode(
5091       ISD::CONCAT_VECTORS, dl, VT,
5092       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5093       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5094 }
5095
5096 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5097
5098   if (Level >= AfterLegalizeTypes)
5099     return SDValue();
5100
5101   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5102   SDValue Mask = MSC->getMask();
5103   SDValue Data  = MSC->getValue();
5104   SDLoc DL(N);
5105
5106   // If the MSCATTER data type requires splitting and the mask is provided by a
5107   // SETCC, then split both nodes and its operands before legalization. This
5108   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5109   // and enables future optimizations (e.g. min/max pattern matching on X86).
5110   if (Mask.getOpcode() != ISD::SETCC)
5111     return SDValue();
5112
5113   // Check if any splitting is required.
5114   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5115       TargetLowering::TypeSplitVector)
5116     return SDValue();
5117   SDValue MaskLo, MaskHi, Lo, Hi;
5118   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5119
5120   EVT LoVT, HiVT;
5121   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5122
5123   SDValue Chain = MSC->getChain();
5124
5125   EVT MemoryVT = MSC->getMemoryVT();
5126   unsigned Alignment = MSC->getOriginalAlignment();
5127
5128   EVT LoMemVT, HiMemVT;
5129   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5130
5131   SDValue DataLo, DataHi;
5132   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5133
5134   SDValue BasePtr = MSC->getBasePtr();
5135   SDValue IndexLo, IndexHi;
5136   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5137
5138   MachineMemOperand *MMO = DAG.getMachineFunction().
5139     getMachineMemOperand(MSC->getPointerInfo(), 
5140                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5141                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5142
5143   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5144   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5145                             DL, OpsLo, MMO);
5146
5147   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5148   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5149                             DL, OpsHi, MMO);
5150
5151   AddToWorklist(Lo.getNode());
5152   AddToWorklist(Hi.getNode());
5153
5154   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5155 }
5156
5157 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5158
5159   if (Level >= AfterLegalizeTypes)
5160     return SDValue();
5161
5162   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5163   SDValue Mask = MST->getMask();
5164   SDValue Data  = MST->getValue();
5165   SDLoc DL(N);
5166
5167   // If the MSTORE data type requires splitting and the mask is provided by a
5168   // SETCC, then split both nodes and its operands before legalization. This
5169   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5170   // and enables future optimizations (e.g. min/max pattern matching on X86).
5171   if (Mask.getOpcode() == ISD::SETCC) {
5172
5173     // Check if any splitting is required.
5174     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5175         TargetLowering::TypeSplitVector)
5176       return SDValue();
5177
5178     SDValue MaskLo, MaskHi, Lo, Hi;
5179     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5180
5181     EVT LoVT, HiVT;
5182     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5183
5184     SDValue Chain = MST->getChain();
5185     SDValue Ptr   = MST->getBasePtr();
5186
5187     EVT MemoryVT = MST->getMemoryVT();
5188     unsigned Alignment = MST->getOriginalAlignment();
5189
5190     // if Alignment is equal to the vector size,
5191     // take the half of it for the second part
5192     unsigned SecondHalfAlignment =
5193       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5194          Alignment/2 : Alignment;
5195
5196     EVT LoMemVT, HiMemVT;
5197     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5198
5199     SDValue DataLo, DataHi;
5200     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5201
5202     MachineMemOperand *MMO = DAG.getMachineFunction().
5203       getMachineMemOperand(MST->getPointerInfo(),
5204                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5205                            Alignment, MST->getAAInfo(), MST->getRanges());
5206
5207     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5208                             MST->isTruncatingStore());
5209
5210     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5211     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5212                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5213
5214     MMO = DAG.getMachineFunction().
5215       getMachineMemOperand(MST->getPointerInfo(),
5216                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5217                            SecondHalfAlignment, MST->getAAInfo(),
5218                            MST->getRanges());
5219
5220     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5221                             MST->isTruncatingStore());
5222
5223     AddToWorklist(Lo.getNode());
5224     AddToWorklist(Hi.getNode());
5225
5226     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5227   }
5228   return SDValue();
5229 }
5230
5231 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5232
5233   if (Level >= AfterLegalizeTypes)
5234     return SDValue();
5235
5236   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5237   SDValue Mask = MGT->getMask();
5238   SDLoc DL(N);
5239
5240   // If the MGATHER result requires splitting and the mask is provided by a
5241   // SETCC, then split both nodes and its operands before legalization. This
5242   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5243   // and enables future optimizations (e.g. min/max pattern matching on X86).
5244
5245   if (Mask.getOpcode() != ISD::SETCC)
5246     return SDValue();
5247
5248   EVT VT = N->getValueType(0);
5249
5250   // Check if any splitting is required.
5251   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5252       TargetLowering::TypeSplitVector)
5253     return SDValue();
5254
5255   SDValue MaskLo, MaskHi, Lo, Hi;
5256   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5257
5258   SDValue Src0 = MGT->getValue();
5259   SDValue Src0Lo, Src0Hi;
5260   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5261
5262   EVT LoVT, HiVT;
5263   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5264
5265   SDValue Chain = MGT->getChain();
5266   EVT MemoryVT = MGT->getMemoryVT();
5267   unsigned Alignment = MGT->getOriginalAlignment();
5268
5269   EVT LoMemVT, HiMemVT;
5270   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5271
5272   SDValue BasePtr = MGT->getBasePtr();
5273   SDValue Index = MGT->getIndex();
5274   SDValue IndexLo, IndexHi;
5275   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5276
5277   MachineMemOperand *MMO = DAG.getMachineFunction().
5278     getMachineMemOperand(MGT->getPointerInfo(), 
5279                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5280                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5281
5282   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5283   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5284                             MMO);
5285
5286   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5287   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5288                             MMO);
5289
5290   AddToWorklist(Lo.getNode());
5291   AddToWorklist(Hi.getNode());
5292
5293   // Build a factor node to remember that this load is independent of the
5294   // other one.
5295   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5296                       Hi.getValue(1));
5297
5298   // Legalized the chain result - switch anything that used the old chain to
5299   // use the new one.
5300   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5301
5302   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5303
5304   SDValue RetOps[] = { GatherRes, Chain };
5305   return DAG.getMergeValues(RetOps, DL);
5306 }
5307
5308 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5309
5310   if (Level >= AfterLegalizeTypes)
5311     return SDValue();
5312
5313   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5314   SDValue Mask = MLD->getMask();
5315   SDLoc DL(N);
5316
5317   // If the MLOAD result requires splitting and the mask is provided by a
5318   // SETCC, then split both nodes and its operands before legalization. This
5319   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5320   // and enables future optimizations (e.g. min/max pattern matching on X86).
5321
5322   if (Mask.getOpcode() == ISD::SETCC) {
5323     EVT VT = N->getValueType(0);
5324
5325     // Check if any splitting is required.
5326     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5327         TargetLowering::TypeSplitVector)
5328       return SDValue();
5329
5330     SDValue MaskLo, MaskHi, Lo, Hi;
5331     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5332
5333     SDValue Src0 = MLD->getSrc0();
5334     SDValue Src0Lo, Src0Hi;
5335     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5336
5337     EVT LoVT, HiVT;
5338     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5339
5340     SDValue Chain = MLD->getChain();
5341     SDValue Ptr   = MLD->getBasePtr();
5342     EVT MemoryVT = MLD->getMemoryVT();
5343     unsigned Alignment = MLD->getOriginalAlignment();
5344
5345     // if Alignment is equal to the vector size,
5346     // take the half of it for the second part
5347     unsigned SecondHalfAlignment =
5348       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5349          Alignment/2 : Alignment;
5350
5351     EVT LoMemVT, HiMemVT;
5352     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5353
5354     MachineMemOperand *MMO = DAG.getMachineFunction().
5355     getMachineMemOperand(MLD->getPointerInfo(),
5356                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5357                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5358
5359     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5360                            ISD::NON_EXTLOAD);
5361
5362     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5363     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5364                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5365
5366     MMO = DAG.getMachineFunction().
5367     getMachineMemOperand(MLD->getPointerInfo(),
5368                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5369                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5370
5371     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5372                            ISD::NON_EXTLOAD);
5373
5374     AddToWorklist(Lo.getNode());
5375     AddToWorklist(Hi.getNode());
5376
5377     // Build a factor node to remember that this load is independent of the
5378     // other one.
5379     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5380                         Hi.getValue(1));
5381
5382     // Legalized the chain result - switch anything that used the old chain to
5383     // use the new one.
5384     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5385
5386     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5387
5388     SDValue RetOps[] = { LoadRes, Chain };
5389     return DAG.getMergeValues(RetOps, DL);
5390   }
5391   return SDValue();
5392 }
5393
5394 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5395   SDValue N0 = N->getOperand(0);
5396   SDValue N1 = N->getOperand(1);
5397   SDValue N2 = N->getOperand(2);
5398   SDLoc DL(N);
5399
5400   // Canonicalize integer abs.
5401   // vselect (setg[te] X,  0),  X, -X ->
5402   // vselect (setgt    X, -1),  X, -X ->
5403   // vselect (setl[te] X,  0), -X,  X ->
5404   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5405   if (N0.getOpcode() == ISD::SETCC) {
5406     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5407     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5408     bool isAbs = false;
5409     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5410
5411     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5412          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5413         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5414       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5415     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5416              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5417       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5418
5419     if (isAbs) {
5420       EVT VT = LHS.getValueType();
5421       SDValue Shift = DAG.getNode(
5422           ISD::SRA, DL, VT, LHS,
5423           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5424       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5425       AddToWorklist(Shift.getNode());
5426       AddToWorklist(Add.getNode());
5427       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5428     }
5429   }
5430
5431   if (SimplifySelectOps(N, N1, N2))
5432     return SDValue(N, 0);  // Don't revisit N.
5433
5434   // If the VSELECT result requires splitting and the mask is provided by a
5435   // SETCC, then split both nodes and its operands before legalization. This
5436   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5437   // and enables future optimizations (e.g. min/max pattern matching on X86).
5438   if (N0.getOpcode() == ISD::SETCC) {
5439     EVT VT = N->getValueType(0);
5440
5441     // Check if any splitting is required.
5442     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5443         TargetLowering::TypeSplitVector)
5444       return SDValue();
5445
5446     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5447     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5448     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5449     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5450
5451     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5452     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5453
5454     // Add the new VSELECT nodes to the work list in case they need to be split
5455     // again.
5456     AddToWorklist(Lo.getNode());
5457     AddToWorklist(Hi.getNode());
5458
5459     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5460   }
5461
5462   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5463   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5464     return N1;
5465   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5466   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5467     return N2;
5468
5469   // The ConvertSelectToConcatVector function is assuming both the above
5470   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5471   // and addressed.
5472   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5473       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5474       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5475     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5476     if (CV.getNode())
5477       return CV;
5478   }
5479
5480   return SDValue();
5481 }
5482
5483 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5484   SDValue N0 = N->getOperand(0);
5485   SDValue N1 = N->getOperand(1);
5486   SDValue N2 = N->getOperand(2);
5487   SDValue N3 = N->getOperand(3);
5488   SDValue N4 = N->getOperand(4);
5489   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5490
5491   // fold select_cc lhs, rhs, x, x, cc -> x
5492   if (N2 == N3)
5493     return N2;
5494
5495   // Determine if the condition we're dealing with is constant
5496   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5497                               N0, N1, CC, SDLoc(N), false);
5498   if (SCC.getNode()) {
5499     AddToWorklist(SCC.getNode());
5500
5501     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5502       if (!SCCC->isNullValue())
5503         return N2;    // cond always true -> true val
5504       else
5505         return N3;    // cond always false -> false val
5506     } else if (SCC->getOpcode() == ISD::UNDEF) {
5507       // When the condition is UNDEF, just return the first operand. This is
5508       // coherent the DAG creation, no setcc node is created in this case
5509       return N2;
5510     } else if (SCC.getOpcode() == ISD::SETCC) {
5511       // Fold to a simpler select_cc
5512       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5513                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5514                          SCC.getOperand(2));
5515     }
5516   }
5517
5518   // If we can fold this based on the true/false value, do so.
5519   if (SimplifySelectOps(N, N2, N3))
5520     return SDValue(N, 0);  // Don't revisit N.
5521
5522   // fold select_cc into other things, such as min/max/abs
5523   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5524 }
5525
5526 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5527   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5528                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5529                        SDLoc(N));
5530 }
5531
5532 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5533 // dag node into a ConstantSDNode or a build_vector of constants.
5534 // This function is called by the DAGCombiner when visiting sext/zext/aext
5535 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5536 // Vector extends are not folded if operations are legal; this is to
5537 // avoid introducing illegal build_vector dag nodes.
5538 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5539                                          SelectionDAG &DAG, bool LegalTypes,
5540                                          bool LegalOperations) {
5541   unsigned Opcode = N->getOpcode();
5542   SDValue N0 = N->getOperand(0);
5543   EVT VT = N->getValueType(0);
5544
5545   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5546          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5547          && "Expected EXTEND dag node in input!");
5548
5549   // fold (sext c1) -> c1
5550   // fold (zext c1) -> c1
5551   // fold (aext c1) -> c1
5552   if (isa<ConstantSDNode>(N0))
5553     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5554
5555   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5556   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5557   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5558   EVT SVT = VT.getScalarType();
5559   if (!(VT.isVector() &&
5560       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5561       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5562     return nullptr;
5563
5564   // We can fold this node into a build_vector.
5565   unsigned VTBits = SVT.getSizeInBits();
5566   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5567   unsigned ShAmt = VTBits - EVTBits;
5568   SmallVector<SDValue, 8> Elts;
5569   unsigned NumElts = VT.getVectorNumElements();
5570   SDLoc DL(N);
5571
5572   for (unsigned i=0; i != NumElts; ++i) {
5573     SDValue Op = N0->getOperand(i);
5574     if (Op->getOpcode() == ISD::UNDEF) {
5575       Elts.push_back(DAG.getUNDEF(SVT));
5576       continue;
5577     }
5578
5579     SDLoc DL(Op);
5580     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5581     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5582     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5583       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5584                                      DL, SVT));
5585     else
5586       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5587                                      DL, SVT));
5588   }
5589
5590   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5591 }
5592
5593 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5594 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5595 // transformation. Returns true if extension are possible and the above
5596 // mentioned transformation is profitable.
5597 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5598                                     unsigned ExtOpc,
5599                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5600                                     const TargetLowering &TLI) {
5601   bool HasCopyToRegUses = false;
5602   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5603   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5604                             UE = N0.getNode()->use_end();
5605        UI != UE; ++UI) {
5606     SDNode *User = *UI;
5607     if (User == N)
5608       continue;
5609     if (UI.getUse().getResNo() != N0.getResNo())
5610       continue;
5611     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5612     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5613       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5614       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5615         // Sign bits will be lost after a zext.
5616         return false;
5617       bool Add = false;
5618       for (unsigned i = 0; i != 2; ++i) {
5619         SDValue UseOp = User->getOperand(i);
5620         if (UseOp == N0)
5621           continue;
5622         if (!isa<ConstantSDNode>(UseOp))
5623           return false;
5624         Add = true;
5625       }
5626       if (Add)
5627         ExtendNodes.push_back(User);
5628       continue;
5629     }
5630     // If truncates aren't free and there are users we can't
5631     // extend, it isn't worthwhile.
5632     if (!isTruncFree)
5633       return false;
5634     // Remember if this value is live-out.
5635     if (User->getOpcode() == ISD::CopyToReg)
5636       HasCopyToRegUses = true;
5637   }
5638
5639   if (HasCopyToRegUses) {
5640     bool BothLiveOut = false;
5641     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5642          UI != UE; ++UI) {
5643       SDUse &Use = UI.getUse();
5644       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5645         BothLiveOut = true;
5646         break;
5647       }
5648     }
5649     if (BothLiveOut)
5650       // Both unextended and extended values are live out. There had better be
5651       // a good reason for the transformation.
5652       return ExtendNodes.size();
5653   }
5654   return true;
5655 }
5656
5657 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5658                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5659                                   ISD::NodeType ExtType) {
5660   // Extend SetCC uses if necessary.
5661   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5662     SDNode *SetCC = SetCCs[i];
5663     SmallVector<SDValue, 4> Ops;
5664
5665     for (unsigned j = 0; j != 2; ++j) {
5666       SDValue SOp = SetCC->getOperand(j);
5667       if (SOp == Trunc)
5668         Ops.push_back(ExtLoad);
5669       else
5670         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5671     }
5672
5673     Ops.push_back(SetCC->getOperand(2));
5674     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5675   }
5676 }
5677
5678 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5679 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5680   SDValue N0 = N->getOperand(0);
5681   EVT DstVT = N->getValueType(0);
5682   EVT SrcVT = N0.getValueType();
5683
5684   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5685           N->getOpcode() == ISD::ZERO_EXTEND) &&
5686          "Unexpected node type (not an extend)!");
5687
5688   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5689   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5690   //   (v8i32 (sext (v8i16 (load x))))
5691   // into:
5692   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5693   //                          (v4i32 (sextload (x + 16)))))
5694   // Where uses of the original load, i.e.:
5695   //   (v8i16 (load x))
5696   // are replaced with:
5697   //   (v8i16 (truncate
5698   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5699   //                            (v4i32 (sextload (x + 16)))))))
5700   //
5701   // This combine is only applicable to illegal, but splittable, vectors.
5702   // All legal types, and illegal non-vector types, are handled elsewhere.
5703   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5704   //
5705   if (N0->getOpcode() != ISD::LOAD)
5706     return SDValue();
5707
5708   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5709
5710   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5711       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5712       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5713     return SDValue();
5714
5715   SmallVector<SDNode *, 4> SetCCs;
5716   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5717     return SDValue();
5718
5719   ISD::LoadExtType ExtType =
5720       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5721
5722   // Try to split the vector types to get down to legal types.
5723   EVT SplitSrcVT = SrcVT;
5724   EVT SplitDstVT = DstVT;
5725   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5726          SplitSrcVT.getVectorNumElements() > 1) {
5727     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5728     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5729   }
5730
5731   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5732     return SDValue();
5733
5734   SDLoc DL(N);
5735   const unsigned NumSplits =
5736       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5737   const unsigned Stride = SplitSrcVT.getStoreSize();
5738   SmallVector<SDValue, 4> Loads;
5739   SmallVector<SDValue, 4> Chains;
5740
5741   SDValue BasePtr = LN0->getBasePtr();
5742   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5743     const unsigned Offset = Idx * Stride;
5744     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5745
5746     SDValue SplitLoad = DAG.getExtLoad(
5747         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5748         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5749         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5750         Align, LN0->getAAInfo());
5751
5752     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5753                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5754
5755     Loads.push_back(SplitLoad.getValue(0));
5756     Chains.push_back(SplitLoad.getValue(1));
5757   }
5758
5759   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5760   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5761
5762   CombineTo(N, NewValue);
5763
5764   // Replace uses of the original load (before extension)
5765   // with a truncate of the concatenated sextloaded vectors.
5766   SDValue Trunc =
5767       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5768   CombineTo(N0.getNode(), Trunc, NewChain);
5769   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5770                   (ISD::NodeType)N->getOpcode());
5771   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5772 }
5773
5774 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5775   SDValue N0 = N->getOperand(0);
5776   EVT VT = N->getValueType(0);
5777
5778   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5779                                               LegalOperations))
5780     return SDValue(Res, 0);
5781
5782   // fold (sext (sext x)) -> (sext x)
5783   // fold (sext (aext x)) -> (sext x)
5784   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5785     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5786                        N0.getOperand(0));
5787
5788   if (N0.getOpcode() == ISD::TRUNCATE) {
5789     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5790     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5791     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5792     if (NarrowLoad.getNode()) {
5793       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5794       if (NarrowLoad.getNode() != N0.getNode()) {
5795         CombineTo(N0.getNode(), NarrowLoad);
5796         // CombineTo deleted the truncate, if needed, but not what's under it.
5797         AddToWorklist(oye);
5798       }
5799       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5800     }
5801
5802     // See if the value being truncated is already sign extended.  If so, just
5803     // eliminate the trunc/sext pair.
5804     SDValue Op = N0.getOperand(0);
5805     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5806     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5807     unsigned DestBits = VT.getScalarType().getSizeInBits();
5808     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5809
5810     if (OpBits == DestBits) {
5811       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5812       // bits, it is already ready.
5813       if (NumSignBits > DestBits-MidBits)
5814         return Op;
5815     } else if (OpBits < DestBits) {
5816       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5817       // bits, just sext from i32.
5818       if (NumSignBits > OpBits-MidBits)
5819         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5820     } else {
5821       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5822       // bits, just truncate to i32.
5823       if (NumSignBits > OpBits-MidBits)
5824         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5825     }
5826
5827     // fold (sext (truncate x)) -> (sextinreg x).
5828     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5829                                                  N0.getValueType())) {
5830       if (OpBits < DestBits)
5831         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5832       else if (OpBits > DestBits)
5833         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5834       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5835                          DAG.getValueType(N0.getValueType()));
5836     }
5837   }
5838
5839   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5840   // Only generate vector extloads when 1) they're legal, and 2) they are
5841   // deemed desirable by the target.
5842   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5843       ((!LegalOperations && !VT.isVector() &&
5844         !cast<LoadSDNode>(N0)->isVolatile()) ||
5845        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5846     bool DoXform = true;
5847     SmallVector<SDNode*, 4> SetCCs;
5848     if (!N0.hasOneUse())
5849       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5850     if (VT.isVector())
5851       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5852     if (DoXform) {
5853       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5854       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5855                                        LN0->getChain(),
5856                                        LN0->getBasePtr(), N0.getValueType(),
5857                                        LN0->getMemOperand());
5858       CombineTo(N, ExtLoad);
5859       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5860                                   N0.getValueType(), ExtLoad);
5861       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5862       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5863                       ISD::SIGN_EXTEND);
5864       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5865     }
5866   }
5867
5868   // fold (sext (load x)) to multiple smaller sextloads.
5869   // Only on illegal but splittable vectors.
5870   if (SDValue ExtLoad = CombineExtLoad(N))
5871     return ExtLoad;
5872
5873   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5874   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5875   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5876       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5877     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5878     EVT MemVT = LN0->getMemoryVT();
5879     if ((!LegalOperations && !LN0->isVolatile()) ||
5880         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5881       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5882                                        LN0->getChain(),
5883                                        LN0->getBasePtr(), MemVT,
5884                                        LN0->getMemOperand());
5885       CombineTo(N, ExtLoad);
5886       CombineTo(N0.getNode(),
5887                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5888                             N0.getValueType(), ExtLoad),
5889                 ExtLoad.getValue(1));
5890       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5891     }
5892   }
5893
5894   // fold (sext (and/or/xor (load x), cst)) ->
5895   //      (and/or/xor (sextload x), (sext cst))
5896   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5897        N0.getOpcode() == ISD::XOR) &&
5898       isa<LoadSDNode>(N0.getOperand(0)) &&
5899       N0.getOperand(1).getOpcode() == ISD::Constant &&
5900       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5901       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5902     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5903     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5904       bool DoXform = true;
5905       SmallVector<SDNode*, 4> SetCCs;
5906       if (!N0.hasOneUse())
5907         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5908                                           SetCCs, TLI);
5909       if (DoXform) {
5910         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5911                                          LN0->getChain(), LN0->getBasePtr(),
5912                                          LN0->getMemoryVT(),
5913                                          LN0->getMemOperand());
5914         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5915         Mask = Mask.sext(VT.getSizeInBits());
5916         SDLoc DL(N);
5917         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5918                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5919         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5920                                     SDLoc(N0.getOperand(0)),
5921                                     N0.getOperand(0).getValueType(), ExtLoad);
5922         CombineTo(N, And);
5923         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5924         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5925                         ISD::SIGN_EXTEND);
5926         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5927       }
5928     }
5929   }
5930
5931   if (N0.getOpcode() == ISD::SETCC) {
5932     EVT N0VT = N0.getOperand(0).getValueType();
5933     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5934     // Only do this before legalize for now.
5935     if (VT.isVector() && !LegalOperations &&
5936         TLI.getBooleanContents(N0VT) ==
5937             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5938       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5939       // of the same size as the compared operands. Only optimize sext(setcc())
5940       // if this is the case.
5941       EVT SVT = getSetCCResultType(N0VT);
5942
5943       // We know that the # elements of the results is the same as the
5944       // # elements of the compare (and the # elements of the compare result
5945       // for that matter).  Check to see that they are the same size.  If so,
5946       // we know that the element size of the sext'd result matches the
5947       // element size of the compare operands.
5948       if (VT.getSizeInBits() == SVT.getSizeInBits())
5949         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5950                              N0.getOperand(1),
5951                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5952
5953       // If the desired elements are smaller or larger than the source
5954       // elements we can use a matching integer vector type and then
5955       // truncate/sign extend
5956       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5957       if (SVT == MatchingVectorType) {
5958         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5959                                N0.getOperand(0), N0.getOperand(1),
5960                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5961         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5962       }
5963     }
5964
5965     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5966     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5967     SDLoc DL(N);
5968     SDValue NegOne =
5969       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5970     SDValue SCC =
5971       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5972                        NegOne, DAG.getConstant(0, DL, VT),
5973                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5974     if (SCC.getNode()) return SCC;
5975
5976     if (!VT.isVector()) {
5977       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5978       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5979         SDLoc DL(N);
5980         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5981         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5982                                      N0.getOperand(0), N0.getOperand(1), CC);
5983         return DAG.getSelect(DL, VT, SetCC,
5984                              NegOne, DAG.getConstant(0, DL, VT));
5985       }
5986     }
5987   }
5988
5989   // fold (sext x) -> (zext x) if the sign bit is known zero.
5990   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5991       DAG.SignBitIsZero(N0))
5992     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5993
5994   return SDValue();
5995 }
5996
5997 // isTruncateOf - If N is a truncate of some other value, return true, record
5998 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5999 // This function computes KnownZero to avoid a duplicated call to
6000 // computeKnownBits in the caller.
6001 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6002                          APInt &KnownZero) {
6003   APInt KnownOne;
6004   if (N->getOpcode() == ISD::TRUNCATE) {
6005     Op = N->getOperand(0);
6006     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6007     return true;
6008   }
6009
6010   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6011       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6012     return false;
6013
6014   SDValue Op0 = N->getOperand(0);
6015   SDValue Op1 = N->getOperand(1);
6016   assert(Op0.getValueType() == Op1.getValueType());
6017
6018   if (isNullConstant(Op0))
6019     Op = Op1;
6020   else if (isNullConstant(Op1))
6021     Op = Op0;
6022   else
6023     return false;
6024
6025   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6026
6027   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6028     return false;
6029
6030   return true;
6031 }
6032
6033 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6034   SDValue N0 = N->getOperand(0);
6035   EVT VT = N->getValueType(0);
6036
6037   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6038                                               LegalOperations))
6039     return SDValue(Res, 0);
6040
6041   // fold (zext (zext x)) -> (zext x)
6042   // fold (zext (aext x)) -> (zext x)
6043   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6044     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6045                        N0.getOperand(0));
6046
6047   // fold (zext (truncate x)) -> (zext x) or
6048   //      (zext (truncate x)) -> (truncate x)
6049   // This is valid when the truncated bits of x are already zero.
6050   // FIXME: We should extend this to work for vectors too.
6051   SDValue Op;
6052   APInt KnownZero;
6053   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6054     APInt TruncatedBits =
6055       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6056       APInt(Op.getValueSizeInBits(), 0) :
6057       APInt::getBitsSet(Op.getValueSizeInBits(),
6058                         N0.getValueSizeInBits(),
6059                         std::min(Op.getValueSizeInBits(),
6060                                  VT.getSizeInBits()));
6061     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6062       if (VT.bitsGT(Op.getValueType()))
6063         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6064       if (VT.bitsLT(Op.getValueType()))
6065         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6066
6067       return Op;
6068     }
6069   }
6070
6071   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6072   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6073   if (N0.getOpcode() == ISD::TRUNCATE) {
6074     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6075     if (NarrowLoad.getNode()) {
6076       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6077       if (NarrowLoad.getNode() != N0.getNode()) {
6078         CombineTo(N0.getNode(), NarrowLoad);
6079         // CombineTo deleted the truncate, if needed, but not what's under it.
6080         AddToWorklist(oye);
6081       }
6082       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6083     }
6084   }
6085
6086   // fold (zext (truncate x)) -> (and x, mask)
6087   if (N0.getOpcode() == ISD::TRUNCATE &&
6088       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6089
6090     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6091     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6092     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6093     if (NarrowLoad.getNode()) {
6094       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6095       if (NarrowLoad.getNode() != N0.getNode()) {
6096         CombineTo(N0.getNode(), NarrowLoad);
6097         // CombineTo deleted the truncate, if needed, but not what's under it.
6098         AddToWorklist(oye);
6099       }
6100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6101     }
6102
6103     SDValue Op = N0.getOperand(0);
6104     if (Op.getValueType().bitsLT(VT)) {
6105       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6106       AddToWorklist(Op.getNode());
6107     } else if (Op.getValueType().bitsGT(VT)) {
6108       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6109       AddToWorklist(Op.getNode());
6110     }
6111     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6112                                   N0.getValueType().getScalarType());
6113   }
6114
6115   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6116   // if either of the casts is not free.
6117   if (N0.getOpcode() == ISD::AND &&
6118       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6119       N0.getOperand(1).getOpcode() == ISD::Constant &&
6120       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6121                            N0.getValueType()) ||
6122        !TLI.isZExtFree(N0.getValueType(), VT))) {
6123     SDValue X = N0.getOperand(0).getOperand(0);
6124     if (X.getValueType().bitsLT(VT)) {
6125       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6126     } else if (X.getValueType().bitsGT(VT)) {
6127       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6128     }
6129     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6130     Mask = Mask.zext(VT.getSizeInBits());
6131     SDLoc DL(N);
6132     return DAG.getNode(ISD::AND, DL, VT,
6133                        X, DAG.getConstant(Mask, DL, VT));
6134   }
6135
6136   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6137   // Only generate vector extloads when 1) they're legal, and 2) they are
6138   // deemed desirable by the target.
6139   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6140       ((!LegalOperations && !VT.isVector() &&
6141         !cast<LoadSDNode>(N0)->isVolatile()) ||
6142        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6143     bool DoXform = true;
6144     SmallVector<SDNode*, 4> SetCCs;
6145     if (!N0.hasOneUse())
6146       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6147     if (VT.isVector())
6148       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6149     if (DoXform) {
6150       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6151       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6152                                        LN0->getChain(),
6153                                        LN0->getBasePtr(), N0.getValueType(),
6154                                        LN0->getMemOperand());
6155       CombineTo(N, ExtLoad);
6156       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6157                                   N0.getValueType(), ExtLoad);
6158       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6159
6160       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6161                       ISD::ZERO_EXTEND);
6162       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6163     }
6164   }
6165
6166   // fold (zext (load x)) to multiple smaller zextloads.
6167   // Only on illegal but splittable vectors.
6168   if (SDValue ExtLoad = CombineExtLoad(N))
6169     return ExtLoad;
6170
6171   // fold (zext (and/or/xor (load x), cst)) ->
6172   //      (and/or/xor (zextload x), (zext cst))
6173   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6174        N0.getOpcode() == ISD::XOR) &&
6175       isa<LoadSDNode>(N0.getOperand(0)) &&
6176       N0.getOperand(1).getOpcode() == ISD::Constant &&
6177       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6178       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6179     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6180     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6181       bool DoXform = true;
6182       SmallVector<SDNode*, 4> SetCCs;
6183       if (!N0.hasOneUse())
6184         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6185                                           SetCCs, TLI);
6186       if (DoXform) {
6187         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6188                                          LN0->getChain(), LN0->getBasePtr(),
6189                                          LN0->getMemoryVT(),
6190                                          LN0->getMemOperand());
6191         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6192         Mask = Mask.zext(VT.getSizeInBits());
6193         SDLoc DL(N);
6194         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6195                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6196         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6197                                     SDLoc(N0.getOperand(0)),
6198                                     N0.getOperand(0).getValueType(), ExtLoad);
6199         CombineTo(N, And);
6200         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6201         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6202                         ISD::ZERO_EXTEND);
6203         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6204       }
6205     }
6206   }
6207
6208   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6209   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6210   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6211       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6212     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6213     EVT MemVT = LN0->getMemoryVT();
6214     if ((!LegalOperations && !LN0->isVolatile()) ||
6215         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6216       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6217                                        LN0->getChain(),
6218                                        LN0->getBasePtr(), MemVT,
6219                                        LN0->getMemOperand());
6220       CombineTo(N, ExtLoad);
6221       CombineTo(N0.getNode(),
6222                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6223                             ExtLoad),
6224                 ExtLoad.getValue(1));
6225       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6226     }
6227   }
6228
6229   if (N0.getOpcode() == ISD::SETCC) {
6230     if (!LegalOperations && VT.isVector() &&
6231         N0.getValueType().getVectorElementType() == MVT::i1) {
6232       EVT N0VT = N0.getOperand(0).getValueType();
6233       if (getSetCCResultType(N0VT) == N0.getValueType())
6234         return SDValue();
6235
6236       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6237       // Only do this before legalize for now.
6238       EVT EltVT = VT.getVectorElementType();
6239       SDLoc DL(N);
6240       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6241                                     DAG.getConstant(1, DL, EltVT));
6242       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6243         // We know that the # elements of the results is the same as the
6244         // # elements of the compare (and the # elements of the compare result
6245         // for that matter).  Check to see that they are the same size.  If so,
6246         // we know that the element size of the sext'd result matches the
6247         // element size of the compare operands.
6248         return DAG.getNode(ISD::AND, DL, VT,
6249                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6250                                          N0.getOperand(1),
6251                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6252                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6253                                        OneOps));
6254
6255       // If the desired elements are smaller or larger than the source
6256       // elements we can use a matching integer vector type and then
6257       // truncate/sign extend
6258       EVT MatchingElementType =
6259         EVT::getIntegerVT(*DAG.getContext(),
6260                           N0VT.getScalarType().getSizeInBits());
6261       EVT MatchingVectorType =
6262         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6263                          N0VT.getVectorNumElements());
6264       SDValue VsetCC =
6265         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6266                       N0.getOperand(1),
6267                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6268       return DAG.getNode(ISD::AND, DL, VT,
6269                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6270                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6271     }
6272
6273     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6274     SDLoc DL(N);
6275     SDValue SCC =
6276       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6277                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6278                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6279     if (SCC.getNode()) return SCC;
6280   }
6281
6282   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6283   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6284       isa<ConstantSDNode>(N0.getOperand(1)) &&
6285       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6286       N0.hasOneUse()) {
6287     SDValue ShAmt = N0.getOperand(1);
6288     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6289     if (N0.getOpcode() == ISD::SHL) {
6290       SDValue InnerZExt = N0.getOperand(0);
6291       // If the original shl may be shifting out bits, do not perform this
6292       // transformation.
6293       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6294         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6295       if (ShAmtVal > KnownZeroBits)
6296         return SDValue();
6297     }
6298
6299     SDLoc DL(N);
6300
6301     // Ensure that the shift amount is wide enough for the shifted value.
6302     if (VT.getSizeInBits() >= 256)
6303       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6304
6305     return DAG.getNode(N0.getOpcode(), DL, VT,
6306                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6307                        ShAmt);
6308   }
6309
6310   return SDValue();
6311 }
6312
6313 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6314   SDValue N0 = N->getOperand(0);
6315   EVT VT = N->getValueType(0);
6316
6317   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6318                                               LegalOperations))
6319     return SDValue(Res, 0);
6320
6321   // fold (aext (aext x)) -> (aext x)
6322   // fold (aext (zext x)) -> (zext x)
6323   // fold (aext (sext x)) -> (sext x)
6324   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6325       N0.getOpcode() == ISD::ZERO_EXTEND ||
6326       N0.getOpcode() == ISD::SIGN_EXTEND)
6327     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6328
6329   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6330   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6331   if (N0.getOpcode() == ISD::TRUNCATE) {
6332     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6333     if (NarrowLoad.getNode()) {
6334       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6335       if (NarrowLoad.getNode() != N0.getNode()) {
6336         CombineTo(N0.getNode(), NarrowLoad);
6337         // CombineTo deleted the truncate, if needed, but not what's under it.
6338         AddToWorklist(oye);
6339       }
6340       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6341     }
6342   }
6343
6344   // fold (aext (truncate x))
6345   if (N0.getOpcode() == ISD::TRUNCATE) {
6346     SDValue TruncOp = N0.getOperand(0);
6347     if (TruncOp.getValueType() == VT)
6348       return TruncOp; // x iff x size == zext size.
6349     if (TruncOp.getValueType().bitsGT(VT))
6350       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6351     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6352   }
6353
6354   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6355   // if the trunc is not free.
6356   if (N0.getOpcode() == ISD::AND &&
6357       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6358       N0.getOperand(1).getOpcode() == ISD::Constant &&
6359       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6360                           N0.getValueType())) {
6361     SDValue X = N0.getOperand(0).getOperand(0);
6362     if (X.getValueType().bitsLT(VT)) {
6363       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6364     } else if (X.getValueType().bitsGT(VT)) {
6365       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6366     }
6367     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6368     Mask = Mask.zext(VT.getSizeInBits());
6369     SDLoc DL(N);
6370     return DAG.getNode(ISD::AND, DL, VT,
6371                        X, DAG.getConstant(Mask, DL, VT));
6372   }
6373
6374   // fold (aext (load x)) -> (aext (truncate (extload x)))
6375   // None of the supported targets knows how to perform load and any_ext
6376   // on vectors in one instruction.  We only perform this transformation on
6377   // scalars.
6378   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6379       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6380       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6381     bool DoXform = true;
6382     SmallVector<SDNode*, 4> SetCCs;
6383     if (!N0.hasOneUse())
6384       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6385     if (DoXform) {
6386       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6387       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6388                                        LN0->getChain(),
6389                                        LN0->getBasePtr(), N0.getValueType(),
6390                                        LN0->getMemOperand());
6391       CombineTo(N, ExtLoad);
6392       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6393                                   N0.getValueType(), ExtLoad);
6394       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6395       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6396                       ISD::ANY_EXTEND);
6397       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6398     }
6399   }
6400
6401   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6402   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6403   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6404   if (N0.getOpcode() == ISD::LOAD &&
6405       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6406       N0.hasOneUse()) {
6407     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6408     ISD::LoadExtType ExtType = LN0->getExtensionType();
6409     EVT MemVT = LN0->getMemoryVT();
6410     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6411       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6412                                        VT, LN0->getChain(), LN0->getBasePtr(),
6413                                        MemVT, LN0->getMemOperand());
6414       CombineTo(N, ExtLoad);
6415       CombineTo(N0.getNode(),
6416                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6417                             N0.getValueType(), ExtLoad),
6418                 ExtLoad.getValue(1));
6419       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6420     }
6421   }
6422
6423   if (N0.getOpcode() == ISD::SETCC) {
6424     // For vectors:
6425     // aext(setcc) -> vsetcc
6426     // aext(setcc) -> truncate(vsetcc)
6427     // aext(setcc) -> aext(vsetcc)
6428     // Only do this before legalize for now.
6429     if (VT.isVector() && !LegalOperations) {
6430       EVT N0VT = N0.getOperand(0).getValueType();
6431         // We know that the # elements of the results is the same as the
6432         // # elements of the compare (and the # elements of the compare result
6433         // for that matter).  Check to see that they are the same size.  If so,
6434         // we know that the element size of the sext'd result matches the
6435         // element size of the compare operands.
6436       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6437         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6438                              N0.getOperand(1),
6439                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6440       // If the desired elements are smaller or larger than the source
6441       // elements we can use a matching integer vector type and then
6442       // truncate/any extend
6443       else {
6444         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6445         SDValue VsetCC =
6446           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6447                         N0.getOperand(1),
6448                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6449         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6450       }
6451     }
6452
6453     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6454     SDLoc DL(N);
6455     SDValue SCC =
6456       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6457                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6458                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6459     if (SCC.getNode())
6460       return SCC;
6461   }
6462
6463   return SDValue();
6464 }
6465
6466 /// See if the specified operand can be simplified with the knowledge that only
6467 /// the bits specified by Mask are used.  If so, return the simpler operand,
6468 /// otherwise return a null SDValue.
6469 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6470   switch (V.getOpcode()) {
6471   default: break;
6472   case ISD::Constant: {
6473     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6474     assert(CV && "Const value should be ConstSDNode.");
6475     const APInt &CVal = CV->getAPIntValue();
6476     APInt NewVal = CVal & Mask;
6477     if (NewVal != CVal)
6478       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6479     break;
6480   }
6481   case ISD::OR:
6482   case ISD::XOR:
6483     // If the LHS or RHS don't contribute bits to the or, drop them.
6484     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6485       return V.getOperand(1);
6486     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6487       return V.getOperand(0);
6488     break;
6489   case ISD::SRL:
6490     // Only look at single-use SRLs.
6491     if (!V.getNode()->hasOneUse())
6492       break;
6493     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6494       // See if we can recursively simplify the LHS.
6495       unsigned Amt = RHSC->getZExtValue();
6496
6497       // Watch out for shift count overflow though.
6498       if (Amt >= Mask.getBitWidth()) break;
6499       APInt NewMask = Mask << Amt;
6500       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6501       if (SimplifyLHS.getNode())
6502         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6503                            SimplifyLHS, V.getOperand(1));
6504     }
6505   }
6506   return SDValue();
6507 }
6508
6509 /// If the result of a wider load is shifted to right of N  bits and then
6510 /// truncated to a narrower type and where N is a multiple of number of bits of
6511 /// the narrower type, transform it to a narrower load from address + N / num of
6512 /// bits of new type. If the result is to be extended, also fold the extension
6513 /// to form a extending load.
6514 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6515   unsigned Opc = N->getOpcode();
6516
6517   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6518   SDValue N0 = N->getOperand(0);
6519   EVT VT = N->getValueType(0);
6520   EVT ExtVT = VT;
6521
6522   // This transformation isn't valid for vector loads.
6523   if (VT.isVector())
6524     return SDValue();
6525
6526   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6527   // extended to VT.
6528   if (Opc == ISD::SIGN_EXTEND_INREG) {
6529     ExtType = ISD::SEXTLOAD;
6530     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6531   } else if (Opc == ISD::SRL) {
6532     // Another special-case: SRL is basically zero-extending a narrower value.
6533     ExtType = ISD::ZEXTLOAD;
6534     N0 = SDValue(N, 0);
6535     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6536     if (!N01) return SDValue();
6537     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6538                               VT.getSizeInBits() - N01->getZExtValue());
6539   }
6540   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6541     return SDValue();
6542
6543   unsigned EVTBits = ExtVT.getSizeInBits();
6544
6545   // Do not generate loads of non-round integer types since these can
6546   // be expensive (and would be wrong if the type is not byte sized).
6547   if (!ExtVT.isRound())
6548     return SDValue();
6549
6550   unsigned ShAmt = 0;
6551   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6552     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6553       ShAmt = N01->getZExtValue();
6554       // Is the shift amount a multiple of size of VT?
6555       if ((ShAmt & (EVTBits-1)) == 0) {
6556         N0 = N0.getOperand(0);
6557         // Is the load width a multiple of size of VT?
6558         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6559           return SDValue();
6560       }
6561
6562       // At this point, we must have a load or else we can't do the transform.
6563       if (!isa<LoadSDNode>(N0)) return SDValue();
6564
6565       // Because a SRL must be assumed to *need* to zero-extend the high bits
6566       // (as opposed to anyext the high bits), we can't combine the zextload
6567       // lowering of SRL and an sextload.
6568       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6569         return SDValue();
6570
6571       // If the shift amount is larger than the input type then we're not
6572       // accessing any of the loaded bytes.  If the load was a zextload/extload
6573       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6574       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6575         return SDValue();
6576     }
6577   }
6578
6579   // If the load is shifted left (and the result isn't shifted back right),
6580   // we can fold the truncate through the shift.
6581   unsigned ShLeftAmt = 0;
6582   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6583       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6584     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6585       ShLeftAmt = N01->getZExtValue();
6586       N0 = N0.getOperand(0);
6587     }
6588   }
6589
6590   // If we haven't found a load, we can't narrow it.  Don't transform one with
6591   // multiple uses, this would require adding a new load.
6592   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6593     return SDValue();
6594
6595   // Don't change the width of a volatile load.
6596   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6597   if (LN0->isVolatile())
6598     return SDValue();
6599
6600   // Verify that we are actually reducing a load width here.
6601   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6602     return SDValue();
6603
6604   // For the transform to be legal, the load must produce only two values
6605   // (the value loaded and the chain).  Don't transform a pre-increment
6606   // load, for example, which produces an extra value.  Otherwise the
6607   // transformation is not equivalent, and the downstream logic to replace
6608   // uses gets things wrong.
6609   if (LN0->getNumValues() > 2)
6610     return SDValue();
6611
6612   // If the load that we're shrinking is an extload and we're not just
6613   // discarding the extension we can't simply shrink the load. Bail.
6614   // TODO: It would be possible to merge the extensions in some cases.
6615   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6616       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6617     return SDValue();
6618
6619   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6620     return SDValue();
6621
6622   EVT PtrType = N0.getOperand(1).getValueType();
6623
6624   if (PtrType == MVT::Untyped || PtrType.isExtended())
6625     // It's not possible to generate a constant of extended or untyped type.
6626     return SDValue();
6627
6628   // For big endian targets, we need to adjust the offset to the pointer to
6629   // load the correct bytes.
6630   if (TLI.isBigEndian()) {
6631     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6632     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6633     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6634   }
6635
6636   uint64_t PtrOff = ShAmt / 8;
6637   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6638   SDLoc DL(LN0);
6639   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6640                                PtrType, LN0->getBasePtr(),
6641                                DAG.getConstant(PtrOff, DL, PtrType));
6642   AddToWorklist(NewPtr.getNode());
6643
6644   SDValue Load;
6645   if (ExtType == ISD::NON_EXTLOAD)
6646     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6647                         LN0->getPointerInfo().getWithOffset(PtrOff),
6648                         LN0->isVolatile(), LN0->isNonTemporal(),
6649                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6650   else
6651     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6652                           LN0->getPointerInfo().getWithOffset(PtrOff),
6653                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6654                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6655
6656   // Replace the old load's chain with the new load's chain.
6657   WorklistRemover DeadNodes(*this);
6658   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6659
6660   // Shift the result left, if we've swallowed a left shift.
6661   SDValue Result = Load;
6662   if (ShLeftAmt != 0) {
6663     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6664     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6665       ShImmTy = VT;
6666     // If the shift amount is as large as the result size (but, presumably,
6667     // no larger than the source) then the useful bits of the result are
6668     // zero; we can't simply return the shortened shift, because the result
6669     // of that operation is undefined.
6670     SDLoc DL(N0);
6671     if (ShLeftAmt >= VT.getSizeInBits())
6672       Result = DAG.getConstant(0, DL, VT);
6673     else
6674       Result = DAG.getNode(ISD::SHL, DL, VT,
6675                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6676   }
6677
6678   // Return the new loaded value.
6679   return Result;
6680 }
6681
6682 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6683   SDValue N0 = N->getOperand(0);
6684   SDValue N1 = N->getOperand(1);
6685   EVT VT = N->getValueType(0);
6686   EVT EVT = cast<VTSDNode>(N1)->getVT();
6687   unsigned VTBits = VT.getScalarType().getSizeInBits();
6688   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6689
6690   // fold (sext_in_reg c1) -> c1
6691   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6692     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6693
6694   // If the input is already sign extended, just drop the extension.
6695   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6696     return N0;
6697
6698   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6699   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6700       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6701     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6702                        N0.getOperand(0), N1);
6703
6704   // fold (sext_in_reg (sext x)) -> (sext x)
6705   // fold (sext_in_reg (aext x)) -> (sext x)
6706   // if x is small enough.
6707   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6708     SDValue N00 = N0.getOperand(0);
6709     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6710         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6711       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6712   }
6713
6714   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6715   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6716     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6717
6718   // fold operands of sext_in_reg based on knowledge that the top bits are not
6719   // demanded.
6720   if (SimplifyDemandedBits(SDValue(N, 0)))
6721     return SDValue(N, 0);
6722
6723   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6724   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6725   SDValue NarrowLoad = ReduceLoadWidth(N);
6726   if (NarrowLoad.getNode())
6727     return NarrowLoad;
6728
6729   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6730   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6731   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6732   if (N0.getOpcode() == ISD::SRL) {
6733     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6734       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6735         // We can turn this into an SRA iff the input to the SRL is already sign
6736         // extended enough.
6737         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6738         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6739           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6740                              N0.getOperand(0), N0.getOperand(1));
6741       }
6742   }
6743
6744   // fold (sext_inreg (extload x)) -> (sextload x)
6745   if (ISD::isEXTLoad(N0.getNode()) &&
6746       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6747       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6748       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6749        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6750     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6751     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6752                                      LN0->getChain(),
6753                                      LN0->getBasePtr(), EVT,
6754                                      LN0->getMemOperand());
6755     CombineTo(N, ExtLoad);
6756     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6757     AddToWorklist(ExtLoad.getNode());
6758     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6759   }
6760   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6761   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6762       N0.hasOneUse() &&
6763       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6764       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6765        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6766     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6767     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6768                                      LN0->getChain(),
6769                                      LN0->getBasePtr(), EVT,
6770                                      LN0->getMemOperand());
6771     CombineTo(N, ExtLoad);
6772     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6773     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6774   }
6775
6776   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6777   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6778     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6779                                        N0.getOperand(1), false);
6780     if (BSwap.getNode())
6781       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6782                          BSwap, N1);
6783   }
6784
6785   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6786   // into a build_vector.
6787   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6788     SmallVector<SDValue, 8> Elts;
6789     unsigned NumElts = N0->getNumOperands();
6790     unsigned ShAmt = VTBits - EVTBits;
6791
6792     for (unsigned i = 0; i != NumElts; ++i) {
6793       SDValue Op = N0->getOperand(i);
6794       if (Op->getOpcode() == ISD::UNDEF) {
6795         Elts.push_back(Op);
6796         continue;
6797       }
6798
6799       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6800       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6801       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6802                                      SDLoc(Op), Op.getValueType()));
6803     }
6804
6805     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6806   }
6807
6808   return SDValue();
6809 }
6810
6811 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6812   SDValue N0 = N->getOperand(0);
6813   EVT VT = N->getValueType(0);
6814
6815   if (N0.getOpcode() == ISD::UNDEF)
6816     return DAG.getUNDEF(VT);
6817
6818   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6819                                               LegalOperations))
6820     return SDValue(Res, 0);
6821
6822   return SDValue();
6823 }
6824
6825 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6826   SDValue N0 = N->getOperand(0);
6827   EVT VT = N->getValueType(0);
6828   bool isLE = TLI.isLittleEndian();
6829
6830   // noop truncate
6831   if (N0.getValueType() == N->getValueType(0))
6832     return N0;
6833   // fold (truncate c1) -> c1
6834   if (isConstantIntBuildVectorOrConstantInt(N0))
6835     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6836   // fold (truncate (truncate x)) -> (truncate x)
6837   if (N0.getOpcode() == ISD::TRUNCATE)
6838     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6839   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6840   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6841       N0.getOpcode() == ISD::SIGN_EXTEND ||
6842       N0.getOpcode() == ISD::ANY_EXTEND) {
6843     if (N0.getOperand(0).getValueType().bitsLT(VT))
6844       // if the source is smaller than the dest, we still need an extend
6845       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6846                          N0.getOperand(0));
6847     if (N0.getOperand(0).getValueType().bitsGT(VT))
6848       // if the source is larger than the dest, than we just need the truncate
6849       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6850     // if the source and dest are the same type, we can drop both the extend
6851     // and the truncate.
6852     return N0.getOperand(0);
6853   }
6854
6855   // Fold extract-and-trunc into a narrow extract. For example:
6856   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6857   //   i32 y = TRUNCATE(i64 x)
6858   //        -- becomes --
6859   //   v16i8 b = BITCAST (v2i64 val)
6860   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6861   //
6862   // Note: We only run this optimization after type legalization (which often
6863   // creates this pattern) and before operation legalization after which
6864   // we need to be more careful about the vector instructions that we generate.
6865   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6866       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6867
6868     EVT VecTy = N0.getOperand(0).getValueType();
6869     EVT ExTy = N0.getValueType();
6870     EVT TrTy = N->getValueType(0);
6871
6872     unsigned NumElem = VecTy.getVectorNumElements();
6873     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6874
6875     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6876     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6877
6878     SDValue EltNo = N0->getOperand(1);
6879     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6880       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6881       EVT IndexTy = TLI.getVectorIdxTy();
6882       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6883
6884       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6885                               NVT, N0.getOperand(0));
6886
6887       SDLoc DL(N);
6888       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6889                          DL, TrTy, V,
6890                          DAG.getConstant(Index, DL, IndexTy));
6891     }
6892   }
6893
6894   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6895   if (N0.getOpcode() == ISD::SELECT) {
6896     EVT SrcVT = N0.getValueType();
6897     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6898         TLI.isTruncateFree(SrcVT, VT)) {
6899       SDLoc SL(N0);
6900       SDValue Cond = N0.getOperand(0);
6901       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6902       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6903       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6904     }
6905   }
6906
6907   // Fold a series of buildvector, bitcast, and truncate if possible.
6908   // For example fold
6909   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6910   //   (2xi32 (buildvector x, y)).
6911   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6912       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6913       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6914       N0.getOperand(0).hasOneUse()) {
6915
6916     SDValue BuildVect = N0.getOperand(0);
6917     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6918     EVT TruncVecEltTy = VT.getVectorElementType();
6919
6920     // Check that the element types match.
6921     if (BuildVectEltTy == TruncVecEltTy) {
6922       // Now we only need to compute the offset of the truncated elements.
6923       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6924       unsigned TruncVecNumElts = VT.getVectorNumElements();
6925       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6926
6927       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6928              "Invalid number of elements");
6929
6930       SmallVector<SDValue, 8> Opnds;
6931       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6932         Opnds.push_back(BuildVect.getOperand(i));
6933
6934       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6935     }
6936   }
6937
6938   // See if we can simplify the input to this truncate through knowledge that
6939   // only the low bits are being used.
6940   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6941   // Currently we only perform this optimization on scalars because vectors
6942   // may have different active low bits.
6943   if (!VT.isVector()) {
6944     SDValue Shorter =
6945       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6946                                                VT.getSizeInBits()));
6947     if (Shorter.getNode())
6948       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6949   }
6950   // fold (truncate (load x)) -> (smaller load x)
6951   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6952   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6953     SDValue Reduced = ReduceLoadWidth(N);
6954     if (Reduced.getNode())
6955       return Reduced;
6956     // Handle the case where the load remains an extending load even
6957     // after truncation.
6958     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6959       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6960       if (!LN0->isVolatile() &&
6961           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6962         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6963                                          VT, LN0->getChain(), LN0->getBasePtr(),
6964                                          LN0->getMemoryVT(),
6965                                          LN0->getMemOperand());
6966         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6967         return NewLoad;
6968       }
6969     }
6970   }
6971   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6972   // where ... are all 'undef'.
6973   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6974     SmallVector<EVT, 8> VTs;
6975     SDValue V;
6976     unsigned Idx = 0;
6977     unsigned NumDefs = 0;
6978
6979     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6980       SDValue X = N0.getOperand(i);
6981       if (X.getOpcode() != ISD::UNDEF) {
6982         V = X;
6983         Idx = i;
6984         NumDefs++;
6985       }
6986       // Stop if more than one members are non-undef.
6987       if (NumDefs > 1)
6988         break;
6989       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6990                                      VT.getVectorElementType(),
6991                                      X.getValueType().getVectorNumElements()));
6992     }
6993
6994     if (NumDefs == 0)
6995       return DAG.getUNDEF(VT);
6996
6997     if (NumDefs == 1) {
6998       assert(V.getNode() && "The single defined operand is empty!");
6999       SmallVector<SDValue, 8> Opnds;
7000       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7001         if (i != Idx) {
7002           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7003           continue;
7004         }
7005         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7006         AddToWorklist(NV.getNode());
7007         Opnds.push_back(NV);
7008       }
7009       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7010     }
7011   }
7012
7013   // Simplify the operands using demanded-bits information.
7014   if (!VT.isVector() &&
7015       SimplifyDemandedBits(SDValue(N, 0)))
7016     return SDValue(N, 0);
7017
7018   return SDValue();
7019 }
7020
7021 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7022   SDValue Elt = N->getOperand(i);
7023   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7024     return Elt.getNode();
7025   return Elt.getOperand(Elt.getResNo()).getNode();
7026 }
7027
7028 /// build_pair (load, load) -> load
7029 /// if load locations are consecutive.
7030 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7031   assert(N->getOpcode() == ISD::BUILD_PAIR);
7032
7033   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7034   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7035   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7036       LD1->getAddressSpace() != LD2->getAddressSpace())
7037     return SDValue();
7038   EVT LD1VT = LD1->getValueType(0);
7039
7040   if (ISD::isNON_EXTLoad(LD2) &&
7041       LD2->hasOneUse() &&
7042       // If both are volatile this would reduce the number of volatile loads.
7043       // If one is volatile it might be ok, but play conservative and bail out.
7044       !LD1->isVolatile() &&
7045       !LD2->isVolatile() &&
7046       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7047     unsigned Align = LD1->getAlignment();
7048     unsigned NewAlign = TLI.getDataLayout()->
7049       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7050
7051     if (NewAlign <= Align &&
7052         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7053       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7054                          LD1->getBasePtr(), LD1->getPointerInfo(),
7055                          false, false, false, Align);
7056   }
7057
7058   return SDValue();
7059 }
7060
7061 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7062   SDValue N0 = N->getOperand(0);
7063   EVT VT = N->getValueType(0);
7064
7065   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7066   // Only do this before legalize, since afterward the target may be depending
7067   // on the bitconvert.
7068   // First check to see if this is all constant.
7069   if (!LegalTypes &&
7070       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7071       VT.isVector()) {
7072     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7073
7074     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7075     assert(!DestEltVT.isVector() &&
7076            "Element type of vector ValueType must not be vector!");
7077     if (isSimple)
7078       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7079   }
7080
7081   // If the input is a constant, let getNode fold it.
7082   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7083     // If we can't allow illegal operations, we need to check that this is just
7084     // a fp -> int or int -> conversion and that the resulting operation will
7085     // be legal.
7086     if (!LegalOperations ||
7087         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7088          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7089         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7090          TLI.isOperationLegal(ISD::Constant, VT)))
7091       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7092   }
7093
7094   // (conv (conv x, t1), t2) -> (conv x, t2)
7095   if (N0.getOpcode() == ISD::BITCAST)
7096     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7097                        N0.getOperand(0));
7098
7099   // fold (conv (load x)) -> (load (conv*)x)
7100   // If the resultant load doesn't need a higher alignment than the original!
7101   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7102       // Do not change the width of a volatile load.
7103       !cast<LoadSDNode>(N0)->isVolatile() &&
7104       // Do not remove the cast if the types differ in endian layout.
7105       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7106       TLI.hasBigEndianPartOrdering(VT) &&
7107       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7108       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7109     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7110     unsigned Align = TLI.getDataLayout()->
7111       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7112     unsigned OrigAlign = LN0->getAlignment();
7113
7114     if (Align <= OrigAlign) {
7115       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7116                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7117                                  LN0->isVolatile(), LN0->isNonTemporal(),
7118                                  LN0->isInvariant(), OrigAlign,
7119                                  LN0->getAAInfo());
7120       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7121       return Load;
7122     }
7123   }
7124
7125   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7126   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7127   // This often reduces constant pool loads.
7128   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7129        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7130       N0.getNode()->hasOneUse() && VT.isInteger() &&
7131       !VT.isVector() && !N0.getValueType().isVector()) {
7132     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7133                                   N0.getOperand(0));
7134     AddToWorklist(NewConv.getNode());
7135
7136     SDLoc DL(N);
7137     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7138     if (N0.getOpcode() == ISD::FNEG)
7139       return DAG.getNode(ISD::XOR, DL, VT,
7140                          NewConv, DAG.getConstant(SignBit, DL, VT));
7141     assert(N0.getOpcode() == ISD::FABS);
7142     return DAG.getNode(ISD::AND, DL, VT,
7143                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7144   }
7145
7146   // fold (bitconvert (fcopysign cst, x)) ->
7147   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7148   // Note that we don't handle (copysign x, cst) because this can always be
7149   // folded to an fneg or fabs.
7150   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7151       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7152       VT.isInteger() && !VT.isVector()) {
7153     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7154     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7155     if (isTypeLegal(IntXVT)) {
7156       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7157                               IntXVT, N0.getOperand(1));
7158       AddToWorklist(X.getNode());
7159
7160       // If X has a different width than the result/lhs, sext it or truncate it.
7161       unsigned VTWidth = VT.getSizeInBits();
7162       if (OrigXWidth < VTWidth) {
7163         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7164         AddToWorklist(X.getNode());
7165       } else if (OrigXWidth > VTWidth) {
7166         // To get the sign bit in the right place, we have to shift it right
7167         // before truncating.
7168         SDLoc DL(X);
7169         X = DAG.getNode(ISD::SRL, DL,
7170                         X.getValueType(), X,
7171                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7172                                         X.getValueType()));
7173         AddToWorklist(X.getNode());
7174         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7175         AddToWorklist(X.getNode());
7176       }
7177
7178       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7179       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7180                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7181       AddToWorklist(X.getNode());
7182
7183       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7184                                 VT, N0.getOperand(0));
7185       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7186                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7187       AddToWorklist(Cst.getNode());
7188
7189       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7190     }
7191   }
7192
7193   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7194   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7195     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7196     if (CombineLD.getNode())
7197       return CombineLD;
7198   }
7199
7200   // Remove double bitcasts from shuffles - this is often a legacy of
7201   // XformToShuffleWithZero being used to combine bitmaskings (of
7202   // float vectors bitcast to integer vectors) into shuffles.
7203   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7204   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7205       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7206       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7207       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7208     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7209
7210     // If operands are a bitcast, peek through if it casts the original VT.
7211     // If operands are a UNDEF or constant, just bitcast back to original VT.
7212     auto PeekThroughBitcast = [&](SDValue Op) {
7213       if (Op.getOpcode() == ISD::BITCAST &&
7214           Op.getOperand(0)->getValueType(0) == VT)
7215         return SDValue(Op.getOperand(0));
7216       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7217           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7218         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7219       return SDValue();
7220     };
7221
7222     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7223     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7224     if (!(SV0 && SV1))
7225       return SDValue();
7226
7227     int MaskScale =
7228         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7229     SmallVector<int, 8> NewMask;
7230     for (int M : SVN->getMask())
7231       for (int i = 0; i != MaskScale; ++i)
7232         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7233
7234     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7235     if (!LegalMask) {
7236       std::swap(SV0, SV1);
7237       ShuffleVectorSDNode::commuteMask(NewMask);
7238       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7239     }
7240
7241     if (LegalMask)
7242       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7243   }
7244
7245   return SDValue();
7246 }
7247
7248 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7249   EVT VT = N->getValueType(0);
7250   return CombineConsecutiveLoads(N, VT);
7251 }
7252
7253 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7254 /// operands. DstEltVT indicates the destination element value type.
7255 SDValue DAGCombiner::
7256 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7257   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7258
7259   // If this is already the right type, we're done.
7260   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7261
7262   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7263   unsigned DstBitSize = DstEltVT.getSizeInBits();
7264
7265   // If this is a conversion of N elements of one type to N elements of another
7266   // type, convert each element.  This handles FP<->INT cases.
7267   if (SrcBitSize == DstBitSize) {
7268     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7269                               BV->getValueType(0).getVectorNumElements());
7270
7271     // Due to the FP element handling below calling this routine recursively,
7272     // we can end up with a scalar-to-vector node here.
7273     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7274       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7275                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7276                                      DstEltVT, BV->getOperand(0)));
7277
7278     SmallVector<SDValue, 8> Ops;
7279     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7280       SDValue Op = BV->getOperand(i);
7281       // If the vector element type is not legal, the BUILD_VECTOR operands
7282       // are promoted and implicitly truncated.  Make that explicit here.
7283       if (Op.getValueType() != SrcEltVT)
7284         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7285       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7286                                 DstEltVT, Op));
7287       AddToWorklist(Ops.back().getNode());
7288     }
7289     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7290   }
7291
7292   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7293   // handle annoying details of growing/shrinking FP values, we convert them to
7294   // int first.
7295   if (SrcEltVT.isFloatingPoint()) {
7296     // Convert the input float vector to a int vector where the elements are the
7297     // same sizes.
7298     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7299     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7300     SrcEltVT = IntVT;
7301   }
7302
7303   // Now we know the input is an integer vector.  If the output is a FP type,
7304   // convert to integer first, then to FP of the right size.
7305   if (DstEltVT.isFloatingPoint()) {
7306     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7307     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7308
7309     // Next, convert to FP elements of the same size.
7310     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7311   }
7312
7313   SDLoc DL(BV);
7314
7315   // Okay, we know the src/dst types are both integers of differing types.
7316   // Handling growing first.
7317   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7318   if (SrcBitSize < DstBitSize) {
7319     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7320
7321     SmallVector<SDValue, 8> Ops;
7322     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7323          i += NumInputsPerOutput) {
7324       bool isLE = TLI.isLittleEndian();
7325       APInt NewBits = APInt(DstBitSize, 0);
7326       bool EltIsUndef = true;
7327       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7328         // Shift the previously computed bits over.
7329         NewBits <<= SrcBitSize;
7330         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7331         if (Op.getOpcode() == ISD::UNDEF) continue;
7332         EltIsUndef = false;
7333
7334         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7335                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7336       }
7337
7338       if (EltIsUndef)
7339         Ops.push_back(DAG.getUNDEF(DstEltVT));
7340       else
7341         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7342     }
7343
7344     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7345     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7346   }
7347
7348   // Finally, this must be the case where we are shrinking elements: each input
7349   // turns into multiple outputs.
7350   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7351   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7352                             NumOutputsPerInput*BV->getNumOperands());
7353   SmallVector<SDValue, 8> Ops;
7354
7355   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7356     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7357       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7358       continue;
7359     }
7360
7361     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7362                   getAPIntValue().zextOrTrunc(SrcBitSize);
7363
7364     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7365       APInt ThisVal = OpVal.trunc(DstBitSize);
7366       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7367       OpVal = OpVal.lshr(DstBitSize);
7368     }
7369
7370     // For big endian targets, swap the order of the pieces of each element.
7371     if (TLI.isBigEndian())
7372       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7373   }
7374
7375   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7376 }
7377
7378 /// Try to perform FMA combining on a given FADD node.
7379 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7380   SDValue N0 = N->getOperand(0);
7381   SDValue N1 = N->getOperand(1);
7382   EVT VT = N->getValueType(0);
7383   SDLoc SL(N);
7384
7385   const TargetOptions &Options = DAG.getTarget().Options;
7386   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7387                        Options.UnsafeFPMath);
7388
7389   // Floating-point multiply-add with intermediate rounding.
7390   bool HasFMAD = (LegalOperations &&
7391                   TLI.isOperationLegal(ISD::FMAD, VT));
7392
7393   // Floating-point multiply-add without intermediate rounding.
7394   bool HasFMA = ((!LegalOperations ||
7395                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7396                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7397                  UnsafeFPMath);
7398
7399   // No valid opcode, do not combine.
7400   if (!HasFMAD && !HasFMA)
7401     return SDValue();
7402
7403   // Always prefer FMAD to FMA for precision.
7404   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7405   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7406   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7407
7408   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7409   if (N0.getOpcode() == ISD::FMUL &&
7410       (Aggressive || N0->hasOneUse())) {
7411     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7412                        N0.getOperand(0), N0.getOperand(1), N1);
7413   }
7414
7415   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7416   // Note: Commutes FADD operands.
7417   if (N1.getOpcode() == ISD::FMUL &&
7418       (Aggressive || N1->hasOneUse())) {
7419     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7420                        N1.getOperand(0), N1.getOperand(1), N0);
7421   }
7422
7423   // Look through FP_EXTEND nodes to do more combining.
7424   if (UnsafeFPMath && LookThroughFPExt) {
7425     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7426     if (N0.getOpcode() == ISD::FP_EXTEND) {
7427       SDValue N00 = N0.getOperand(0);
7428       if (N00.getOpcode() == ISD::FMUL)
7429         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7430                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7431                                        N00.getOperand(0)),
7432                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7433                                        N00.getOperand(1)), N1);
7434     }
7435
7436     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7437     // Note: Commutes FADD operands.
7438     if (N1.getOpcode() == ISD::FP_EXTEND) {
7439       SDValue N10 = N1.getOperand(0);
7440       if (N10.getOpcode() == ISD::FMUL)
7441         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7442                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7443                                        N10.getOperand(0)),
7444                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7445                                        N10.getOperand(1)), N0);
7446     }
7447   }
7448
7449   // More folding opportunities when target permits.
7450   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7451     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7452     if (N0.getOpcode() == PreferredFusedOpcode &&
7453         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7454       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7455                          N0.getOperand(0), N0.getOperand(1),
7456                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7457                                      N0.getOperand(2).getOperand(0),
7458                                      N0.getOperand(2).getOperand(1),
7459                                      N1));
7460     }
7461
7462     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7463     if (N1->getOpcode() == PreferredFusedOpcode &&
7464         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7465       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7466                          N1.getOperand(0), N1.getOperand(1),
7467                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7468                                      N1.getOperand(2).getOperand(0),
7469                                      N1.getOperand(2).getOperand(1),
7470                                      N0));
7471     }
7472
7473     if (UnsafeFPMath && LookThroughFPExt) {
7474       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7475       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7476       auto FoldFAddFMAFPExtFMul = [&] (
7477           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7478         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7479                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7480                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7481                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7482                                        Z));
7483       };
7484       if (N0.getOpcode() == PreferredFusedOpcode) {
7485         SDValue N02 = N0.getOperand(2);
7486         if (N02.getOpcode() == ISD::FP_EXTEND) {
7487           SDValue N020 = N02.getOperand(0);
7488           if (N020.getOpcode() == ISD::FMUL)
7489             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7490                                         N020.getOperand(0), N020.getOperand(1),
7491                                         N1);
7492         }
7493       }
7494
7495       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7496       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7497       // FIXME: This turns two single-precision and one double-precision
7498       // operation into two double-precision operations, which might not be
7499       // interesting for all targets, especially GPUs.
7500       auto FoldFAddFPExtFMAFMul = [&] (
7501           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7502         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7503                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7504                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7505                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7506                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7507                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7508                                        Z));
7509       };
7510       if (N0.getOpcode() == ISD::FP_EXTEND) {
7511         SDValue N00 = N0.getOperand(0);
7512         if (N00.getOpcode() == PreferredFusedOpcode) {
7513           SDValue N002 = N00.getOperand(2);
7514           if (N002.getOpcode() == ISD::FMUL)
7515             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7516                                         N002.getOperand(0), N002.getOperand(1),
7517                                         N1);
7518         }
7519       }
7520
7521       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7522       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7523       if (N1.getOpcode() == PreferredFusedOpcode) {
7524         SDValue N12 = N1.getOperand(2);
7525         if (N12.getOpcode() == ISD::FP_EXTEND) {
7526           SDValue N120 = N12.getOperand(0);
7527           if (N120.getOpcode() == ISD::FMUL)
7528             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7529                                         N120.getOperand(0), N120.getOperand(1),
7530                                         N0);
7531         }
7532       }
7533
7534       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7535       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7536       // FIXME: This turns two single-precision and one double-precision
7537       // operation into two double-precision operations, which might not be
7538       // interesting for all targets, especially GPUs.
7539       if (N1.getOpcode() == ISD::FP_EXTEND) {
7540         SDValue N10 = N1.getOperand(0);
7541         if (N10.getOpcode() == PreferredFusedOpcode) {
7542           SDValue N102 = N10.getOperand(2);
7543           if (N102.getOpcode() == ISD::FMUL)
7544             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7545                                         N102.getOperand(0), N102.getOperand(1),
7546                                         N0);
7547         }
7548       }
7549     }
7550   }
7551
7552   return SDValue();
7553 }
7554
7555 /// Try to perform FMA combining on a given FSUB node.
7556 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7557   SDValue N0 = N->getOperand(0);
7558   SDValue N1 = N->getOperand(1);
7559   EVT VT = N->getValueType(0);
7560   SDLoc SL(N);
7561
7562   const TargetOptions &Options = DAG.getTarget().Options;
7563   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7564                        Options.UnsafeFPMath);
7565
7566   // Floating-point multiply-add with intermediate rounding.
7567   bool HasFMAD = (LegalOperations &&
7568                   TLI.isOperationLegal(ISD::FMAD, VT));
7569
7570   // Floating-point multiply-add without intermediate rounding.
7571   bool HasFMA = ((!LegalOperations ||
7572                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7573                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7574                  UnsafeFPMath);
7575
7576   // No valid opcode, do not combine.
7577   if (!HasFMAD && !HasFMA)
7578     return SDValue();
7579
7580   // Always prefer FMAD to FMA for precision.
7581   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7582   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7583   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7584
7585   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7586   if (N0.getOpcode() == ISD::FMUL &&
7587       (Aggressive || N0->hasOneUse())) {
7588     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7589                        N0.getOperand(0), N0.getOperand(1),
7590                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7591   }
7592
7593   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7594   // Note: Commutes FSUB operands.
7595   if (N1.getOpcode() == ISD::FMUL &&
7596       (Aggressive || N1->hasOneUse()))
7597     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7598                        DAG.getNode(ISD::FNEG, SL, VT,
7599                                    N1.getOperand(0)),
7600                        N1.getOperand(1), N0);
7601
7602   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7603   if (N0.getOpcode() == ISD::FNEG &&
7604       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7605       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7606     SDValue N00 = N0.getOperand(0).getOperand(0);
7607     SDValue N01 = N0.getOperand(0).getOperand(1);
7608     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7609                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7610                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7611   }
7612
7613   // Look through FP_EXTEND nodes to do more combining.
7614   if (UnsafeFPMath && LookThroughFPExt) {
7615     // fold (fsub (fpext (fmul x, y)), z)
7616     //   -> (fma (fpext x), (fpext y), (fneg z))
7617     if (N0.getOpcode() == ISD::FP_EXTEND) {
7618       SDValue N00 = N0.getOperand(0);
7619       if (N00.getOpcode() == ISD::FMUL)
7620         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7621                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7622                                        N00.getOperand(0)),
7623                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7624                                        N00.getOperand(1)),
7625                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7626     }
7627
7628     // fold (fsub x, (fpext (fmul y, z)))
7629     //   -> (fma (fneg (fpext y)), (fpext z), x)
7630     // Note: Commutes FSUB operands.
7631     if (N1.getOpcode() == ISD::FP_EXTEND) {
7632       SDValue N10 = N1.getOperand(0);
7633       if (N10.getOpcode() == ISD::FMUL)
7634         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7635                            DAG.getNode(ISD::FNEG, SL, VT,
7636                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7637                                                    N10.getOperand(0))),
7638                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7639                                        N10.getOperand(1)),
7640                            N0);
7641     }
7642
7643     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7644     //   -> (fneg (fma (fpext x), (fpext y), z))
7645     // Note: This could be removed with appropriate canonicalization of the
7646     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7647     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7648     // from implementing the canonicalization in visitFSUB.
7649     if (N0.getOpcode() == ISD::FP_EXTEND) {
7650       SDValue N00 = N0.getOperand(0);
7651       if (N00.getOpcode() == ISD::FNEG) {
7652         SDValue N000 = N00.getOperand(0);
7653         if (N000.getOpcode() == ISD::FMUL) {
7654           return DAG.getNode(ISD::FNEG, SL, VT,
7655                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7656                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7657                                                      N000.getOperand(0)),
7658                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7659                                                      N000.getOperand(1)),
7660                                          N1));
7661         }
7662       }
7663     }
7664
7665     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7666     //   -> (fneg (fma (fpext x)), (fpext y), z)
7667     // Note: This could be removed with appropriate canonicalization of the
7668     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7669     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7670     // from implementing the canonicalization in visitFSUB.
7671     if (N0.getOpcode() == ISD::FNEG) {
7672       SDValue N00 = N0.getOperand(0);
7673       if (N00.getOpcode() == ISD::FP_EXTEND) {
7674         SDValue N000 = N00.getOperand(0);
7675         if (N000.getOpcode() == ISD::FMUL) {
7676           return DAG.getNode(ISD::FNEG, SL, VT,
7677                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7678                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7679                                                      N000.getOperand(0)),
7680                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7681                                                      N000.getOperand(1)),
7682                                          N1));
7683         }
7684       }
7685     }
7686
7687   }
7688
7689   // More folding opportunities when target permits.
7690   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7691     // fold (fsub (fma x, y, (fmul u, v)), z)
7692     //   -> (fma x, y (fma u, v, (fneg z)))
7693     if (N0.getOpcode() == PreferredFusedOpcode &&
7694         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7695       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7696                          N0.getOperand(0), N0.getOperand(1),
7697                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7698                                      N0.getOperand(2).getOperand(0),
7699                                      N0.getOperand(2).getOperand(1),
7700                                      DAG.getNode(ISD::FNEG, SL, VT,
7701                                                  N1)));
7702     }
7703
7704     // fold (fsub x, (fma y, z, (fmul u, v)))
7705     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7706     if (N1.getOpcode() == PreferredFusedOpcode &&
7707         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7708       SDValue N20 = N1.getOperand(2).getOperand(0);
7709       SDValue N21 = N1.getOperand(2).getOperand(1);
7710       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7711                          DAG.getNode(ISD::FNEG, SL, VT,
7712                                      N1.getOperand(0)),
7713                          N1.getOperand(1),
7714                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7715                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7716
7717                                      N21, N0));
7718     }
7719
7720     if (UnsafeFPMath && LookThroughFPExt) {
7721       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7722       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7723       if (N0.getOpcode() == PreferredFusedOpcode) {
7724         SDValue N02 = N0.getOperand(2);
7725         if (N02.getOpcode() == ISD::FP_EXTEND) {
7726           SDValue N020 = N02.getOperand(0);
7727           if (N020.getOpcode() == ISD::FMUL)
7728             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7729                                N0.getOperand(0), N0.getOperand(1),
7730                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7731                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7732                                                        N020.getOperand(0)),
7733                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7734                                                        N020.getOperand(1)),
7735                                            DAG.getNode(ISD::FNEG, SL, VT,
7736                                                        N1)));
7737         }
7738       }
7739
7740       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7741       //   -> (fma (fpext x), (fpext y),
7742       //           (fma (fpext u), (fpext v), (fneg z)))
7743       // FIXME: This turns two single-precision and one double-precision
7744       // operation into two double-precision operations, which might not be
7745       // interesting for all targets, especially GPUs.
7746       if (N0.getOpcode() == ISD::FP_EXTEND) {
7747         SDValue N00 = N0.getOperand(0);
7748         if (N00.getOpcode() == PreferredFusedOpcode) {
7749           SDValue N002 = N00.getOperand(2);
7750           if (N002.getOpcode() == ISD::FMUL)
7751             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7752                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7753                                            N00.getOperand(0)),
7754                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7755                                            N00.getOperand(1)),
7756                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7757                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7758                                                        N002.getOperand(0)),
7759                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7760                                                        N002.getOperand(1)),
7761                                            DAG.getNode(ISD::FNEG, SL, VT,
7762                                                        N1)));
7763         }
7764       }
7765
7766       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7767       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7768       if (N1.getOpcode() == PreferredFusedOpcode &&
7769         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7770         SDValue N120 = N1.getOperand(2).getOperand(0);
7771         if (N120.getOpcode() == ISD::FMUL) {
7772           SDValue N1200 = N120.getOperand(0);
7773           SDValue N1201 = N120.getOperand(1);
7774           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7775                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7776                              N1.getOperand(1),
7777                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7778                                          DAG.getNode(ISD::FNEG, SL, VT,
7779                                              DAG.getNode(ISD::FP_EXTEND, SL,
7780                                                          VT, N1200)),
7781                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782                                                      N1201),
7783                                          N0));
7784         }
7785       }
7786
7787       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7788       //   -> (fma (fneg (fpext y)), (fpext z),
7789       //           (fma (fneg (fpext u)), (fpext v), x))
7790       // FIXME: This turns two single-precision and one double-precision
7791       // operation into two double-precision operations, which might not be
7792       // interesting for all targets, especially GPUs.
7793       if (N1.getOpcode() == ISD::FP_EXTEND &&
7794         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7795         SDValue N100 = N1.getOperand(0).getOperand(0);
7796         SDValue N101 = N1.getOperand(0).getOperand(1);
7797         SDValue N102 = N1.getOperand(0).getOperand(2);
7798         if (N102.getOpcode() == ISD::FMUL) {
7799           SDValue N1020 = N102.getOperand(0);
7800           SDValue N1021 = N102.getOperand(1);
7801           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                              DAG.getNode(ISD::FNEG, SL, VT,
7803                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7804                                                      N100)),
7805                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7806                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7807                                          DAG.getNode(ISD::FNEG, SL, VT,
7808                                              DAG.getNode(ISD::FP_EXTEND, SL,
7809                                                          VT, N1020)),
7810                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7811                                                      N1021),
7812                                          N0));
7813         }
7814       }
7815     }
7816   }
7817
7818   return SDValue();
7819 }
7820
7821 SDValue DAGCombiner::visitFADD(SDNode *N) {
7822   SDValue N0 = N->getOperand(0);
7823   SDValue N1 = N->getOperand(1);
7824   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7825   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7826   EVT VT = N->getValueType(0);
7827   SDLoc DL(N);
7828   const TargetOptions &Options = DAG.getTarget().Options;
7829
7830   // fold vector ops
7831   if (VT.isVector())
7832     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7833       return FoldedVOp;
7834
7835   // fold (fadd c1, c2) -> c1 + c2
7836   if (N0CFP && N1CFP)
7837     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7838
7839   // canonicalize constant to RHS
7840   if (N0CFP && !N1CFP)
7841     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7842
7843   // fold (fadd A, (fneg B)) -> (fsub A, B)
7844   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7845       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7846     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7847                        GetNegatedExpression(N1, DAG, LegalOperations));
7848
7849   // fold (fadd (fneg A), B) -> (fsub B, A)
7850   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7851       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7852     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7853                        GetNegatedExpression(N0, DAG, LegalOperations));
7854
7855   // If 'unsafe math' is enabled, fold lots of things.
7856   if (Options.UnsafeFPMath) {
7857     // No FP constant should be created after legalization as Instruction
7858     // Selection pass has a hard time dealing with FP constants.
7859     bool AllowNewConst = (Level < AfterLegalizeDAG);
7860
7861     // fold (fadd A, 0) -> A
7862     if (N1CFP && N1CFP->getValueAPF().isZero())
7863       return N0;
7864
7865     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7866     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7867         isa<ConstantFPSDNode>(N0.getOperand(1)))
7868       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7869                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7870
7871     // If allowed, fold (fadd (fneg x), x) -> 0.0
7872     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7873       return DAG.getConstantFP(0.0, DL, VT);
7874
7875     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7876     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7877       return DAG.getConstantFP(0.0, DL, VT);
7878
7879     // We can fold chains of FADD's of the same value into multiplications.
7880     // This transform is not safe in general because we are reducing the number
7881     // of rounding steps.
7882     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7883       if (N0.getOpcode() == ISD::FMUL) {
7884         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7885         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7886
7887         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7888         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7889           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7890                                        DAG.getConstantFP(1.0, DL, VT));
7891           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7892         }
7893
7894         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7895         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7896             N1.getOperand(0) == N1.getOperand(1) &&
7897             N0.getOperand(0) == N1.getOperand(0)) {
7898           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7899                                        DAG.getConstantFP(2.0, DL, VT));
7900           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7901         }
7902       }
7903
7904       if (N1.getOpcode() == ISD::FMUL) {
7905         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7906         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7907
7908         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7909         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7910           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7911                                        DAG.getConstantFP(1.0, DL, VT));
7912           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7913         }
7914
7915         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7916         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7917             N0.getOperand(0) == N0.getOperand(1) &&
7918             N1.getOperand(0) == N0.getOperand(0)) {
7919           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7920                                        DAG.getConstantFP(2.0, DL, VT));
7921           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7922         }
7923       }
7924
7925       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7926         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7927         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7928         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7929             (N0.getOperand(0) == N1)) {
7930           return DAG.getNode(ISD::FMUL, DL, VT,
7931                              N1, DAG.getConstantFP(3.0, DL, VT));
7932         }
7933       }
7934
7935       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7936         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7937         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7938         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7939             N1.getOperand(0) == N0) {
7940           return DAG.getNode(ISD::FMUL, DL, VT,
7941                              N0, DAG.getConstantFP(3.0, DL, VT));
7942         }
7943       }
7944
7945       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7946       if (AllowNewConst &&
7947           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7948           N0.getOperand(0) == N0.getOperand(1) &&
7949           N1.getOperand(0) == N1.getOperand(1) &&
7950           N0.getOperand(0) == N1.getOperand(0)) {
7951         return DAG.getNode(ISD::FMUL, DL, VT,
7952                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7953       }
7954     }
7955   } // enable-unsafe-fp-math
7956
7957   // FADD -> FMA combines:
7958   SDValue Fused = visitFADDForFMACombine(N);
7959   if (Fused) {
7960     AddToWorklist(Fused.getNode());
7961     return Fused;
7962   }
7963
7964   return SDValue();
7965 }
7966
7967 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7968   SDValue N0 = N->getOperand(0);
7969   SDValue N1 = N->getOperand(1);
7970   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7971   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7972   EVT VT = N->getValueType(0);
7973   SDLoc dl(N);
7974   const TargetOptions &Options = DAG.getTarget().Options;
7975
7976   // fold vector ops
7977   if (VT.isVector())
7978     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7979       return FoldedVOp;
7980
7981   // fold (fsub c1, c2) -> c1-c2
7982   if (N0CFP && N1CFP)
7983     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7984
7985   // fold (fsub A, (fneg B)) -> (fadd A, B)
7986   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7987     return DAG.getNode(ISD::FADD, dl, VT, N0,
7988                        GetNegatedExpression(N1, DAG, LegalOperations));
7989
7990   // If 'unsafe math' is enabled, fold lots of things.
7991   if (Options.UnsafeFPMath) {
7992     // (fsub A, 0) -> A
7993     if (N1CFP && N1CFP->getValueAPF().isZero())
7994       return N0;
7995
7996     // (fsub 0, B) -> -B
7997     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7998       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7999         return GetNegatedExpression(N1, DAG, LegalOperations);
8000       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8001         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8002     }
8003
8004     // (fsub x, x) -> 0.0
8005     if (N0 == N1)
8006       return DAG.getConstantFP(0.0f, dl, VT);
8007
8008     // (fsub x, (fadd x, y)) -> (fneg y)
8009     // (fsub x, (fadd y, x)) -> (fneg y)
8010     if (N1.getOpcode() == ISD::FADD) {
8011       SDValue N10 = N1->getOperand(0);
8012       SDValue N11 = N1->getOperand(1);
8013
8014       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8015         return GetNegatedExpression(N11, DAG, LegalOperations);
8016
8017       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8018         return GetNegatedExpression(N10, DAG, LegalOperations);
8019     }
8020   }
8021
8022   // FSUB -> FMA combines:
8023   SDValue Fused = visitFSUBForFMACombine(N);
8024   if (Fused) {
8025     AddToWorklist(Fused.getNode());
8026     return Fused;
8027   }
8028
8029   return SDValue();
8030 }
8031
8032 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8033   SDValue N0 = N->getOperand(0);
8034   SDValue N1 = N->getOperand(1);
8035   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8036   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8037   EVT VT = N->getValueType(0);
8038   SDLoc DL(N);
8039   const TargetOptions &Options = DAG.getTarget().Options;
8040
8041   // fold vector ops
8042   if (VT.isVector()) {
8043     // This just handles C1 * C2 for vectors. Other vector folds are below.
8044     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8045       return FoldedVOp;
8046   }
8047
8048   // fold (fmul c1, c2) -> c1*c2
8049   if (N0CFP && N1CFP)
8050     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8051
8052   // canonicalize constant to RHS
8053   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8054      !isConstantFPBuildVectorOrConstantFP(N1))
8055     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8056
8057   // fold (fmul A, 1.0) -> A
8058   if (N1CFP && N1CFP->isExactlyValue(1.0))
8059     return N0;
8060
8061   if (Options.UnsafeFPMath) {
8062     // fold (fmul A, 0) -> 0
8063     if (N1CFP && N1CFP->getValueAPF().isZero())
8064       return N1;
8065
8066     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8067     if (N0.getOpcode() == ISD::FMUL) {
8068       // Fold scalars or any vector constants (not just splats).
8069       // This fold is done in general by InstCombine, but extra fmul insts
8070       // may have been generated during lowering.
8071       SDValue N00 = N0.getOperand(0);
8072       SDValue N01 = N0.getOperand(1);
8073       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8074       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8075       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8076       
8077       // Check 1: Make sure that the first operand of the inner multiply is NOT
8078       // a constant. Otherwise, we may induce infinite looping.
8079       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8080         // Check 2: Make sure that the second operand of the inner multiply and
8081         // the second operand of the outer multiply are constants.
8082         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8083             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8084           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8085           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8086         }
8087       }
8088     }
8089
8090     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8091     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8092     // during an early run of DAGCombiner can prevent folding with fmuls
8093     // inserted during lowering.
8094     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8095       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8096       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8097       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8098     }
8099   }
8100
8101   // fold (fmul X, 2.0) -> (fadd X, X)
8102   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8103     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8104
8105   // fold (fmul X, -1.0) -> (fneg X)
8106   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8107     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8108       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8109
8110   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8111   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8112     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8113       // Both can be negated for free, check to see if at least one is cheaper
8114       // negated.
8115       if (LHSNeg == 2 || RHSNeg == 2)
8116         return DAG.getNode(ISD::FMUL, DL, VT,
8117                            GetNegatedExpression(N0, DAG, LegalOperations),
8118                            GetNegatedExpression(N1, DAG, LegalOperations));
8119     }
8120   }
8121
8122   return SDValue();
8123 }
8124
8125 SDValue DAGCombiner::visitFMA(SDNode *N) {
8126   SDValue N0 = N->getOperand(0);
8127   SDValue N1 = N->getOperand(1);
8128   SDValue N2 = N->getOperand(2);
8129   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8130   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8131   EVT VT = N->getValueType(0);
8132   SDLoc dl(N);
8133   const TargetOptions &Options = DAG.getTarget().Options;
8134
8135   // Constant fold FMA.
8136   if (isa<ConstantFPSDNode>(N0) &&
8137       isa<ConstantFPSDNode>(N1) &&
8138       isa<ConstantFPSDNode>(N2)) {
8139     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8140   }
8141
8142   if (Options.UnsafeFPMath) {
8143     if (N0CFP && N0CFP->isZero())
8144       return N2;
8145     if (N1CFP && N1CFP->isZero())
8146       return N2;
8147   }
8148   if (N0CFP && N0CFP->isExactlyValue(1.0))
8149     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8150   if (N1CFP && N1CFP->isExactlyValue(1.0))
8151     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8152
8153   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8154   if (N0CFP && !N1CFP)
8155     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8156
8157   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8158   if (Options.UnsafeFPMath && N1CFP &&
8159       N2.getOpcode() == ISD::FMUL &&
8160       N0 == N2.getOperand(0) &&
8161       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8162     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8163                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8164   }
8165
8166
8167   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8168   if (Options.UnsafeFPMath &&
8169       N0.getOpcode() == ISD::FMUL && N1CFP &&
8170       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8171     return DAG.getNode(ISD::FMA, dl, VT,
8172                        N0.getOperand(0),
8173                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8174                        N2);
8175   }
8176
8177   // (fma x, 1, y) -> (fadd x, y)
8178   // (fma x, -1, y) -> (fadd (fneg x), y)
8179   if (N1CFP) {
8180     if (N1CFP->isExactlyValue(1.0))
8181       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8182
8183     if (N1CFP->isExactlyValue(-1.0) &&
8184         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8185       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8186       AddToWorklist(RHSNeg.getNode());
8187       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8188     }
8189   }
8190
8191   // (fma x, c, x) -> (fmul x, (c+1))
8192   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8193     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8194                        DAG.getNode(ISD::FADD, dl, VT,
8195                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8196
8197   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8198   if (Options.UnsafeFPMath && N1CFP &&
8199       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8200     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8201                        DAG.getNode(ISD::FADD, dl, VT,
8202                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8203
8204
8205   return SDValue();
8206 }
8207
8208 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8209   SDValue N0 = N->getOperand(0);
8210   SDValue N1 = N->getOperand(1);
8211   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8212   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8213   EVT VT = N->getValueType(0);
8214   SDLoc DL(N);
8215   const TargetOptions &Options = DAG.getTarget().Options;
8216
8217   // fold vector ops
8218   if (VT.isVector())
8219     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8220       return FoldedVOp;
8221
8222   // fold (fdiv c1, c2) -> c1/c2
8223   if (N0CFP && N1CFP)
8224     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8225
8226   if (Options.UnsafeFPMath) {
8227     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8228     if (N1CFP) {
8229       // Compute the reciprocal 1.0 / c2.
8230       APFloat N1APF = N1CFP->getValueAPF();
8231       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8232       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8233       // Only do the transform if the reciprocal is a legal fp immediate that
8234       // isn't too nasty (eg NaN, denormal, ...).
8235       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8236           (!LegalOperations ||
8237            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8238            // backend)... we should handle this gracefully after Legalize.
8239            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8240            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8241            TLI.isFPImmLegal(Recip, VT)))
8242         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8243                            DAG.getConstantFP(Recip, DL, VT));
8244     }
8245
8246     // If this FDIV is part of a reciprocal square root, it may be folded
8247     // into a target-specific square root estimate instruction.
8248     if (N1.getOpcode() == ISD::FSQRT) {
8249       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8250         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8251       }
8252     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8253                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8254       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8255         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8256         AddToWorklist(RV.getNode());
8257         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8258       }
8259     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8260                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8261       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8262         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8263         AddToWorklist(RV.getNode());
8264         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8265       }
8266     } else if (N1.getOpcode() == ISD::FMUL) {
8267       // Look through an FMUL. Even though this won't remove the FDIV directly,
8268       // it's still worthwhile to get rid of the FSQRT if possible.
8269       SDValue SqrtOp;
8270       SDValue OtherOp;
8271       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8272         SqrtOp = N1.getOperand(0);
8273         OtherOp = N1.getOperand(1);
8274       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8275         SqrtOp = N1.getOperand(1);
8276         OtherOp = N1.getOperand(0);
8277       }
8278       if (SqrtOp.getNode()) {
8279         // We found a FSQRT, so try to make this fold:
8280         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8281         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8282           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8283           AddToWorklist(RV.getNode());
8284           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8285         }
8286       }
8287     }
8288
8289     // Fold into a reciprocal estimate and multiply instead of a real divide.
8290     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8291       AddToWorklist(RV.getNode());
8292       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8293     }
8294   }
8295
8296   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8297   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8298     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8299       // Both can be negated for free, check to see if at least one is cheaper
8300       // negated.
8301       if (LHSNeg == 2 || RHSNeg == 2)
8302         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8303                            GetNegatedExpression(N0, DAG, LegalOperations),
8304                            GetNegatedExpression(N1, DAG, LegalOperations));
8305     }
8306   }
8307
8308   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8309   // reciprocal.
8310   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8311   // Notice that this is not always beneficial. One reason is different target
8312   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8313   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8314   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8315   if (Options.UnsafeFPMath) {
8316     // Skip if current node is a reciprocal.
8317     if (N0CFP && N0CFP->isExactlyValue(1.0))
8318       return SDValue();
8319
8320     SmallVector<SDNode *, 4> Users;
8321     // Find all FDIV users of the same divisor.
8322     for (auto *U : N1->uses()) {
8323       if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8324         Users.push_back(U);
8325     }
8326
8327     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8328       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8329       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8330
8331       // Dividend / Divisor -> Dividend * Reciprocal
8332       for (auto *U : Users) {
8333         SDValue Dividend = U->getOperand(0);
8334         if (Dividend != FPOne) {
8335           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8336                                         Reciprocal);
8337           DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8338         }
8339       }
8340       return SDValue();
8341     }
8342   }
8343
8344   return SDValue();
8345 }
8346
8347 SDValue DAGCombiner::visitFREM(SDNode *N) {
8348   SDValue N0 = N->getOperand(0);
8349   SDValue N1 = N->getOperand(1);
8350   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8351   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8352   EVT VT = N->getValueType(0);
8353
8354   // fold (frem c1, c2) -> fmod(c1,c2)
8355   if (N0CFP && N1CFP)
8356     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8357
8358   return SDValue();
8359 }
8360
8361 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8362   if (DAG.getTarget().Options.UnsafeFPMath &&
8363       !TLI.isFsqrtCheap()) {
8364     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8365     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8366       EVT VT = RV.getValueType();
8367       SDLoc DL(N);
8368       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8369       AddToWorklist(RV.getNode());
8370
8371       // Unfortunately, RV is now NaN if the input was exactly 0.
8372       // Select out this case and force the answer to 0.
8373       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8374       SDValue ZeroCmp =
8375         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8376                      N->getOperand(0), Zero, ISD::SETEQ);
8377       AddToWorklist(ZeroCmp.getNode());
8378       AddToWorklist(RV.getNode());
8379
8380       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8381                        DL, VT, ZeroCmp, Zero, RV);
8382       return RV;
8383     }
8384   }
8385   return SDValue();
8386 }
8387
8388 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8389   SDValue N0 = N->getOperand(0);
8390   SDValue N1 = N->getOperand(1);
8391   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8392   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8393   EVT VT = N->getValueType(0);
8394
8395   if (N0CFP && N1CFP)  // Constant fold
8396     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8397
8398   if (N1CFP) {
8399     const APFloat& V = N1CFP->getValueAPF();
8400     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8401     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8402     if (!V.isNegative()) {
8403       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8404         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8405     } else {
8406       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8407         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8408                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8409     }
8410   }
8411
8412   // copysign(fabs(x), y) -> copysign(x, y)
8413   // copysign(fneg(x), y) -> copysign(x, y)
8414   // copysign(copysign(x,z), y) -> copysign(x, y)
8415   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8416       N0.getOpcode() == ISD::FCOPYSIGN)
8417     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8418                        N0.getOperand(0), N1);
8419
8420   // copysign(x, abs(y)) -> abs(x)
8421   if (N1.getOpcode() == ISD::FABS)
8422     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8423
8424   // copysign(x, copysign(y,z)) -> copysign(x, z)
8425   if (N1.getOpcode() == ISD::FCOPYSIGN)
8426     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8427                        N0, N1.getOperand(1));
8428
8429   // copysign(x, fp_extend(y)) -> copysign(x, y)
8430   // copysign(x, fp_round(y)) -> copysign(x, y)
8431   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8432     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8433                        N0, N1.getOperand(0));
8434
8435   return SDValue();
8436 }
8437
8438 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8439   SDValue N0 = N->getOperand(0);
8440   EVT VT = N->getValueType(0);
8441   EVT OpVT = N0.getValueType();
8442
8443   // fold (sint_to_fp c1) -> c1fp
8444   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8445       // ...but only if the target supports immediate floating-point values
8446       (!LegalOperations ||
8447        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8448     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8449
8450   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8451   // but UINT_TO_FP is legal on this target, try to convert.
8452   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8453       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8454     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8455     if (DAG.SignBitIsZero(N0))
8456       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8457   }
8458
8459   // The next optimizations are desirable only if SELECT_CC can be lowered.
8460   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8461     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8462     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8463         !VT.isVector() &&
8464         (!LegalOperations ||
8465          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8466       SDLoc DL(N);
8467       SDValue Ops[] =
8468         { N0.getOperand(0), N0.getOperand(1),
8469           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8470           N0.getOperand(2) };
8471       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8472     }
8473
8474     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8475     //      (select_cc x, y, 1.0, 0.0,, cc)
8476     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8477         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8478         (!LegalOperations ||
8479          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8480       SDLoc DL(N);
8481       SDValue Ops[] =
8482         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8483           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8484           N0.getOperand(0).getOperand(2) };
8485       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8486     }
8487   }
8488
8489   return SDValue();
8490 }
8491
8492 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8493   SDValue N0 = N->getOperand(0);
8494   EVT VT = N->getValueType(0);
8495   EVT OpVT = N0.getValueType();
8496
8497   // fold (uint_to_fp c1) -> c1fp
8498   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8499       // ...but only if the target supports immediate floating-point values
8500       (!LegalOperations ||
8501        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8502     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8503
8504   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8505   // but SINT_TO_FP is legal on this target, try to convert.
8506   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8507       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8508     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8509     if (DAG.SignBitIsZero(N0))
8510       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8511   }
8512
8513   // The next optimizations are desirable only if SELECT_CC can be lowered.
8514   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8515     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8516
8517     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8518         (!LegalOperations ||
8519          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8520       SDLoc DL(N);
8521       SDValue Ops[] =
8522         { N0.getOperand(0), N0.getOperand(1),
8523           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8524           N0.getOperand(2) };
8525       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8526     }
8527   }
8528
8529   return SDValue();
8530 }
8531
8532 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8533 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8534   SDValue N0 = N->getOperand(0);
8535   EVT VT = N->getValueType(0);
8536
8537   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8538     return SDValue();
8539
8540   SDValue Src = N0.getOperand(0);
8541   EVT SrcVT = Src.getValueType();
8542   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8543   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8544
8545   // We can safely assume the conversion won't overflow the output range,
8546   // because (for example) (uint8_t)18293.f is undefined behavior.
8547
8548   // Since we can assume the conversion won't overflow, our decision as to
8549   // whether the input will fit in the float should depend on the minimum
8550   // of the input range and output range.
8551
8552   // This means this is also safe for a signed input and unsigned output, since
8553   // a negative input would lead to undefined behavior.
8554   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8555   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8556   unsigned ActualSize = std::min(InputSize, OutputSize);
8557   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8558
8559   // We can only fold away the float conversion if the input range can be
8560   // represented exactly in the float range.
8561   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8562     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8563       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8564                                                        : ISD::ZERO_EXTEND;
8565       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8566     }
8567     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8568       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8569     if (SrcVT == VT)
8570       return Src;
8571     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8572   }
8573   return SDValue();
8574 }
8575
8576 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8577   SDValue N0 = N->getOperand(0);
8578   EVT VT = N->getValueType(0);
8579
8580   // fold (fp_to_sint c1fp) -> c1
8581   if (isConstantFPBuildVectorOrConstantFP(N0))
8582     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8583
8584   return FoldIntToFPToInt(N, DAG);
8585 }
8586
8587 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8588   SDValue N0 = N->getOperand(0);
8589   EVT VT = N->getValueType(0);
8590
8591   // fold (fp_to_uint c1fp) -> c1
8592   if (isConstantFPBuildVectorOrConstantFP(N0))
8593     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8594
8595   return FoldIntToFPToInt(N, DAG);
8596 }
8597
8598 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8599   SDValue N0 = N->getOperand(0);
8600   SDValue N1 = N->getOperand(1);
8601   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8602   EVT VT = N->getValueType(0);
8603
8604   // fold (fp_round c1fp) -> c1fp
8605   if (N0CFP)
8606     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8607
8608   // fold (fp_round (fp_extend x)) -> x
8609   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8610     return N0.getOperand(0);
8611
8612   // fold (fp_round (fp_round x)) -> (fp_round x)
8613   if (N0.getOpcode() == ISD::FP_ROUND) {
8614     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8615     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8616     // If the first fp_round isn't a value preserving truncation, it might
8617     // introduce a tie in the second fp_round, that wouldn't occur in the
8618     // single-step fp_round we want to fold to.
8619     // In other words, double rounding isn't the same as rounding.
8620     // Also, this is a value preserving truncation iff both fp_round's are.
8621     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8622       SDLoc DL(N);
8623       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8624                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8625     }
8626   }
8627
8628   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8629   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8630     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8631                               N0.getOperand(0), N1);
8632     AddToWorklist(Tmp.getNode());
8633     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8634                        Tmp, N0.getOperand(1));
8635   }
8636
8637   return SDValue();
8638 }
8639
8640 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8641   SDValue N0 = N->getOperand(0);
8642   EVT VT = N->getValueType(0);
8643   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8644   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8645
8646   // fold (fp_round_inreg c1fp) -> c1fp
8647   if (N0CFP && isTypeLegal(EVT)) {
8648     SDLoc DL(N);
8649     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8650     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8651   }
8652
8653   return SDValue();
8654 }
8655
8656 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8657   SDValue N0 = N->getOperand(0);
8658   EVT VT = N->getValueType(0);
8659
8660   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8661   if (N->hasOneUse() &&
8662       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8663     return SDValue();
8664
8665   // fold (fp_extend c1fp) -> c1fp
8666   if (isConstantFPBuildVectorOrConstantFP(N0))
8667     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8668
8669   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8670   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8671       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8672     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8673
8674   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8675   // value of X.
8676   if (N0.getOpcode() == ISD::FP_ROUND
8677       && N0.getNode()->getConstantOperandVal(1) == 1) {
8678     SDValue In = N0.getOperand(0);
8679     if (In.getValueType() == VT) return In;
8680     if (VT.bitsLT(In.getValueType()))
8681       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8682                          In, N0.getOperand(1));
8683     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8684   }
8685
8686   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8687   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8688        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8689     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8690     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8691                                      LN0->getChain(),
8692                                      LN0->getBasePtr(), N0.getValueType(),
8693                                      LN0->getMemOperand());
8694     CombineTo(N, ExtLoad);
8695     CombineTo(N0.getNode(),
8696               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8697                           N0.getValueType(), ExtLoad,
8698                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8699               ExtLoad.getValue(1));
8700     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8701   }
8702
8703   return SDValue();
8704 }
8705
8706 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8707   SDValue N0 = N->getOperand(0);
8708   EVT VT = N->getValueType(0);
8709
8710   // fold (fceil c1) -> fceil(c1)
8711   if (isConstantFPBuildVectorOrConstantFP(N0))
8712     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8713
8714   return SDValue();
8715 }
8716
8717 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8718   SDValue N0 = N->getOperand(0);
8719   EVT VT = N->getValueType(0);
8720
8721   // fold (ftrunc c1) -> ftrunc(c1)
8722   if (isConstantFPBuildVectorOrConstantFP(N0))
8723     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8724
8725   return SDValue();
8726 }
8727
8728 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8729   SDValue N0 = N->getOperand(0);
8730   EVT VT = N->getValueType(0);
8731
8732   // fold (ffloor c1) -> ffloor(c1)
8733   if (isConstantFPBuildVectorOrConstantFP(N0))
8734     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8735
8736   return SDValue();
8737 }
8738
8739 // FIXME: FNEG and FABS have a lot in common; refactor.
8740 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8741   SDValue N0 = N->getOperand(0);
8742   EVT VT = N->getValueType(0);
8743
8744   // Constant fold FNEG.
8745   if (isConstantFPBuildVectorOrConstantFP(N0))
8746     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8747
8748   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8749                          &DAG.getTarget().Options))
8750     return GetNegatedExpression(N0, DAG, LegalOperations);
8751
8752   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8753   // constant pool values.
8754   if (!TLI.isFNegFree(VT) &&
8755       N0.getOpcode() == ISD::BITCAST &&
8756       N0.getNode()->hasOneUse()) {
8757     SDValue Int = N0.getOperand(0);
8758     EVT IntVT = Int.getValueType();
8759     if (IntVT.isInteger() && !IntVT.isVector()) {
8760       APInt SignMask;
8761       if (N0.getValueType().isVector()) {
8762         // For a vector, get a mask such as 0x80... per scalar element
8763         // and splat it.
8764         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8765         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8766       } else {
8767         // For a scalar, just generate 0x80...
8768         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8769       }
8770       SDLoc DL0(N0);
8771       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8772                         DAG.getConstant(SignMask, DL0, IntVT));
8773       AddToWorklist(Int.getNode());
8774       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8775     }
8776   }
8777
8778   // (fneg (fmul c, x)) -> (fmul -c, x)
8779   if (N0.getOpcode() == ISD::FMUL) {
8780     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8781     if (CFP1) {
8782       APFloat CVal = CFP1->getValueAPF();
8783       CVal.changeSign();
8784       if (Level >= AfterLegalizeDAG &&
8785           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8786            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8787         return DAG.getNode(
8788             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8789             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8790     }
8791   }
8792
8793   return SDValue();
8794 }
8795
8796 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8797   SDValue N0 = N->getOperand(0);
8798   SDValue N1 = N->getOperand(1);
8799   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8800   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8801
8802   if (N0CFP && N1CFP) {
8803     const APFloat &C0 = N0CFP->getValueAPF();
8804     const APFloat &C1 = N1CFP->getValueAPF();
8805     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8806   }
8807
8808   if (N0CFP) {
8809     EVT VT = N->getValueType(0);
8810     // Canonicalize to constant on RHS.
8811     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8812   }
8813
8814   return SDValue();
8815 }
8816
8817 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8818   SDValue N0 = N->getOperand(0);
8819   SDValue N1 = N->getOperand(1);
8820   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8821   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8822
8823   if (N0CFP && N1CFP) {
8824     const APFloat &C0 = N0CFP->getValueAPF();
8825     const APFloat &C1 = N1CFP->getValueAPF();
8826     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8827   }
8828
8829   if (N0CFP) {
8830     EVT VT = N->getValueType(0);
8831     // Canonicalize to constant on RHS.
8832     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8833   }
8834
8835   return SDValue();
8836 }
8837
8838 SDValue DAGCombiner::visitFABS(SDNode *N) {
8839   SDValue N0 = N->getOperand(0);
8840   EVT VT = N->getValueType(0);
8841
8842   // fold (fabs c1) -> fabs(c1)
8843   if (isConstantFPBuildVectorOrConstantFP(N0))
8844     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8845
8846   // fold (fabs (fabs x)) -> (fabs x)
8847   if (N0.getOpcode() == ISD::FABS)
8848     return N->getOperand(0);
8849
8850   // fold (fabs (fneg x)) -> (fabs x)
8851   // fold (fabs (fcopysign x, y)) -> (fabs x)
8852   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8853     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8854
8855   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8856   // constant pool values.
8857   if (!TLI.isFAbsFree(VT) &&
8858       N0.getOpcode() == ISD::BITCAST &&
8859       N0.getNode()->hasOneUse()) {
8860     SDValue Int = N0.getOperand(0);
8861     EVT IntVT = Int.getValueType();
8862     if (IntVT.isInteger() && !IntVT.isVector()) {
8863       APInt SignMask;
8864       if (N0.getValueType().isVector()) {
8865         // For a vector, get a mask such as 0x7f... per scalar element
8866         // and splat it.
8867         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8868         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8869       } else {
8870         // For a scalar, just generate 0x7f...
8871         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8872       }
8873       SDLoc DL(N0);
8874       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8875                         DAG.getConstant(SignMask, DL, IntVT));
8876       AddToWorklist(Int.getNode());
8877       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8878     }
8879   }
8880
8881   return SDValue();
8882 }
8883
8884 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8885   SDValue Chain = N->getOperand(0);
8886   SDValue N1 = N->getOperand(1);
8887   SDValue N2 = N->getOperand(2);
8888
8889   // If N is a constant we could fold this into a fallthrough or unconditional
8890   // branch. However that doesn't happen very often in normal code, because
8891   // Instcombine/SimplifyCFG should have handled the available opportunities.
8892   // If we did this folding here, it would be necessary to update the
8893   // MachineBasicBlock CFG, which is awkward.
8894
8895   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8896   // on the target.
8897   if (N1.getOpcode() == ISD::SETCC &&
8898       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8899                                    N1.getOperand(0).getValueType())) {
8900     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8901                        Chain, N1.getOperand(2),
8902                        N1.getOperand(0), N1.getOperand(1), N2);
8903   }
8904
8905   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8906       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8907        (N1.getOperand(0).hasOneUse() &&
8908         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8909     SDNode *Trunc = nullptr;
8910     if (N1.getOpcode() == ISD::TRUNCATE) {
8911       // Look pass the truncate.
8912       Trunc = N1.getNode();
8913       N1 = N1.getOperand(0);
8914     }
8915
8916     // Match this pattern so that we can generate simpler code:
8917     //
8918     //   %a = ...
8919     //   %b = and i32 %a, 2
8920     //   %c = srl i32 %b, 1
8921     //   brcond i32 %c ...
8922     //
8923     // into
8924     //
8925     //   %a = ...
8926     //   %b = and i32 %a, 2
8927     //   %c = setcc eq %b, 0
8928     //   brcond %c ...
8929     //
8930     // This applies only when the AND constant value has one bit set and the
8931     // SRL constant is equal to the log2 of the AND constant. The back-end is
8932     // smart enough to convert the result into a TEST/JMP sequence.
8933     SDValue Op0 = N1.getOperand(0);
8934     SDValue Op1 = N1.getOperand(1);
8935
8936     if (Op0.getOpcode() == ISD::AND &&
8937         Op1.getOpcode() == ISD::Constant) {
8938       SDValue AndOp1 = Op0.getOperand(1);
8939
8940       if (AndOp1.getOpcode() == ISD::Constant) {
8941         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8942
8943         if (AndConst.isPowerOf2() &&
8944             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8945           SDLoc DL(N);
8946           SDValue SetCC =
8947             DAG.getSetCC(DL,
8948                          getSetCCResultType(Op0.getValueType()),
8949                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8950                          ISD::SETNE);
8951
8952           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8953                                           MVT::Other, Chain, SetCC, N2);
8954           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8955           // will convert it back to (X & C1) >> C2.
8956           CombineTo(N, NewBRCond, false);
8957           // Truncate is dead.
8958           if (Trunc)
8959             deleteAndRecombine(Trunc);
8960           // Replace the uses of SRL with SETCC
8961           WorklistRemover DeadNodes(*this);
8962           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8963           deleteAndRecombine(N1.getNode());
8964           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8965         }
8966       }
8967     }
8968
8969     if (Trunc)
8970       // Restore N1 if the above transformation doesn't match.
8971       N1 = N->getOperand(1);
8972   }
8973
8974   // Transform br(xor(x, y)) -> br(x != y)
8975   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8976   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8977     SDNode *TheXor = N1.getNode();
8978     SDValue Op0 = TheXor->getOperand(0);
8979     SDValue Op1 = TheXor->getOperand(1);
8980     if (Op0.getOpcode() == Op1.getOpcode()) {
8981       // Avoid missing important xor optimizations.
8982       SDValue Tmp = visitXOR(TheXor);
8983       if (Tmp.getNode()) {
8984         if (Tmp.getNode() != TheXor) {
8985           DEBUG(dbgs() << "\nReplacing.8 ";
8986                 TheXor->dump(&DAG);
8987                 dbgs() << "\nWith: ";
8988                 Tmp.getNode()->dump(&DAG);
8989                 dbgs() << '\n');
8990           WorklistRemover DeadNodes(*this);
8991           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8992           deleteAndRecombine(TheXor);
8993           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8994                              MVT::Other, Chain, Tmp, N2);
8995         }
8996
8997         // visitXOR has changed XOR's operands or replaced the XOR completely,
8998         // bail out.
8999         return SDValue(N, 0);
9000       }
9001     }
9002
9003     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9004       bool Equal = false;
9005       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9006           Op0.getOpcode() == ISD::XOR) {
9007         TheXor = Op0.getNode();
9008         Equal = true;
9009       }
9010
9011       EVT SetCCVT = N1.getValueType();
9012       if (LegalTypes)
9013         SetCCVT = getSetCCResultType(SetCCVT);
9014       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9015                                    SetCCVT,
9016                                    Op0, Op1,
9017                                    Equal ? ISD::SETEQ : ISD::SETNE);
9018       // Replace the uses of XOR with SETCC
9019       WorklistRemover DeadNodes(*this);
9020       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9021       deleteAndRecombine(N1.getNode());
9022       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9023                          MVT::Other, Chain, SetCC, N2);
9024     }
9025   }
9026
9027   return SDValue();
9028 }
9029
9030 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9031 //
9032 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9033   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9034   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9035
9036   // If N is a constant we could fold this into a fallthrough or unconditional
9037   // branch. However that doesn't happen very often in normal code, because
9038   // Instcombine/SimplifyCFG should have handled the available opportunities.
9039   // If we did this folding here, it would be necessary to update the
9040   // MachineBasicBlock CFG, which is awkward.
9041
9042   // Use SimplifySetCC to simplify SETCC's.
9043   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9044                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9045                                false);
9046   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9047
9048   // fold to a simpler setcc
9049   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9050     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9051                        N->getOperand(0), Simp.getOperand(2),
9052                        Simp.getOperand(0), Simp.getOperand(1),
9053                        N->getOperand(4));
9054
9055   return SDValue();
9056 }
9057
9058 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9059 /// and that N may be folded in the load / store addressing mode.
9060 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9061                                     SelectionDAG &DAG,
9062                                     const TargetLowering &TLI) {
9063   EVT VT;
9064   unsigned AS;
9065
9066   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9067     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9068       return false;
9069     VT = LD->getMemoryVT();
9070     AS = LD->getAddressSpace();
9071   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9072     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9073       return false;
9074     VT = ST->getMemoryVT();
9075     AS = ST->getAddressSpace();
9076   } else
9077     return false;
9078
9079   TargetLowering::AddrMode AM;
9080   if (N->getOpcode() == ISD::ADD) {
9081     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9082     if (Offset)
9083       // [reg +/- imm]
9084       AM.BaseOffs = Offset->getSExtValue();
9085     else
9086       // [reg +/- reg]
9087       AM.Scale = 1;
9088   } else if (N->getOpcode() == ISD::SUB) {
9089     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9090     if (Offset)
9091       // [reg +/- imm]
9092       AM.BaseOffs = -Offset->getSExtValue();
9093     else
9094       // [reg +/- reg]
9095       AM.Scale = 1;
9096   } else
9097     return false;
9098
9099   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9100 }
9101
9102 /// Try turning a load/store into a pre-indexed load/store when the base
9103 /// pointer is an add or subtract and it has other uses besides the load/store.
9104 /// After the transformation, the new indexed load/store has effectively folded
9105 /// the add/subtract in and all of its other uses are redirected to the
9106 /// new load/store.
9107 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9108   if (Level < AfterLegalizeDAG)
9109     return false;
9110
9111   bool isLoad = true;
9112   SDValue Ptr;
9113   EVT VT;
9114   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9115     if (LD->isIndexed())
9116       return false;
9117     VT = LD->getMemoryVT();
9118     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9119         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9120       return false;
9121     Ptr = LD->getBasePtr();
9122   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9123     if (ST->isIndexed())
9124       return false;
9125     VT = ST->getMemoryVT();
9126     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9127         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9128       return false;
9129     Ptr = ST->getBasePtr();
9130     isLoad = false;
9131   } else {
9132     return false;
9133   }
9134
9135   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9136   // out.  There is no reason to make this a preinc/predec.
9137   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9138       Ptr.getNode()->hasOneUse())
9139     return false;
9140
9141   // Ask the target to do addressing mode selection.
9142   SDValue BasePtr;
9143   SDValue Offset;
9144   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9145   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9146     return false;
9147
9148   // Backends without true r+i pre-indexed forms may need to pass a
9149   // constant base with a variable offset so that constant coercion
9150   // will work with the patterns in canonical form.
9151   bool Swapped = false;
9152   if (isa<ConstantSDNode>(BasePtr)) {
9153     std::swap(BasePtr, Offset);
9154     Swapped = true;
9155   }
9156
9157   // Don't create a indexed load / store with zero offset.
9158   if (isNullConstant(Offset))
9159     return false;
9160
9161   // Try turning it into a pre-indexed load / store except when:
9162   // 1) The new base ptr is a frame index.
9163   // 2) If N is a store and the new base ptr is either the same as or is a
9164   //    predecessor of the value being stored.
9165   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9166   //    that would create a cycle.
9167   // 4) All uses are load / store ops that use it as old base ptr.
9168
9169   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9170   // (plus the implicit offset) to a register to preinc anyway.
9171   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9172     return false;
9173
9174   // Check #2.
9175   if (!isLoad) {
9176     SDValue Val = cast<StoreSDNode>(N)->getValue();
9177     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9178       return false;
9179   }
9180
9181   // If the offset is a constant, there may be other adds of constants that
9182   // can be folded with this one. We should do this to avoid having to keep
9183   // a copy of the original base pointer.
9184   SmallVector<SDNode *, 16> OtherUses;
9185   if (isa<ConstantSDNode>(Offset))
9186     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9187                               UE = BasePtr.getNode()->use_end();
9188          UI != UE; ++UI) {
9189       SDUse &Use = UI.getUse();
9190       // Skip the use that is Ptr and uses of other results from BasePtr's
9191       // node (important for nodes that return multiple results).
9192       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9193         continue;
9194
9195       if (Use.getUser()->isPredecessorOf(N))
9196         continue;
9197
9198       if (Use.getUser()->getOpcode() != ISD::ADD &&
9199           Use.getUser()->getOpcode() != ISD::SUB) {
9200         OtherUses.clear();
9201         break;
9202       }
9203
9204       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9205       if (!isa<ConstantSDNode>(Op1)) {
9206         OtherUses.clear();
9207         break;
9208       }
9209
9210       // FIXME: In some cases, we can be smarter about this.
9211       if (Op1.getValueType() != Offset.getValueType()) {
9212         OtherUses.clear();
9213         break;
9214       }
9215
9216       OtherUses.push_back(Use.getUser());
9217     }
9218
9219   if (Swapped)
9220     std::swap(BasePtr, Offset);
9221
9222   // Now check for #3 and #4.
9223   bool RealUse = false;
9224
9225   // Caches for hasPredecessorHelper
9226   SmallPtrSet<const SDNode *, 32> Visited;
9227   SmallVector<const SDNode *, 16> Worklist;
9228
9229   for (SDNode *Use : Ptr.getNode()->uses()) {
9230     if (Use == N)
9231       continue;
9232     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9233       return false;
9234
9235     // If Ptr may be folded in addressing mode of other use, then it's
9236     // not profitable to do this transformation.
9237     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9238       RealUse = true;
9239   }
9240
9241   if (!RealUse)
9242     return false;
9243
9244   SDValue Result;
9245   if (isLoad)
9246     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9247                                 BasePtr, Offset, AM);
9248   else
9249     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9250                                  BasePtr, Offset, AM);
9251   ++PreIndexedNodes;
9252   ++NodesCombined;
9253   DEBUG(dbgs() << "\nReplacing.4 ";
9254         N->dump(&DAG);
9255         dbgs() << "\nWith: ";
9256         Result.getNode()->dump(&DAG);
9257         dbgs() << '\n');
9258   WorklistRemover DeadNodes(*this);
9259   if (isLoad) {
9260     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9261     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9262   } else {
9263     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9264   }
9265
9266   // Finally, since the node is now dead, remove it from the graph.
9267   deleteAndRecombine(N);
9268
9269   if (Swapped)
9270     std::swap(BasePtr, Offset);
9271
9272   // Replace other uses of BasePtr that can be updated to use Ptr
9273   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9274     unsigned OffsetIdx = 1;
9275     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9276       OffsetIdx = 0;
9277     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9278            BasePtr.getNode() && "Expected BasePtr operand");
9279
9280     // We need to replace ptr0 in the following expression:
9281     //   x0 * offset0 + y0 * ptr0 = t0
9282     // knowing that
9283     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9284     //
9285     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9286     // indexed load/store and the expresion that needs to be re-written.
9287     //
9288     // Therefore, we have:
9289     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9290
9291     ConstantSDNode *CN =
9292       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9293     int X0, X1, Y0, Y1;
9294     APInt Offset0 = CN->getAPIntValue();
9295     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9296
9297     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9298     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9299     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9300     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9301
9302     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9303
9304     APInt CNV = Offset0;
9305     if (X0 < 0) CNV = -CNV;
9306     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9307     else CNV = CNV - Offset1;
9308
9309     SDLoc DL(OtherUses[i]);
9310
9311     // We can now generate the new expression.
9312     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9313     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9314
9315     SDValue NewUse = DAG.getNode(Opcode,
9316                                  DL,
9317                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9318     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9319     deleteAndRecombine(OtherUses[i]);
9320   }
9321
9322   // Replace the uses of Ptr with uses of the updated base value.
9323   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9324   deleteAndRecombine(Ptr.getNode());
9325
9326   return true;
9327 }
9328
9329 /// Try to combine a load/store with a add/sub of the base pointer node into a
9330 /// post-indexed load/store. The transformation folded the add/subtract into the
9331 /// new indexed load/store effectively and all of its uses are redirected to the
9332 /// new load/store.
9333 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9334   if (Level < AfterLegalizeDAG)
9335     return false;
9336
9337   bool isLoad = true;
9338   SDValue Ptr;
9339   EVT VT;
9340   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9341     if (LD->isIndexed())
9342       return false;
9343     VT = LD->getMemoryVT();
9344     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9345         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9346       return false;
9347     Ptr = LD->getBasePtr();
9348   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9349     if (ST->isIndexed())
9350       return false;
9351     VT = ST->getMemoryVT();
9352     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9353         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9354       return false;
9355     Ptr = ST->getBasePtr();
9356     isLoad = false;
9357   } else {
9358     return false;
9359   }
9360
9361   if (Ptr.getNode()->hasOneUse())
9362     return false;
9363
9364   for (SDNode *Op : Ptr.getNode()->uses()) {
9365     if (Op == N ||
9366         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9367       continue;
9368
9369     SDValue BasePtr;
9370     SDValue Offset;
9371     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9372     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9373       // Don't create a indexed load / store with zero offset.
9374       if (isNullConstant(Offset))
9375         continue;
9376
9377       // Try turning it into a post-indexed load / store except when
9378       // 1) All uses are load / store ops that use it as base ptr (and
9379       //    it may be folded as addressing mmode).
9380       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9381       //    nor a successor of N. Otherwise, if Op is folded that would
9382       //    create a cycle.
9383
9384       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9385         continue;
9386
9387       // Check for #1.
9388       bool TryNext = false;
9389       for (SDNode *Use : BasePtr.getNode()->uses()) {
9390         if (Use == Ptr.getNode())
9391           continue;
9392
9393         // If all the uses are load / store addresses, then don't do the
9394         // transformation.
9395         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9396           bool RealUse = false;
9397           for (SDNode *UseUse : Use->uses()) {
9398             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9399               RealUse = true;
9400           }
9401
9402           if (!RealUse) {
9403             TryNext = true;
9404             break;
9405           }
9406         }
9407       }
9408
9409       if (TryNext)
9410         continue;
9411
9412       // Check for #2
9413       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9414         SDValue Result = isLoad
9415           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9416                                BasePtr, Offset, AM)
9417           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9418                                 BasePtr, Offset, AM);
9419         ++PostIndexedNodes;
9420         ++NodesCombined;
9421         DEBUG(dbgs() << "\nReplacing.5 ";
9422               N->dump(&DAG);
9423               dbgs() << "\nWith: ";
9424               Result.getNode()->dump(&DAG);
9425               dbgs() << '\n');
9426         WorklistRemover DeadNodes(*this);
9427         if (isLoad) {
9428           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9429           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9430         } else {
9431           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9432         }
9433
9434         // Finally, since the node is now dead, remove it from the graph.
9435         deleteAndRecombine(N);
9436
9437         // Replace the uses of Use with uses of the updated base value.
9438         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9439                                       Result.getValue(isLoad ? 1 : 0));
9440         deleteAndRecombine(Op);
9441         return true;
9442       }
9443     }
9444   }
9445
9446   return false;
9447 }
9448
9449 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9450 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9451   ISD::MemIndexedMode AM = LD->getAddressingMode();
9452   assert(AM != ISD::UNINDEXED);
9453   SDValue BP = LD->getOperand(1);
9454   SDValue Inc = LD->getOperand(2);
9455
9456   // Some backends use TargetConstants for load offsets, but don't expect
9457   // TargetConstants in general ADD nodes. We can convert these constants into
9458   // regular Constants (if the constant is not opaque).
9459   assert((Inc.getOpcode() != ISD::TargetConstant ||
9460           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9461          "Cannot split out indexing using opaque target constants");
9462   if (Inc.getOpcode() == ISD::TargetConstant) {
9463     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9464     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9465                           ConstInc->getValueType(0));
9466   }
9467
9468   unsigned Opc =
9469       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9470   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9471 }
9472
9473 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9474   LoadSDNode *LD  = cast<LoadSDNode>(N);
9475   SDValue Chain = LD->getChain();
9476   SDValue Ptr   = LD->getBasePtr();
9477
9478   // If load is not volatile and there are no uses of the loaded value (and
9479   // the updated indexed value in case of indexed loads), change uses of the
9480   // chain value into uses of the chain input (i.e. delete the dead load).
9481   if (!LD->isVolatile()) {
9482     if (N->getValueType(1) == MVT::Other) {
9483       // Unindexed loads.
9484       if (!N->hasAnyUseOfValue(0)) {
9485         // It's not safe to use the two value CombineTo variant here. e.g.
9486         // v1, chain2 = load chain1, loc
9487         // v2, chain3 = load chain2, loc
9488         // v3         = add v2, c
9489         // Now we replace use of chain2 with chain1.  This makes the second load
9490         // isomorphic to the one we are deleting, and thus makes this load live.
9491         DEBUG(dbgs() << "\nReplacing.6 ";
9492               N->dump(&DAG);
9493               dbgs() << "\nWith chain: ";
9494               Chain.getNode()->dump(&DAG);
9495               dbgs() << "\n");
9496         WorklistRemover DeadNodes(*this);
9497         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9498
9499         if (N->use_empty())
9500           deleteAndRecombine(N);
9501
9502         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9503       }
9504     } else {
9505       // Indexed loads.
9506       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9507
9508       // If this load has an opaque TargetConstant offset, then we cannot split
9509       // the indexing into an add/sub directly (that TargetConstant may not be
9510       // valid for a different type of node, and we cannot convert an opaque
9511       // target constant into a regular constant).
9512       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9513                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9514
9515       if (!N->hasAnyUseOfValue(0) &&
9516           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9517         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9518         SDValue Index;
9519         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9520           Index = SplitIndexingFromLoad(LD);
9521           // Try to fold the base pointer arithmetic into subsequent loads and
9522           // stores.
9523           AddUsersToWorklist(N);
9524         } else
9525           Index = DAG.getUNDEF(N->getValueType(1));
9526         DEBUG(dbgs() << "\nReplacing.7 ";
9527               N->dump(&DAG);
9528               dbgs() << "\nWith: ";
9529               Undef.getNode()->dump(&DAG);
9530               dbgs() << " and 2 other values\n");
9531         WorklistRemover DeadNodes(*this);
9532         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9533         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9534         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9535         deleteAndRecombine(N);
9536         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9537       }
9538     }
9539   }
9540
9541   // If this load is directly stored, replace the load value with the stored
9542   // value.
9543   // TODO: Handle store large -> read small portion.
9544   // TODO: Handle TRUNCSTORE/LOADEXT
9545   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9546     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9547       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9548       if (PrevST->getBasePtr() == Ptr &&
9549           PrevST->getValue().getValueType() == N->getValueType(0))
9550       return CombineTo(N, Chain.getOperand(1), Chain);
9551     }
9552   }
9553
9554   // Try to infer better alignment information than the load already has.
9555   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9556     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9557       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9558         SDValue NewLoad =
9559                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9560                               LD->getValueType(0),
9561                               Chain, Ptr, LD->getPointerInfo(),
9562                               LD->getMemoryVT(),
9563                               LD->isVolatile(), LD->isNonTemporal(),
9564                               LD->isInvariant(), Align, LD->getAAInfo());
9565         if (NewLoad.getNode() != N)
9566           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9567       }
9568     }
9569   }
9570
9571   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9572                                                   : DAG.getSubtarget().useAA();
9573 #ifndef NDEBUG
9574   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9575       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9576     UseAA = false;
9577 #endif
9578   if (UseAA && LD->isUnindexed()) {
9579     // Walk up chain skipping non-aliasing memory nodes.
9580     SDValue BetterChain = FindBetterChain(N, Chain);
9581
9582     // If there is a better chain.
9583     if (Chain != BetterChain) {
9584       SDValue ReplLoad;
9585
9586       // Replace the chain to void dependency.
9587       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9588         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9589                                BetterChain, Ptr, LD->getMemOperand());
9590       } else {
9591         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9592                                   LD->getValueType(0),
9593                                   BetterChain, Ptr, LD->getMemoryVT(),
9594                                   LD->getMemOperand());
9595       }
9596
9597       // Create token factor to keep old chain connected.
9598       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9599                                   MVT::Other, Chain, ReplLoad.getValue(1));
9600
9601       // Make sure the new and old chains are cleaned up.
9602       AddToWorklist(Token.getNode());
9603
9604       // Replace uses with load result and token factor. Don't add users
9605       // to work list.
9606       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9607     }
9608   }
9609
9610   // Try transforming N to an indexed load.
9611   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9612     return SDValue(N, 0);
9613
9614   // Try to slice up N to more direct loads if the slices are mapped to
9615   // different register banks or pairing can take place.
9616   if (SliceUpLoad(N))
9617     return SDValue(N, 0);
9618
9619   return SDValue();
9620 }
9621
9622 namespace {
9623 /// \brief Helper structure used to slice a load in smaller loads.
9624 /// Basically a slice is obtained from the following sequence:
9625 /// Origin = load Ty1, Base
9626 /// Shift = srl Ty1 Origin, CstTy Amount
9627 /// Inst = trunc Shift to Ty2
9628 ///
9629 /// Then, it will be rewriten into:
9630 /// Slice = load SliceTy, Base + SliceOffset
9631 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9632 ///
9633 /// SliceTy is deduced from the number of bits that are actually used to
9634 /// build Inst.
9635 struct LoadedSlice {
9636   /// \brief Helper structure used to compute the cost of a slice.
9637   struct Cost {
9638     /// Are we optimizing for code size.
9639     bool ForCodeSize;
9640     /// Various cost.
9641     unsigned Loads;
9642     unsigned Truncates;
9643     unsigned CrossRegisterBanksCopies;
9644     unsigned ZExts;
9645     unsigned Shift;
9646
9647     Cost(bool ForCodeSize = false)
9648         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9649           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9650
9651     /// \brief Get the cost of one isolated slice.
9652     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9653         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9654           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9655       EVT TruncType = LS.Inst->getValueType(0);
9656       EVT LoadedType = LS.getLoadedType();
9657       if (TruncType != LoadedType &&
9658           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9659         ZExts = 1;
9660     }
9661
9662     /// \brief Account for slicing gain in the current cost.
9663     /// Slicing provide a few gains like removing a shift or a
9664     /// truncate. This method allows to grow the cost of the original
9665     /// load with the gain from this slice.
9666     void addSliceGain(const LoadedSlice &LS) {
9667       // Each slice saves a truncate.
9668       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9669       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9670                               LS.Inst->getOperand(0).getValueType()))
9671         ++Truncates;
9672       // If there is a shift amount, this slice gets rid of it.
9673       if (LS.Shift)
9674         ++Shift;
9675       // If this slice can merge a cross register bank copy, account for it.
9676       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9677         ++CrossRegisterBanksCopies;
9678     }
9679
9680     Cost &operator+=(const Cost &RHS) {
9681       Loads += RHS.Loads;
9682       Truncates += RHS.Truncates;
9683       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9684       ZExts += RHS.ZExts;
9685       Shift += RHS.Shift;
9686       return *this;
9687     }
9688
9689     bool operator==(const Cost &RHS) const {
9690       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9691              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9692              ZExts == RHS.ZExts && Shift == RHS.Shift;
9693     }
9694
9695     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9696
9697     bool operator<(const Cost &RHS) const {
9698       // Assume cross register banks copies are as expensive as loads.
9699       // FIXME: Do we want some more target hooks?
9700       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9701       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9702       // Unless we are optimizing for code size, consider the
9703       // expensive operation first.
9704       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9705         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9706       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9707              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9708     }
9709
9710     bool operator>(const Cost &RHS) const { return RHS < *this; }
9711
9712     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9713
9714     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9715   };
9716   // The last instruction that represent the slice. This should be a
9717   // truncate instruction.
9718   SDNode *Inst;
9719   // The original load instruction.
9720   LoadSDNode *Origin;
9721   // The right shift amount in bits from the original load.
9722   unsigned Shift;
9723   // The DAG from which Origin came from.
9724   // This is used to get some contextual information about legal types, etc.
9725   SelectionDAG *DAG;
9726
9727   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9728               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9729       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9730
9731   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9732   /// \return Result is \p BitWidth and has used bits set to 1 and
9733   ///         not used bits set to 0.
9734   APInt getUsedBits() const {
9735     // Reproduce the trunc(lshr) sequence:
9736     // - Start from the truncated value.
9737     // - Zero extend to the desired bit width.
9738     // - Shift left.
9739     assert(Origin && "No original load to compare against.");
9740     unsigned BitWidth = Origin->getValueSizeInBits(0);
9741     assert(Inst && "This slice is not bound to an instruction");
9742     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9743            "Extracted slice is bigger than the whole type!");
9744     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9745     UsedBits.setAllBits();
9746     UsedBits = UsedBits.zext(BitWidth);
9747     UsedBits <<= Shift;
9748     return UsedBits;
9749   }
9750
9751   /// \brief Get the size of the slice to be loaded in bytes.
9752   unsigned getLoadedSize() const {
9753     unsigned SliceSize = getUsedBits().countPopulation();
9754     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9755     return SliceSize / 8;
9756   }
9757
9758   /// \brief Get the type that will be loaded for this slice.
9759   /// Note: This may not be the final type for the slice.
9760   EVT getLoadedType() const {
9761     assert(DAG && "Missing context");
9762     LLVMContext &Ctxt = *DAG->getContext();
9763     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9764   }
9765
9766   /// \brief Get the alignment of the load used for this slice.
9767   unsigned getAlignment() const {
9768     unsigned Alignment = Origin->getAlignment();
9769     unsigned Offset = getOffsetFromBase();
9770     if (Offset != 0)
9771       Alignment = MinAlign(Alignment, Alignment + Offset);
9772     return Alignment;
9773   }
9774
9775   /// \brief Check if this slice can be rewritten with legal operations.
9776   bool isLegal() const {
9777     // An invalid slice is not legal.
9778     if (!Origin || !Inst || !DAG)
9779       return false;
9780
9781     // Offsets are for indexed load only, we do not handle that.
9782     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9783       return false;
9784
9785     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9786
9787     // Check that the type is legal.
9788     EVT SliceType = getLoadedType();
9789     if (!TLI.isTypeLegal(SliceType))
9790       return false;
9791
9792     // Check that the load is legal for this type.
9793     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9794       return false;
9795
9796     // Check that the offset can be computed.
9797     // 1. Check its type.
9798     EVT PtrType = Origin->getBasePtr().getValueType();
9799     if (PtrType == MVT::Untyped || PtrType.isExtended())
9800       return false;
9801
9802     // 2. Check that it fits in the immediate.
9803     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9804       return false;
9805
9806     // 3. Check that the computation is legal.
9807     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9808       return false;
9809
9810     // Check that the zext is legal if it needs one.
9811     EVT TruncateType = Inst->getValueType(0);
9812     if (TruncateType != SliceType &&
9813         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9814       return false;
9815
9816     return true;
9817   }
9818
9819   /// \brief Get the offset in bytes of this slice in the original chunk of
9820   /// bits.
9821   /// \pre DAG != nullptr.
9822   uint64_t getOffsetFromBase() const {
9823     assert(DAG && "Missing context.");
9824     bool IsBigEndian =
9825         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9826     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9827     uint64_t Offset = Shift / 8;
9828     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9829     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9830            "The size of the original loaded type is not a multiple of a"
9831            " byte.");
9832     // If Offset is bigger than TySizeInBytes, it means we are loading all
9833     // zeros. This should have been optimized before in the process.
9834     assert(TySizeInBytes > Offset &&
9835            "Invalid shift amount for given loaded size");
9836     if (IsBigEndian)
9837       Offset = TySizeInBytes - Offset - getLoadedSize();
9838     return Offset;
9839   }
9840
9841   /// \brief Generate the sequence of instructions to load the slice
9842   /// represented by this object and redirect the uses of this slice to
9843   /// this new sequence of instructions.
9844   /// \pre this->Inst && this->Origin are valid Instructions and this
9845   /// object passed the legal check: LoadedSlice::isLegal returned true.
9846   /// \return The last instruction of the sequence used to load the slice.
9847   SDValue loadSlice() const {
9848     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9849     const SDValue &OldBaseAddr = Origin->getBasePtr();
9850     SDValue BaseAddr = OldBaseAddr;
9851     // Get the offset in that chunk of bytes w.r.t. the endianess.
9852     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9853     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9854     if (Offset) {
9855       // BaseAddr = BaseAddr + Offset.
9856       EVT ArithType = BaseAddr.getValueType();
9857       SDLoc DL(Origin);
9858       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9859                               DAG->getConstant(Offset, DL, ArithType));
9860     }
9861
9862     // Create the type of the loaded slice according to its size.
9863     EVT SliceType = getLoadedType();
9864
9865     // Create the load for the slice.
9866     SDValue LastInst = DAG->getLoad(
9867         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9868         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9869         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9870     // If the final type is not the same as the loaded type, this means that
9871     // we have to pad with zero. Create a zero extend for that.
9872     EVT FinalType = Inst->getValueType(0);
9873     if (SliceType != FinalType)
9874       LastInst =
9875           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9876     return LastInst;
9877   }
9878
9879   /// \brief Check if this slice can be merged with an expensive cross register
9880   /// bank copy. E.g.,
9881   /// i = load i32
9882   /// f = bitcast i32 i to float
9883   bool canMergeExpensiveCrossRegisterBankCopy() const {
9884     if (!Inst || !Inst->hasOneUse())
9885       return false;
9886     SDNode *Use = *Inst->use_begin();
9887     if (Use->getOpcode() != ISD::BITCAST)
9888       return false;
9889     assert(DAG && "Missing context");
9890     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9891     EVT ResVT = Use->getValueType(0);
9892     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9893     const TargetRegisterClass *ArgRC =
9894         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9895     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9896       return false;
9897
9898     // At this point, we know that we perform a cross-register-bank copy.
9899     // Check if it is expensive.
9900     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9901     // Assume bitcasts are cheap, unless both register classes do not
9902     // explicitly share a common sub class.
9903     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9904       return false;
9905
9906     // Check if it will be merged with the load.
9907     // 1. Check the alignment constraint.
9908     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9909         ResVT.getTypeForEVT(*DAG->getContext()));
9910
9911     if (RequiredAlignment > getAlignment())
9912       return false;
9913
9914     // 2. Check that the load is a legal operation for that type.
9915     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9916       return false;
9917
9918     // 3. Check that we do not have a zext in the way.
9919     if (Inst->getValueType(0) != getLoadedType())
9920       return false;
9921
9922     return true;
9923   }
9924 };
9925 }
9926
9927 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9928 /// \p UsedBits looks like 0..0 1..1 0..0.
9929 static bool areUsedBitsDense(const APInt &UsedBits) {
9930   // If all the bits are one, this is dense!
9931   if (UsedBits.isAllOnesValue())
9932     return true;
9933
9934   // Get rid of the unused bits on the right.
9935   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9936   // Get rid of the unused bits on the left.
9937   if (NarrowedUsedBits.countLeadingZeros())
9938     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9939   // Check that the chunk of bits is completely used.
9940   return NarrowedUsedBits.isAllOnesValue();
9941 }
9942
9943 /// \brief Check whether or not \p First and \p Second are next to each other
9944 /// in memory. This means that there is no hole between the bits loaded
9945 /// by \p First and the bits loaded by \p Second.
9946 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9947                                      const LoadedSlice &Second) {
9948   assert(First.Origin == Second.Origin && First.Origin &&
9949          "Unable to match different memory origins.");
9950   APInt UsedBits = First.getUsedBits();
9951   assert((UsedBits & Second.getUsedBits()) == 0 &&
9952          "Slices are not supposed to overlap.");
9953   UsedBits |= Second.getUsedBits();
9954   return areUsedBitsDense(UsedBits);
9955 }
9956
9957 /// \brief Adjust the \p GlobalLSCost according to the target
9958 /// paring capabilities and the layout of the slices.
9959 /// \pre \p GlobalLSCost should account for at least as many loads as
9960 /// there is in the slices in \p LoadedSlices.
9961 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9962                                  LoadedSlice::Cost &GlobalLSCost) {
9963   unsigned NumberOfSlices = LoadedSlices.size();
9964   // If there is less than 2 elements, no pairing is possible.
9965   if (NumberOfSlices < 2)
9966     return;
9967
9968   // Sort the slices so that elements that are likely to be next to each
9969   // other in memory are next to each other in the list.
9970   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9971             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9972     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9973     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9974   });
9975   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9976   // First (resp. Second) is the first (resp. Second) potentially candidate
9977   // to be placed in a paired load.
9978   const LoadedSlice *First = nullptr;
9979   const LoadedSlice *Second = nullptr;
9980   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9981                 // Set the beginning of the pair.
9982                                                            First = Second) {
9983
9984     Second = &LoadedSlices[CurrSlice];
9985
9986     // If First is NULL, it means we start a new pair.
9987     // Get to the next slice.
9988     if (!First)
9989       continue;
9990
9991     EVT LoadedType = First->getLoadedType();
9992
9993     // If the types of the slices are different, we cannot pair them.
9994     if (LoadedType != Second->getLoadedType())
9995       continue;
9996
9997     // Check if the target supplies paired loads for this type.
9998     unsigned RequiredAlignment = 0;
9999     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10000       // move to the next pair, this type is hopeless.
10001       Second = nullptr;
10002       continue;
10003     }
10004     // Check if we meet the alignment requirement.
10005     if (RequiredAlignment > First->getAlignment())
10006       continue;
10007
10008     // Check that both loads are next to each other in memory.
10009     if (!areSlicesNextToEachOther(*First, *Second))
10010       continue;
10011
10012     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10013     --GlobalLSCost.Loads;
10014     // Move to the next pair.
10015     Second = nullptr;
10016   }
10017 }
10018
10019 /// \brief Check the profitability of all involved LoadedSlice.
10020 /// Currently, it is considered profitable if there is exactly two
10021 /// involved slices (1) which are (2) next to each other in memory, and
10022 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10023 ///
10024 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10025 /// the elements themselves.
10026 ///
10027 /// FIXME: When the cost model will be mature enough, we can relax
10028 /// constraints (1) and (2).
10029 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10030                                 const APInt &UsedBits, bool ForCodeSize) {
10031   unsigned NumberOfSlices = LoadedSlices.size();
10032   if (StressLoadSlicing)
10033     return NumberOfSlices > 1;
10034
10035   // Check (1).
10036   if (NumberOfSlices != 2)
10037     return false;
10038
10039   // Check (2).
10040   if (!areUsedBitsDense(UsedBits))
10041     return false;
10042
10043   // Check (3).
10044   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10045   // The original code has one big load.
10046   OrigCost.Loads = 1;
10047   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10048     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10049     // Accumulate the cost of all the slices.
10050     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10051     GlobalSlicingCost += SliceCost;
10052
10053     // Account as cost in the original configuration the gain obtained
10054     // with the current slices.
10055     OrigCost.addSliceGain(LS);
10056   }
10057
10058   // If the target supports paired load, adjust the cost accordingly.
10059   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10060   return OrigCost > GlobalSlicingCost;
10061 }
10062
10063 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10064 /// operations, split it in the various pieces being extracted.
10065 ///
10066 /// This sort of thing is introduced by SROA.
10067 /// This slicing takes care not to insert overlapping loads.
10068 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10069 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10070   if (Level < AfterLegalizeDAG)
10071     return false;
10072
10073   LoadSDNode *LD = cast<LoadSDNode>(N);
10074   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10075       !LD->getValueType(0).isInteger())
10076     return false;
10077
10078   // Keep track of already used bits to detect overlapping values.
10079   // In that case, we will just abort the transformation.
10080   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10081
10082   SmallVector<LoadedSlice, 4> LoadedSlices;
10083
10084   // Check if this load is used as several smaller chunks of bits.
10085   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10086   // of computation for each trunc.
10087   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10088        UI != UIEnd; ++UI) {
10089     // Skip the uses of the chain.
10090     if (UI.getUse().getResNo() != 0)
10091       continue;
10092
10093     SDNode *User = *UI;
10094     unsigned Shift = 0;
10095
10096     // Check if this is a trunc(lshr).
10097     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10098         isa<ConstantSDNode>(User->getOperand(1))) {
10099       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10100       User = *User->use_begin();
10101     }
10102
10103     // At this point, User is a Truncate, iff we encountered, trunc or
10104     // trunc(lshr).
10105     if (User->getOpcode() != ISD::TRUNCATE)
10106       return false;
10107
10108     // The width of the type must be a power of 2 and greater than 8-bits.
10109     // Otherwise the load cannot be represented in LLVM IR.
10110     // Moreover, if we shifted with a non-8-bits multiple, the slice
10111     // will be across several bytes. We do not support that.
10112     unsigned Width = User->getValueSizeInBits(0);
10113     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10114       return 0;
10115
10116     // Build the slice for this chain of computations.
10117     LoadedSlice LS(User, LD, Shift, &DAG);
10118     APInt CurrentUsedBits = LS.getUsedBits();
10119
10120     // Check if this slice overlaps with another.
10121     if ((CurrentUsedBits & UsedBits) != 0)
10122       return false;
10123     // Update the bits used globally.
10124     UsedBits |= CurrentUsedBits;
10125
10126     // Check if the new slice would be legal.
10127     if (!LS.isLegal())
10128       return false;
10129
10130     // Record the slice.
10131     LoadedSlices.push_back(LS);
10132   }
10133
10134   // Abort slicing if it does not seem to be profitable.
10135   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10136     return false;
10137
10138   ++SlicedLoads;
10139
10140   // Rewrite each chain to use an independent load.
10141   // By construction, each chain can be represented by a unique load.
10142
10143   // Prepare the argument for the new token factor for all the slices.
10144   SmallVector<SDValue, 8> ArgChains;
10145   for (SmallVectorImpl<LoadedSlice>::const_iterator
10146            LSIt = LoadedSlices.begin(),
10147            LSItEnd = LoadedSlices.end();
10148        LSIt != LSItEnd; ++LSIt) {
10149     SDValue SliceInst = LSIt->loadSlice();
10150     CombineTo(LSIt->Inst, SliceInst, true);
10151     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10152       SliceInst = SliceInst.getOperand(0);
10153     assert(SliceInst->getOpcode() == ISD::LOAD &&
10154            "It takes more than a zext to get to the loaded slice!!");
10155     ArgChains.push_back(SliceInst.getValue(1));
10156   }
10157
10158   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10159                               ArgChains);
10160   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10161   return true;
10162 }
10163
10164 /// Check to see if V is (and load (ptr), imm), where the load is having
10165 /// specific bytes cleared out.  If so, return the byte size being masked out
10166 /// and the shift amount.
10167 static std::pair<unsigned, unsigned>
10168 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10169   std::pair<unsigned, unsigned> Result(0, 0);
10170
10171   // Check for the structure we're looking for.
10172   if (V->getOpcode() != ISD::AND ||
10173       !isa<ConstantSDNode>(V->getOperand(1)) ||
10174       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10175     return Result;
10176
10177   // Check the chain and pointer.
10178   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10179   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10180
10181   // The store should be chained directly to the load or be an operand of a
10182   // tokenfactor.
10183   if (LD == Chain.getNode())
10184     ; // ok.
10185   else if (Chain->getOpcode() != ISD::TokenFactor)
10186     return Result; // Fail.
10187   else {
10188     bool isOk = false;
10189     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10190       if (Chain->getOperand(i).getNode() == LD) {
10191         isOk = true;
10192         break;
10193       }
10194     if (!isOk) return Result;
10195   }
10196
10197   // This only handles simple types.
10198   if (V.getValueType() != MVT::i16 &&
10199       V.getValueType() != MVT::i32 &&
10200       V.getValueType() != MVT::i64)
10201     return Result;
10202
10203   // Check the constant mask.  Invert it so that the bits being masked out are
10204   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10205   // follow the sign bit for uniformity.
10206   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10207   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10208   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10209   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10210   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10211   if (NotMaskLZ == 64) return Result;  // All zero mask.
10212
10213   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10214   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10215     return Result;
10216
10217   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10218   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10219     NotMaskLZ -= 64-V.getValueSizeInBits();
10220
10221   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10222   switch (MaskedBytes) {
10223   case 1:
10224   case 2:
10225   case 4: break;
10226   default: return Result; // All one mask, or 5-byte mask.
10227   }
10228
10229   // Verify that the first bit starts at a multiple of mask so that the access
10230   // is aligned the same as the access width.
10231   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10232
10233   Result.first = MaskedBytes;
10234   Result.second = NotMaskTZ/8;
10235   return Result;
10236 }
10237
10238
10239 /// Check to see if IVal is something that provides a value as specified by
10240 /// MaskInfo. If so, replace the specified store with a narrower store of
10241 /// truncated IVal.
10242 static SDNode *
10243 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10244                                 SDValue IVal, StoreSDNode *St,
10245                                 DAGCombiner *DC) {
10246   unsigned NumBytes = MaskInfo.first;
10247   unsigned ByteShift = MaskInfo.second;
10248   SelectionDAG &DAG = DC->getDAG();
10249
10250   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10251   // that uses this.  If not, this is not a replacement.
10252   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10253                                   ByteShift*8, (ByteShift+NumBytes)*8);
10254   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10255
10256   // Check that it is legal on the target to do this.  It is legal if the new
10257   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10258   // legalization.
10259   MVT VT = MVT::getIntegerVT(NumBytes*8);
10260   if (!DC->isTypeLegal(VT))
10261     return nullptr;
10262
10263   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10264   // shifted by ByteShift and truncated down to NumBytes.
10265   if (ByteShift) {
10266     SDLoc DL(IVal);
10267     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10268                        DAG.getConstant(ByteShift*8, DL,
10269                                     DC->getShiftAmountTy(IVal.getValueType())));
10270   }
10271
10272   // Figure out the offset for the store and the alignment of the access.
10273   unsigned StOffset;
10274   unsigned NewAlign = St->getAlignment();
10275
10276   if (DAG.getTargetLoweringInfo().isLittleEndian())
10277     StOffset = ByteShift;
10278   else
10279     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10280
10281   SDValue Ptr = St->getBasePtr();
10282   if (StOffset) {
10283     SDLoc DL(IVal);
10284     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10285                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10286     NewAlign = MinAlign(NewAlign, StOffset);
10287   }
10288
10289   // Truncate down to the new size.
10290   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10291
10292   ++OpsNarrowed;
10293   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10294                       St->getPointerInfo().getWithOffset(StOffset),
10295                       false, false, NewAlign).getNode();
10296 }
10297
10298
10299 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10300 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10301 /// narrowing the load and store if it would end up being a win for performance
10302 /// or code size.
10303 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10304   StoreSDNode *ST  = cast<StoreSDNode>(N);
10305   if (ST->isVolatile())
10306     return SDValue();
10307
10308   SDValue Chain = ST->getChain();
10309   SDValue Value = ST->getValue();
10310   SDValue Ptr   = ST->getBasePtr();
10311   EVT VT = Value.getValueType();
10312
10313   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10314     return SDValue();
10315
10316   unsigned Opc = Value.getOpcode();
10317
10318   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10319   // is a byte mask indicating a consecutive number of bytes, check to see if
10320   // Y is known to provide just those bytes.  If so, we try to replace the
10321   // load + replace + store sequence with a single (narrower) store, which makes
10322   // the load dead.
10323   if (Opc == ISD::OR) {
10324     std::pair<unsigned, unsigned> MaskedLoad;
10325     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10326     if (MaskedLoad.first)
10327       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10328                                                   Value.getOperand(1), ST,this))
10329         return SDValue(NewST, 0);
10330
10331     // Or is commutative, so try swapping X and Y.
10332     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10333     if (MaskedLoad.first)
10334       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10335                                                   Value.getOperand(0), ST,this))
10336         return SDValue(NewST, 0);
10337   }
10338
10339   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10340       Value.getOperand(1).getOpcode() != ISD::Constant)
10341     return SDValue();
10342
10343   SDValue N0 = Value.getOperand(0);
10344   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10345       Chain == SDValue(N0.getNode(), 1)) {
10346     LoadSDNode *LD = cast<LoadSDNode>(N0);
10347     if (LD->getBasePtr() != Ptr ||
10348         LD->getPointerInfo().getAddrSpace() !=
10349         ST->getPointerInfo().getAddrSpace())
10350       return SDValue();
10351
10352     // Find the type to narrow it the load / op / store to.
10353     SDValue N1 = Value.getOperand(1);
10354     unsigned BitWidth = N1.getValueSizeInBits();
10355     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10356     if (Opc == ISD::AND)
10357       Imm ^= APInt::getAllOnesValue(BitWidth);
10358     if (Imm == 0 || Imm.isAllOnesValue())
10359       return SDValue();
10360     unsigned ShAmt = Imm.countTrailingZeros();
10361     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10362     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10363     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10364     // The narrowing should be profitable, the load/store operation should be
10365     // legal (or custom) and the store size should be equal to the NewVT width.
10366     while (NewBW < BitWidth &&
10367            (NewVT.getStoreSizeInBits() != NewBW ||
10368             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10369             !TLI.isNarrowingProfitable(VT, NewVT))) {
10370       NewBW = NextPowerOf2(NewBW);
10371       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10372     }
10373     if (NewBW >= BitWidth)
10374       return SDValue();
10375
10376     // If the lsb changed does not start at the type bitwidth boundary,
10377     // start at the previous one.
10378     if (ShAmt % NewBW)
10379       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10380     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10381                                    std::min(BitWidth, ShAmt + NewBW));
10382     if ((Imm & Mask) == Imm) {
10383       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10384       if (Opc == ISD::AND)
10385         NewImm ^= APInt::getAllOnesValue(NewBW);
10386       uint64_t PtrOff = ShAmt / 8;
10387       // For big endian targets, we need to adjust the offset to the pointer to
10388       // load the correct bytes.
10389       if (TLI.isBigEndian())
10390         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10391
10392       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10393       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10394       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10395         return SDValue();
10396
10397       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10398                                    Ptr.getValueType(), Ptr,
10399                                    DAG.getConstant(PtrOff, SDLoc(LD),
10400                                                    Ptr.getValueType()));
10401       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10402                                   LD->getChain(), NewPtr,
10403                                   LD->getPointerInfo().getWithOffset(PtrOff),
10404                                   LD->isVolatile(), LD->isNonTemporal(),
10405                                   LD->isInvariant(), NewAlign,
10406                                   LD->getAAInfo());
10407       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10408                                    DAG.getConstant(NewImm, SDLoc(Value),
10409                                                    NewVT));
10410       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10411                                    NewVal, NewPtr,
10412                                    ST->getPointerInfo().getWithOffset(PtrOff),
10413                                    false, false, NewAlign);
10414
10415       AddToWorklist(NewPtr.getNode());
10416       AddToWorklist(NewLD.getNode());
10417       AddToWorklist(NewVal.getNode());
10418       WorklistRemover DeadNodes(*this);
10419       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10420       ++OpsNarrowed;
10421       return NewST;
10422     }
10423   }
10424
10425   return SDValue();
10426 }
10427
10428 /// For a given floating point load / store pair, if the load value isn't used
10429 /// by any other operations, then consider transforming the pair to integer
10430 /// load / store operations if the target deems the transformation profitable.
10431 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10432   StoreSDNode *ST  = cast<StoreSDNode>(N);
10433   SDValue Chain = ST->getChain();
10434   SDValue Value = ST->getValue();
10435   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10436       Value.hasOneUse() &&
10437       Chain == SDValue(Value.getNode(), 1)) {
10438     LoadSDNode *LD = cast<LoadSDNode>(Value);
10439     EVT VT = LD->getMemoryVT();
10440     if (!VT.isFloatingPoint() ||
10441         VT != ST->getMemoryVT() ||
10442         LD->isNonTemporal() ||
10443         ST->isNonTemporal() ||
10444         LD->getPointerInfo().getAddrSpace() != 0 ||
10445         ST->getPointerInfo().getAddrSpace() != 0)
10446       return SDValue();
10447
10448     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10449     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10450         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10451         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10452         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10453       return SDValue();
10454
10455     unsigned LDAlign = LD->getAlignment();
10456     unsigned STAlign = ST->getAlignment();
10457     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10458     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10459     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10460       return SDValue();
10461
10462     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10463                                 LD->getChain(), LD->getBasePtr(),
10464                                 LD->getPointerInfo(),
10465                                 false, false, false, LDAlign);
10466
10467     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10468                                  NewLD, ST->getBasePtr(),
10469                                  ST->getPointerInfo(),
10470                                  false, false, STAlign);
10471
10472     AddToWorklist(NewLD.getNode());
10473     AddToWorklist(NewST.getNode());
10474     WorklistRemover DeadNodes(*this);
10475     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10476     ++LdStFP2Int;
10477     return NewST;
10478   }
10479
10480   return SDValue();
10481 }
10482
10483 namespace {
10484 /// Helper struct to parse and store a memory address as base + index + offset.
10485 /// We ignore sign extensions when it is safe to do so.
10486 /// The following two expressions are not equivalent. To differentiate we need
10487 /// to store whether there was a sign extension involved in the index
10488 /// computation.
10489 ///  (load (i64 add (i64 copyfromreg %c)
10490 ///                 (i64 signextend (add (i8 load %index)
10491 ///                                      (i8 1))))
10492 /// vs
10493 ///
10494 /// (load (i64 add (i64 copyfromreg %c)
10495 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10496 ///                                         (i32 1)))))
10497 struct BaseIndexOffset {
10498   SDValue Base;
10499   SDValue Index;
10500   int64_t Offset;
10501   bool IsIndexSignExt;
10502
10503   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10504
10505   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10506                   bool IsIndexSignExt) :
10507     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10508
10509   bool equalBaseIndex(const BaseIndexOffset &Other) {
10510     return Other.Base == Base && Other.Index == Index &&
10511       Other.IsIndexSignExt == IsIndexSignExt;
10512   }
10513
10514   /// Parses tree in Ptr for base, index, offset addresses.
10515   static BaseIndexOffset match(SDValue Ptr) {
10516     bool IsIndexSignExt = false;
10517
10518     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10519     // instruction, then it could be just the BASE or everything else we don't
10520     // know how to handle. Just use Ptr as BASE and give up.
10521     if (Ptr->getOpcode() != ISD::ADD)
10522       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10523
10524     // We know that we have at least an ADD instruction. Try to pattern match
10525     // the simple case of BASE + OFFSET.
10526     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10527       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10528       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10529                               IsIndexSignExt);
10530     }
10531
10532     // Inside a loop the current BASE pointer is calculated using an ADD and a
10533     // MUL instruction. In this case Ptr is the actual BASE pointer.
10534     // (i64 add (i64 %array_ptr)
10535     //          (i64 mul (i64 %induction_var)
10536     //                   (i64 %element_size)))
10537     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10538       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10539
10540     // Look at Base + Index + Offset cases.
10541     SDValue Base = Ptr->getOperand(0);
10542     SDValue IndexOffset = Ptr->getOperand(1);
10543
10544     // Skip signextends.
10545     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10546       IndexOffset = IndexOffset->getOperand(0);
10547       IsIndexSignExt = true;
10548     }
10549
10550     // Either the case of Base + Index (no offset) or something else.
10551     if (IndexOffset->getOpcode() != ISD::ADD)
10552       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10553
10554     // Now we have the case of Base + Index + offset.
10555     SDValue Index = IndexOffset->getOperand(0);
10556     SDValue Offset = IndexOffset->getOperand(1);
10557
10558     if (!isa<ConstantSDNode>(Offset))
10559       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10560
10561     // Ignore signextends.
10562     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10563       Index = Index->getOperand(0);
10564       IsIndexSignExt = true;
10565     } else IsIndexSignExt = false;
10566
10567     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10568     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10569   }
10570 };
10571 } // namespace
10572
10573 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10574                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10575                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10576   // Make sure we have something to merge.
10577   if (NumElem < 2)
10578     return false;
10579
10580   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10581   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10582   unsigned LatestNodeUsed = 0;
10583
10584   for (unsigned i=0; i < NumElem; ++i) {
10585     // Find a chain for the new wide-store operand. Notice that some
10586     // of the store nodes that we found may not be selected for inclusion
10587     // in the wide store. The chain we use needs to be the chain of the
10588     // latest store node which is *used* and replaced by the wide store.
10589     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10590       LatestNodeUsed = i;
10591   }
10592
10593   // The latest Node in the DAG.
10594   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10595   SDLoc DL(StoreNodes[0].MemNode);
10596
10597   SDValue StoredVal;
10598   if (UseVector) {
10599     // Find a legal type for the vector store.
10600     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10601     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10602     if (IsConstantSrc) {
10603       // A vector store with a constant source implies that the constant is
10604       // zero; we only handle merging stores of constant zeros because the zero
10605       // can be materialized without a load.
10606       // It may be beneficial to loosen this restriction to allow non-zero
10607       // store merging.
10608       StoredVal = DAG.getConstant(0, DL, Ty);
10609     } else {
10610       SmallVector<SDValue, 8> Ops;
10611       for (unsigned i = 0; i < NumElem ; ++i) {
10612         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10613         SDValue Val = St->getValue();
10614         // All of the operands of a BUILD_VECTOR must have the same type.
10615         if (Val.getValueType() != MemVT)
10616           return false;
10617         Ops.push_back(Val);
10618       }
10619
10620       // Build the extracted vector elements back into a vector.
10621       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10622     }
10623   } else {
10624     // We should always use a vector store when merging extracted vector
10625     // elements, so this path implies a store of constants.
10626     assert(IsConstantSrc && "Merged vector elements should use vector store");
10627
10628     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10629     APInt StoreInt(StoreBW, 0);
10630
10631     // Construct a single integer constant which is made of the smaller
10632     // constant inputs.
10633     bool IsLE = TLI.isLittleEndian();
10634     for (unsigned i = 0; i < NumElem ; ++i) {
10635       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10636       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10637       SDValue Val = St->getValue();
10638       StoreInt <<= ElementSizeBytes*8;
10639       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10640         StoreInt |= C->getAPIntValue().zext(StoreBW);
10641       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10642         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10643       } else {
10644         llvm_unreachable("Invalid constant element type");
10645       }
10646     }
10647
10648     // Create the new Load and Store operations.
10649     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10650     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10651   }
10652
10653   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10654                                   FirstInChain->getBasePtr(),
10655                                   FirstInChain->getPointerInfo(),
10656                                   false, false,
10657                                   FirstInChain->getAlignment());
10658
10659   // Replace the last store with the new store
10660   CombineTo(LatestOp, NewStore);
10661   // Erase all other stores.
10662   for (unsigned i = 0; i < NumElem ; ++i) {
10663     if (StoreNodes[i].MemNode == LatestOp)
10664       continue;
10665     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10666     // ReplaceAllUsesWith will replace all uses that existed when it was
10667     // called, but graph optimizations may cause new ones to appear. For
10668     // example, the case in pr14333 looks like
10669     //
10670     //  St's chain -> St -> another store -> X
10671     //
10672     // And the only difference from St to the other store is the chain.
10673     // When we change it's chain to be St's chain they become identical,
10674     // get CSEed and the net result is that X is now a use of St.
10675     // Since we know that St is redundant, just iterate.
10676     while (!St->use_empty())
10677       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10678     deleteAndRecombine(St);
10679   }
10680
10681   return true;
10682 }
10683
10684 static bool allowableAlignment(const SelectionDAG &DAG,
10685                                const TargetLowering &TLI, EVT EVTTy,
10686                                unsigned AS, unsigned Align) {
10687   if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10688     return true;
10689
10690   Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10691   unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10692   return (Align >= ABIAlignment);
10693 }
10694
10695 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10696   if (OptLevel == CodeGenOpt::None)
10697     return false;
10698
10699   EVT MemVT = St->getMemoryVT();
10700   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10701   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10702       Attribute::NoImplicitFloat);
10703
10704   // This function cannot currently deal with non-byte-sized memory sizes.
10705   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10706     return false;
10707
10708   // Don't merge vectors into wider inputs.
10709   if (MemVT.isVector() || !MemVT.isSimple())
10710     return false;
10711
10712   // Perform an early exit check. Do not bother looking at stored values that
10713   // are not constants, loads, or extracted vector elements.
10714   SDValue StoredVal = St->getValue();
10715   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10716   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10717                        isa<ConstantFPSDNode>(StoredVal);
10718   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10719
10720   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10721     return false;
10722
10723   // Only look at ends of store sequences.
10724   SDValue Chain = SDValue(St, 0);
10725   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10726     return false;
10727
10728   // This holds the base pointer, index, and the offset in bytes from the base
10729   // pointer.
10730   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10731
10732   // We must have a base and an offset.
10733   if (!BasePtr.Base.getNode())
10734     return false;
10735
10736   // Do not handle stores to undef base pointers.
10737   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10738     return false;
10739
10740   // Save the LoadSDNodes that we find in the chain.
10741   // We need to make sure that these nodes do not interfere with
10742   // any of the store nodes.
10743   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10744
10745   // Save the StoreSDNodes that we find in the chain.
10746   SmallVector<MemOpLink, 8> StoreNodes;
10747
10748   // Walk up the chain and look for nodes with offsets from the same
10749   // base pointer. Stop when reaching an instruction with a different kind
10750   // or instruction which has a different base pointer.
10751   unsigned Seq = 0;
10752   StoreSDNode *Index = St;
10753   while (Index) {
10754     // If the chain has more than one use, then we can't reorder the mem ops.
10755     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10756       break;
10757
10758     // Find the base pointer and offset for this memory node.
10759     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10760
10761     // Check that the base pointer is the same as the original one.
10762     if (!Ptr.equalBaseIndex(BasePtr))
10763       break;
10764
10765     // The memory operands must not be volatile.
10766     if (Index->isVolatile() || Index->isIndexed())
10767       break;
10768
10769     // No truncation.
10770     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10771       if (St->isTruncatingStore())
10772         break;
10773
10774     // The stored memory type must be the same.
10775     if (Index->getMemoryVT() != MemVT)
10776       break;
10777
10778     // We found a potential memory operand to merge.
10779     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10780
10781     // Find the next memory operand in the chain. If the next operand in the
10782     // chain is a store then move up and continue the scan with the next
10783     // memory operand. If the next operand is a load save it and use alias
10784     // information to check if it interferes with anything.
10785     SDNode *NextInChain = Index->getChain().getNode();
10786     while (1) {
10787       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10788         // We found a store node. Use it for the next iteration.
10789         Index = STn;
10790         break;
10791       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10792         if (Ldn->isVolatile()) {
10793           Index = nullptr;
10794           break;
10795         }
10796
10797         // Save the load node for later. Continue the scan.
10798         AliasLoadNodes.push_back(Ldn);
10799         NextInChain = Ldn->getChain().getNode();
10800         continue;
10801       } else {
10802         Index = nullptr;
10803         break;
10804       }
10805     }
10806   }
10807
10808   // Check if there is anything to merge.
10809   if (StoreNodes.size() < 2)
10810     return false;
10811
10812   // Sort the memory operands according to their distance from the base pointer.
10813   std::sort(StoreNodes.begin(), StoreNodes.end(),
10814             [](MemOpLink LHS, MemOpLink RHS) {
10815     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10816            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10817             LHS.SequenceNum > RHS.SequenceNum);
10818   });
10819
10820   // Scan the memory operations on the chain and find the first non-consecutive
10821   // store memory address.
10822   unsigned LastConsecutiveStore = 0;
10823   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10824   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10825
10826     // Check that the addresses are consecutive starting from the second
10827     // element in the list of stores.
10828     if (i > 0) {
10829       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10830       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10831         break;
10832     }
10833
10834     bool Alias = false;
10835     // Check if this store interferes with any of the loads that we found.
10836     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10837       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10838         Alias = true;
10839         break;
10840       }
10841     // We found a load that alias with this store. Stop the sequence.
10842     if (Alias)
10843       break;
10844
10845     // Mark this node as useful.
10846     LastConsecutiveStore = i;
10847   }
10848
10849   // The node with the lowest store address.
10850   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10851   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10852   unsigned FirstStoreAlign = FirstInChain->getAlignment();
10853
10854   // Store the constants into memory as one consecutive store.
10855   if (IsConstantSrc) {
10856     unsigned LastLegalType = 0;
10857     unsigned LastLegalVectorType = 0;
10858     bool NonZero = false;
10859     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10860       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10861       SDValue StoredVal = St->getValue();
10862
10863       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10864         NonZero |= !C->isNullValue();
10865       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10866         NonZero |= !C->getConstantFPValue()->isNullValue();
10867       } else {
10868         // Non-constant.
10869         break;
10870       }
10871
10872       // Find a legal type for the constant store.
10873       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10874       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10875       if (TLI.isTypeLegal(StoreTy) &&
10876           allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10877                              FirstStoreAlign)) {
10878         LastLegalType = i+1;
10879       // Or check whether a truncstore is legal.
10880       } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10881                  TargetLowering::TypePromoteInteger) {
10882         EVT LegalizedStoredValueTy =
10883           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10884         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10885             allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10886                                FirstStoreAlign)) {
10887           LastLegalType = i + 1;
10888         }
10889       }
10890
10891       // Find a legal type for the vector store.
10892       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10893       if (TLI.isTypeLegal(Ty) &&
10894           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10895         LastLegalVectorType = i + 1;
10896       }
10897     }
10898
10899
10900     // We only use vectors if the constant is known to be zero or the target
10901     // allows it and the function is not marked with the noimplicitfloat
10902     // attribute.
10903     if (NoVectors) {
10904       LastLegalVectorType = 0;
10905     } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10906                                                             LastLegalVectorType,
10907                                                             FirstStoreAS)) {
10908       LastLegalVectorType = 0;
10909     }
10910
10911     // Check if we found a legal integer type to store.
10912     if (LastLegalType == 0 && LastLegalVectorType == 0)
10913       return false;
10914
10915     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10916     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10917
10918     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10919                                            true, UseVector);
10920   }
10921
10922   // When extracting multiple vector elements, try to store them
10923   // in one vector store rather than a sequence of scalar stores.
10924   if (IsExtractVecEltSrc) {
10925     unsigned NumElem = 0;
10926     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10927       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10928       SDValue StoredVal = St->getValue();
10929       // This restriction could be loosened.
10930       // Bail out if any stored values are not elements extracted from a vector.
10931       // It should be possible to handle mixed sources, but load sources need
10932       // more careful handling (see the block of code below that handles
10933       // consecutive loads).
10934       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10935         return false;
10936
10937       // Find a legal type for the vector store.
10938       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10939       if (TLI.isTypeLegal(Ty) &&
10940           allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
10941         NumElem = i + 1;
10942     }
10943
10944     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10945                                            false, true);
10946   }
10947
10948   // Below we handle the case of multiple consecutive stores that
10949   // come from multiple consecutive loads. We merge them into a single
10950   // wide load and a single wide store.
10951
10952   // Look for load nodes which are used by the stored values.
10953   SmallVector<MemOpLink, 8> LoadNodes;
10954
10955   // Find acceptable loads. Loads need to have the same chain (token factor),
10956   // must not be zext, volatile, indexed, and they must be consecutive.
10957   BaseIndexOffset LdBasePtr;
10958   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10959     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10960     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10961     if (!Ld) break;
10962
10963     // Loads must only have one use.
10964     if (!Ld->hasNUsesOfValue(1, 0))
10965       break;
10966
10967     // The memory operands must not be volatile.
10968     if (Ld->isVolatile() || Ld->isIndexed())
10969       break;
10970
10971     // We do not accept ext loads.
10972     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10973       break;
10974
10975     // The stored memory type must be the same.
10976     if (Ld->getMemoryVT() != MemVT)
10977       break;
10978
10979     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10980     // If this is not the first ptr that we check.
10981     if (LdBasePtr.Base.getNode()) {
10982       // The base ptr must be the same.
10983       if (!LdPtr.equalBaseIndex(LdBasePtr))
10984         break;
10985     } else {
10986       // Check that all other base pointers are the same as this one.
10987       LdBasePtr = LdPtr;
10988     }
10989
10990     // We found a potential memory operand to merge.
10991     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10992   }
10993
10994   if (LoadNodes.size() < 2)
10995     return false;
10996
10997   // If we have load/store pair instructions and we only have two values,
10998   // don't bother.
10999   unsigned RequiredAlignment;
11000   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11001       St->getAlignment() >= RequiredAlignment)
11002     return false;
11003
11004   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11005   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11006   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11007
11008   // Scan the memory operations on the chain and find the first non-consecutive
11009   // load memory address. These variables hold the index in the store node
11010   // array.
11011   unsigned LastConsecutiveLoad = 0;
11012   // This variable refers to the size and not index in the array.
11013   unsigned LastLegalVectorType = 0;
11014   unsigned LastLegalIntegerType = 0;
11015   StartAddress = LoadNodes[0].OffsetFromBase;
11016   SDValue FirstChain = FirstLoad->getChain();
11017   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11018     // All loads much share the same chain.
11019     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11020       break;
11021
11022     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11023     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11024       break;
11025     LastConsecutiveLoad = i;
11026
11027     // Find a legal type for the vector store.
11028     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11029     if (TLI.isTypeLegal(StoreTy) &&
11030         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11031         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11032       LastLegalVectorType = i + 1;
11033     }
11034
11035     // Find a legal type for the integer store.
11036     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11037     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11038     if (TLI.isTypeLegal(StoreTy) &&
11039         allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11040         allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11041       LastLegalIntegerType = i + 1;
11042     // Or check whether a truncstore and extload is legal.
11043     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11044              TargetLowering::TypePromoteInteger) {
11045       EVT LegalizedStoredValueTy =
11046         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11047       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11048           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11049           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11050           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11051           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11052                              FirstStoreAlign) &&
11053           allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11054                              FirstLoadAlign))
11055         LastLegalIntegerType = i+1;
11056     }
11057   }
11058
11059   // Only use vector types if the vector type is larger than the integer type.
11060   // If they are the same, use integers.
11061   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11062   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11063
11064   // We add +1 here because the LastXXX variables refer to location while
11065   // the NumElem refers to array/index size.
11066   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11067   NumElem = std::min(LastLegalType, NumElem);
11068
11069   if (NumElem < 2)
11070     return false;
11071
11072   // The latest Node in the DAG.
11073   unsigned LatestNodeUsed = 0;
11074   for (unsigned i=1; i<NumElem; ++i) {
11075     // Find a chain for the new wide-store operand. Notice that some
11076     // of the store nodes that we found may not be selected for inclusion
11077     // in the wide store. The chain we use needs to be the chain of the
11078     // latest store node which is *used* and replaced by the wide store.
11079     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11080       LatestNodeUsed = i;
11081   }
11082
11083   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11084
11085   // Find if it is better to use vectors or integers to load and store
11086   // to memory.
11087   EVT JointMemOpVT;
11088   if (UseVectorTy) {
11089     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11090   } else {
11091     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11092     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11093   }
11094
11095   SDLoc LoadDL(LoadNodes[0].MemNode);
11096   SDLoc StoreDL(StoreNodes[0].MemNode);
11097
11098   SDValue NewLoad = DAG.getLoad(
11099       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11100       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11101
11102   SDValue NewStore = DAG.getStore(
11103       LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11104       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11105
11106   // Replace one of the loads with the new load.
11107   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11108   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11109                                 SDValue(NewLoad.getNode(), 1));
11110
11111   // Remove the rest of the load chains.
11112   for (unsigned i = 1; i < NumElem ; ++i) {
11113     // Replace all chain users of the old load nodes with the chain of the new
11114     // load node.
11115     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11116     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11117   }
11118
11119   // Replace the last store with the new store.
11120   CombineTo(LatestOp, NewStore);
11121   // Erase all other stores.
11122   for (unsigned i = 0; i < NumElem ; ++i) {
11123     // Remove all Store nodes.
11124     if (StoreNodes[i].MemNode == LatestOp)
11125       continue;
11126     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11127     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11128     deleteAndRecombine(St);
11129   }
11130
11131   return true;
11132 }
11133
11134 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11135   StoreSDNode *ST  = cast<StoreSDNode>(N);
11136   SDValue Chain = ST->getChain();
11137   SDValue Value = ST->getValue();
11138   SDValue Ptr   = ST->getBasePtr();
11139
11140   // If this is a store of a bit convert, store the input value if the
11141   // resultant store does not need a higher alignment than the original.
11142   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11143       ST->isUnindexed()) {
11144     unsigned OrigAlign = ST->getAlignment();
11145     EVT SVT = Value.getOperand(0).getValueType();
11146     unsigned Align = TLI.getDataLayout()->
11147       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11148     if (Align <= OrigAlign &&
11149         ((!LegalOperations && !ST->isVolatile()) ||
11150          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11151       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11152                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11153                           ST->isNonTemporal(), OrigAlign,
11154                           ST->getAAInfo());
11155   }
11156
11157   // Turn 'store undef, Ptr' -> nothing.
11158   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11159     return Chain;
11160
11161   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11162   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11163     // NOTE: If the original store is volatile, this transform must not increase
11164     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11165     // processor operation but an i64 (which is not legal) requires two.  So the
11166     // transform should not be done in this case.
11167     if (Value.getOpcode() != ISD::TargetConstantFP) {
11168       SDValue Tmp;
11169       switch (CFP->getSimpleValueType(0).SimpleTy) {
11170       default: llvm_unreachable("Unknown FP type");
11171       case MVT::f16:    // We don't do this for these yet.
11172       case MVT::f80:
11173       case MVT::f128:
11174       case MVT::ppcf128:
11175         break;
11176       case MVT::f32:
11177         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11178             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11179           ;
11180           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11181                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11182                               MVT::i32);
11183           return DAG.getStore(Chain, SDLoc(N), Tmp,
11184                               Ptr, ST->getMemOperand());
11185         }
11186         break;
11187       case MVT::f64:
11188         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11189              !ST->isVolatile()) ||
11190             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11191           ;
11192           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11193                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11194           return DAG.getStore(Chain, SDLoc(N), Tmp,
11195                               Ptr, ST->getMemOperand());
11196         }
11197
11198         if (!ST->isVolatile() &&
11199             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11200           // Many FP stores are not made apparent until after legalize, e.g. for
11201           // argument passing.  Since this is so common, custom legalize the
11202           // 64-bit integer store into two 32-bit stores.
11203           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11204           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11205           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11206           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11207
11208           unsigned Alignment = ST->getAlignment();
11209           bool isVolatile = ST->isVolatile();
11210           bool isNonTemporal = ST->isNonTemporal();
11211           AAMDNodes AAInfo = ST->getAAInfo();
11212
11213           SDLoc DL(N);
11214
11215           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11216                                      Ptr, ST->getPointerInfo(),
11217                                      isVolatile, isNonTemporal,
11218                                      ST->getAlignment(), AAInfo);
11219           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11220                             DAG.getConstant(4, DL, Ptr.getValueType()));
11221           Alignment = MinAlign(Alignment, 4U);
11222           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11223                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11224                                      isVolatile, isNonTemporal,
11225                                      Alignment, AAInfo);
11226           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11227                              St0, St1);
11228         }
11229
11230         break;
11231       }
11232     }
11233   }
11234
11235   // Try to infer better alignment information than the store already has.
11236   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11237     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11238       if (Align > ST->getAlignment()) {
11239         SDValue NewStore =
11240                DAG.getTruncStore(Chain, SDLoc(N), Value,
11241                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11242                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11243                                  ST->getAAInfo());
11244         if (NewStore.getNode() != N)
11245           return CombineTo(ST, NewStore, true);
11246       }
11247     }
11248   }
11249
11250   // Try transforming a pair floating point load / store ops to integer
11251   // load / store ops.
11252   SDValue NewST = TransformFPLoadStorePair(N);
11253   if (NewST.getNode())
11254     return NewST;
11255
11256   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11257                                                   : DAG.getSubtarget().useAA();
11258 #ifndef NDEBUG
11259   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11260       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11261     UseAA = false;
11262 #endif
11263   if (UseAA && ST->isUnindexed()) {
11264     // Walk up chain skipping non-aliasing memory nodes.
11265     SDValue BetterChain = FindBetterChain(N, Chain);
11266
11267     // If there is a better chain.
11268     if (Chain != BetterChain) {
11269       SDValue ReplStore;
11270
11271       // Replace the chain to avoid dependency.
11272       if (ST->isTruncatingStore()) {
11273         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11274                                       ST->getMemoryVT(), ST->getMemOperand());
11275       } else {
11276         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11277                                  ST->getMemOperand());
11278       }
11279
11280       // Create token to keep both nodes around.
11281       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11282                                   MVT::Other, Chain, ReplStore);
11283
11284       // Make sure the new and old chains are cleaned up.
11285       AddToWorklist(Token.getNode());
11286
11287       // Don't add users to work list.
11288       return CombineTo(N, Token, false);
11289     }
11290   }
11291
11292   // Try transforming N to an indexed store.
11293   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11294     return SDValue(N, 0);
11295
11296   // FIXME: is there such a thing as a truncating indexed store?
11297   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11298       Value.getValueType().isInteger()) {
11299     // See if we can simplify the input to this truncstore with knowledge that
11300     // only the low bits are being used.  For example:
11301     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11302     SDValue Shorter =
11303       GetDemandedBits(Value,
11304                       APInt::getLowBitsSet(
11305                         Value.getValueType().getScalarType().getSizeInBits(),
11306                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11307     AddToWorklist(Value.getNode());
11308     if (Shorter.getNode())
11309       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11310                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11311
11312     // Otherwise, see if we can simplify the operation with
11313     // SimplifyDemandedBits, which only works if the value has a single use.
11314     if (SimplifyDemandedBits(Value,
11315                         APInt::getLowBitsSet(
11316                           Value.getValueType().getScalarType().getSizeInBits(),
11317                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11318       return SDValue(N, 0);
11319   }
11320
11321   // If this is a load followed by a store to the same location, then the store
11322   // is dead/noop.
11323   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11324     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11325         ST->isUnindexed() && !ST->isVolatile() &&
11326         // There can't be any side effects between the load and store, such as
11327         // a call or store.
11328         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11329       // The store is dead, remove it.
11330       return Chain;
11331     }
11332   }
11333
11334   // If this is a store followed by a store with the same value to the same
11335   // location, then the store is dead/noop.
11336   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11337     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11338         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11339         ST1->isUnindexed() && !ST1->isVolatile()) {
11340       // The store is dead, remove it.
11341       return Chain;
11342     }
11343   }
11344
11345   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11346   // truncating store.  We can do this even if this is already a truncstore.
11347   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11348       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11349       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11350                             ST->getMemoryVT())) {
11351     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11352                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11353   }
11354
11355   // Only perform this optimization before the types are legal, because we
11356   // don't want to perform this optimization on every DAGCombine invocation.
11357   if (!LegalTypes) {
11358     bool EverChanged = false;
11359
11360     do {
11361       // There can be multiple store sequences on the same chain.
11362       // Keep trying to merge store sequences until we are unable to do so
11363       // or until we merge the last store on the chain.
11364       bool Changed = MergeConsecutiveStores(ST);
11365       EverChanged |= Changed;
11366       if (!Changed) break;
11367     } while (ST->getOpcode() != ISD::DELETED_NODE);
11368
11369     if (EverChanged)
11370       return SDValue(N, 0);
11371   }
11372
11373   return ReduceLoadOpStoreWidth(N);
11374 }
11375
11376 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11377   SDValue InVec = N->getOperand(0);
11378   SDValue InVal = N->getOperand(1);
11379   SDValue EltNo = N->getOperand(2);
11380   SDLoc dl(N);
11381
11382   // If the inserted element is an UNDEF, just use the input vector.
11383   if (InVal.getOpcode() == ISD::UNDEF)
11384     return InVec;
11385
11386   EVT VT = InVec.getValueType();
11387
11388   // If we can't generate a legal BUILD_VECTOR, exit
11389   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11390     return SDValue();
11391
11392   // Check that we know which element is being inserted
11393   if (!isa<ConstantSDNode>(EltNo))
11394     return SDValue();
11395   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11396
11397   // Canonicalize insert_vector_elt dag nodes.
11398   // Example:
11399   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11400   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11401   //
11402   // Do this only if the child insert_vector node has one use; also
11403   // do this only if indices are both constants and Idx1 < Idx0.
11404   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11405       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11406     unsigned OtherElt =
11407       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11408     if (Elt < OtherElt) {
11409       // Swap nodes.
11410       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11411                                   InVec.getOperand(0), InVal, EltNo);
11412       AddToWorklist(NewOp.getNode());
11413       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11414                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11415     }
11416   }
11417
11418   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11419   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11420   // vector elements.
11421   SmallVector<SDValue, 8> Ops;
11422   // Do not combine these two vectors if the output vector will not replace
11423   // the input vector.
11424   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11425     Ops.append(InVec.getNode()->op_begin(),
11426                InVec.getNode()->op_end());
11427   } else if (InVec.getOpcode() == ISD::UNDEF) {
11428     unsigned NElts = VT.getVectorNumElements();
11429     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11430   } else {
11431     return SDValue();
11432   }
11433
11434   // Insert the element
11435   if (Elt < Ops.size()) {
11436     // All the operands of BUILD_VECTOR must have the same type;
11437     // we enforce that here.
11438     EVT OpVT = Ops[0].getValueType();
11439     if (InVal.getValueType() != OpVT)
11440       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11441                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11442                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11443     Ops[Elt] = InVal;
11444   }
11445
11446   // Return the new vector
11447   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11448 }
11449
11450 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11451     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11452   EVT ResultVT = EVE->getValueType(0);
11453   EVT VecEltVT = InVecVT.getVectorElementType();
11454   unsigned Align = OriginalLoad->getAlignment();
11455   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11456       VecEltVT.getTypeForEVT(*DAG.getContext()));
11457
11458   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11459     return SDValue();
11460
11461   Align = NewAlign;
11462
11463   SDValue NewPtr = OriginalLoad->getBasePtr();
11464   SDValue Offset;
11465   EVT PtrType = NewPtr.getValueType();
11466   MachinePointerInfo MPI;
11467   SDLoc DL(EVE);
11468   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11469     int Elt = ConstEltNo->getZExtValue();
11470     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11471     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11472     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11473   } else {
11474     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11475     Offset = DAG.getNode(
11476         ISD::MUL, DL, PtrType, Offset,
11477         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11478     MPI = OriginalLoad->getPointerInfo();
11479   }
11480   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11481
11482   // The replacement we need to do here is a little tricky: we need to
11483   // replace an extractelement of a load with a load.
11484   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11485   // Note that this replacement assumes that the extractvalue is the only
11486   // use of the load; that's okay because we don't want to perform this
11487   // transformation in other cases anyway.
11488   SDValue Load;
11489   SDValue Chain;
11490   if (ResultVT.bitsGT(VecEltVT)) {
11491     // If the result type of vextract is wider than the load, then issue an
11492     // extending load instead.
11493     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11494                                                   VecEltVT)
11495                                    ? ISD::ZEXTLOAD
11496                                    : ISD::EXTLOAD;
11497     Load = DAG.getExtLoad(
11498         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11499         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11500         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11501     Chain = Load.getValue(1);
11502   } else {
11503     Load = DAG.getLoad(
11504         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11505         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11506         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11507     Chain = Load.getValue(1);
11508     if (ResultVT.bitsLT(VecEltVT))
11509       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11510     else
11511       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11512   }
11513   WorklistRemover DeadNodes(*this);
11514   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11515   SDValue To[] = { Load, Chain };
11516   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11517   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11518   // worklist explicitly as well.
11519   AddToWorklist(Load.getNode());
11520   AddUsersToWorklist(Load.getNode()); // Add users too
11521   // Make sure to revisit this node to clean it up; it will usually be dead.
11522   AddToWorklist(EVE);
11523   ++OpsNarrowed;
11524   return SDValue(EVE, 0);
11525 }
11526
11527 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11528   // (vextract (scalar_to_vector val, 0) -> val
11529   SDValue InVec = N->getOperand(0);
11530   EVT VT = InVec.getValueType();
11531   EVT NVT = N->getValueType(0);
11532
11533   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11534     // Check if the result type doesn't match the inserted element type. A
11535     // SCALAR_TO_VECTOR may truncate the inserted element and the
11536     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11537     SDValue InOp = InVec.getOperand(0);
11538     if (InOp.getValueType() != NVT) {
11539       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11540       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11541     }
11542     return InOp;
11543   }
11544
11545   SDValue EltNo = N->getOperand(1);
11546   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11547
11548   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11549   // We only perform this optimization before the op legalization phase because
11550   // we may introduce new vector instructions which are not backed by TD
11551   // patterns. For example on AVX, extracting elements from a wide vector
11552   // without using extract_subvector. However, if we can find an underlying
11553   // scalar value, then we can always use that.
11554   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11555       && ConstEltNo) {
11556     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11557     int NumElem = VT.getVectorNumElements();
11558     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11559     // Find the new index to extract from.
11560     int OrigElt = SVOp->getMaskElt(Elt);
11561
11562     // Extracting an undef index is undef.
11563     if (OrigElt == -1)
11564       return DAG.getUNDEF(NVT);
11565
11566     // Select the right vector half to extract from.
11567     SDValue SVInVec;
11568     if (OrigElt < NumElem) {
11569       SVInVec = InVec->getOperand(0);
11570     } else {
11571       SVInVec = InVec->getOperand(1);
11572       OrigElt -= NumElem;
11573     }
11574
11575     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11576       SDValue InOp = SVInVec.getOperand(OrigElt);
11577       if (InOp.getValueType() != NVT) {
11578         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11579         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11580       }
11581
11582       return InOp;
11583     }
11584
11585     // FIXME: We should handle recursing on other vector shuffles and
11586     // scalar_to_vector here as well.
11587
11588     if (!LegalOperations) {
11589       EVT IndexTy = TLI.getVectorIdxTy();
11590       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11591                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11592     }
11593   }
11594
11595   bool BCNumEltsChanged = false;
11596   EVT ExtVT = VT.getVectorElementType();
11597   EVT LVT = ExtVT;
11598
11599   // If the result of load has to be truncated, then it's not necessarily
11600   // profitable.
11601   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11602     return SDValue();
11603
11604   if (InVec.getOpcode() == ISD::BITCAST) {
11605     // Don't duplicate a load with other uses.
11606     if (!InVec.hasOneUse())
11607       return SDValue();
11608
11609     EVT BCVT = InVec.getOperand(0).getValueType();
11610     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11611       return SDValue();
11612     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11613       BCNumEltsChanged = true;
11614     InVec = InVec.getOperand(0);
11615     ExtVT = BCVT.getVectorElementType();
11616   }
11617
11618   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11619   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11620       ISD::isNormalLoad(InVec.getNode()) &&
11621       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11622     SDValue Index = N->getOperand(1);
11623     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11624       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11625                                                            OrigLoad);
11626   }
11627
11628   // Perform only after legalization to ensure build_vector / vector_shuffle
11629   // optimizations have already been done.
11630   if (!LegalOperations) return SDValue();
11631
11632   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11633   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11634   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11635
11636   if (ConstEltNo) {
11637     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11638
11639     LoadSDNode *LN0 = nullptr;
11640     const ShuffleVectorSDNode *SVN = nullptr;
11641     if (ISD::isNormalLoad(InVec.getNode())) {
11642       LN0 = cast<LoadSDNode>(InVec);
11643     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11644                InVec.getOperand(0).getValueType() == ExtVT &&
11645                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11646       // Don't duplicate a load with other uses.
11647       if (!InVec.hasOneUse())
11648         return SDValue();
11649
11650       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11651     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11652       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11653       // =>
11654       // (load $addr+1*size)
11655
11656       // Don't duplicate a load with other uses.
11657       if (!InVec.hasOneUse())
11658         return SDValue();
11659
11660       // If the bit convert changed the number of elements, it is unsafe
11661       // to examine the mask.
11662       if (BCNumEltsChanged)
11663         return SDValue();
11664
11665       // Select the input vector, guarding against out of range extract vector.
11666       unsigned NumElems = VT.getVectorNumElements();
11667       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11668       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11669
11670       if (InVec.getOpcode() == ISD::BITCAST) {
11671         // Don't duplicate a load with other uses.
11672         if (!InVec.hasOneUse())
11673           return SDValue();
11674
11675         InVec = InVec.getOperand(0);
11676       }
11677       if (ISD::isNormalLoad(InVec.getNode())) {
11678         LN0 = cast<LoadSDNode>(InVec);
11679         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11680         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11681       }
11682     }
11683
11684     // Make sure we found a non-volatile load and the extractelement is
11685     // the only use.
11686     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11687       return SDValue();
11688
11689     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11690     if (Elt == -1)
11691       return DAG.getUNDEF(LVT);
11692
11693     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11694   }
11695
11696   return SDValue();
11697 }
11698
11699 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11700 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11701   // We perform this optimization post type-legalization because
11702   // the type-legalizer often scalarizes integer-promoted vectors.
11703   // Performing this optimization before may create bit-casts which
11704   // will be type-legalized to complex code sequences.
11705   // We perform this optimization only before the operation legalizer because we
11706   // may introduce illegal operations.
11707   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11708     return SDValue();
11709
11710   unsigned NumInScalars = N->getNumOperands();
11711   SDLoc dl(N);
11712   EVT VT = N->getValueType(0);
11713
11714   // Check to see if this is a BUILD_VECTOR of a bunch of values
11715   // which come from any_extend or zero_extend nodes. If so, we can create
11716   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11717   // optimizations. We do not handle sign-extend because we can't fill the sign
11718   // using shuffles.
11719   EVT SourceType = MVT::Other;
11720   bool AllAnyExt = true;
11721
11722   for (unsigned i = 0; i != NumInScalars; ++i) {
11723     SDValue In = N->getOperand(i);
11724     // Ignore undef inputs.
11725     if (In.getOpcode() == ISD::UNDEF) continue;
11726
11727     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11728     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11729
11730     // Abort if the element is not an extension.
11731     if (!ZeroExt && !AnyExt) {
11732       SourceType = MVT::Other;
11733       break;
11734     }
11735
11736     // The input is a ZeroExt or AnyExt. Check the original type.
11737     EVT InTy = In.getOperand(0).getValueType();
11738
11739     // Check that all of the widened source types are the same.
11740     if (SourceType == MVT::Other)
11741       // First time.
11742       SourceType = InTy;
11743     else if (InTy != SourceType) {
11744       // Multiple income types. Abort.
11745       SourceType = MVT::Other;
11746       break;
11747     }
11748
11749     // Check if all of the extends are ANY_EXTENDs.
11750     AllAnyExt &= AnyExt;
11751   }
11752
11753   // In order to have valid types, all of the inputs must be extended from the
11754   // same source type and all of the inputs must be any or zero extend.
11755   // Scalar sizes must be a power of two.
11756   EVT OutScalarTy = VT.getScalarType();
11757   bool ValidTypes = SourceType != MVT::Other &&
11758                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11759                  isPowerOf2_32(SourceType.getSizeInBits());
11760
11761   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11762   // turn into a single shuffle instruction.
11763   if (!ValidTypes)
11764     return SDValue();
11765
11766   bool isLE = TLI.isLittleEndian();
11767   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11768   assert(ElemRatio > 1 && "Invalid element size ratio");
11769   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11770                                DAG.getConstant(0, SDLoc(N), SourceType);
11771
11772   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11773   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11774
11775   // Populate the new build_vector
11776   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11777     SDValue Cast = N->getOperand(i);
11778     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11779             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11780             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11781     SDValue In;
11782     if (Cast.getOpcode() == ISD::UNDEF)
11783       In = DAG.getUNDEF(SourceType);
11784     else
11785       In = Cast->getOperand(0);
11786     unsigned Index = isLE ? (i * ElemRatio) :
11787                             (i * ElemRatio + (ElemRatio - 1));
11788
11789     assert(Index < Ops.size() && "Invalid index");
11790     Ops[Index] = In;
11791   }
11792
11793   // The type of the new BUILD_VECTOR node.
11794   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11795   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11796          "Invalid vector size");
11797   // Check if the new vector type is legal.
11798   if (!isTypeLegal(VecVT)) return SDValue();
11799
11800   // Make the new BUILD_VECTOR.
11801   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11802
11803   // The new BUILD_VECTOR node has the potential to be further optimized.
11804   AddToWorklist(BV.getNode());
11805   // Bitcast to the desired type.
11806   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11807 }
11808
11809 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11810   EVT VT = N->getValueType(0);
11811
11812   unsigned NumInScalars = N->getNumOperands();
11813   SDLoc dl(N);
11814
11815   EVT SrcVT = MVT::Other;
11816   unsigned Opcode = ISD::DELETED_NODE;
11817   unsigned NumDefs = 0;
11818
11819   for (unsigned i = 0; i != NumInScalars; ++i) {
11820     SDValue In = N->getOperand(i);
11821     unsigned Opc = In.getOpcode();
11822
11823     if (Opc == ISD::UNDEF)
11824       continue;
11825
11826     // If all scalar values are floats and converted from integers.
11827     if (Opcode == ISD::DELETED_NODE &&
11828         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11829       Opcode = Opc;
11830     }
11831
11832     if (Opc != Opcode)
11833       return SDValue();
11834
11835     EVT InVT = In.getOperand(0).getValueType();
11836
11837     // If all scalar values are typed differently, bail out. It's chosen to
11838     // simplify BUILD_VECTOR of integer types.
11839     if (SrcVT == MVT::Other)
11840       SrcVT = InVT;
11841     if (SrcVT != InVT)
11842       return SDValue();
11843     NumDefs++;
11844   }
11845
11846   // If the vector has just one element defined, it's not worth to fold it into
11847   // a vectorized one.
11848   if (NumDefs < 2)
11849     return SDValue();
11850
11851   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11852          && "Should only handle conversion from integer to float.");
11853   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11854
11855   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11856
11857   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11858     return SDValue();
11859
11860   // Just because the floating-point vector type is legal does not necessarily
11861   // mean that the corresponding integer vector type is.
11862   if (!isTypeLegal(NVT))
11863     return SDValue();
11864
11865   SmallVector<SDValue, 8> Opnds;
11866   for (unsigned i = 0; i != NumInScalars; ++i) {
11867     SDValue In = N->getOperand(i);
11868
11869     if (In.getOpcode() == ISD::UNDEF)
11870       Opnds.push_back(DAG.getUNDEF(SrcVT));
11871     else
11872       Opnds.push_back(In.getOperand(0));
11873   }
11874   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11875   AddToWorklist(BV.getNode());
11876
11877   return DAG.getNode(Opcode, dl, VT, BV);
11878 }
11879
11880 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11881   unsigned NumInScalars = N->getNumOperands();
11882   SDLoc dl(N);
11883   EVT VT = N->getValueType(0);
11884
11885   // A vector built entirely of undefs is undef.
11886   if (ISD::allOperandsUndef(N))
11887     return DAG.getUNDEF(VT);
11888
11889   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11890     return V;
11891
11892   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11893     return V;
11894
11895   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11896   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11897   // at most two distinct vectors, turn this into a shuffle node.
11898
11899   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11900   if (!isTypeLegal(VT))
11901     return SDValue();
11902
11903   // May only combine to shuffle after legalize if shuffle is legal.
11904   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11905     return SDValue();
11906
11907   SDValue VecIn1, VecIn2;
11908   bool UsesZeroVector = false;
11909   for (unsigned i = 0; i != NumInScalars; ++i) {
11910     SDValue Op = N->getOperand(i);
11911     // Ignore undef inputs.
11912     if (Op.getOpcode() == ISD::UNDEF) continue;
11913
11914     // See if we can combine this build_vector into a blend with a zero vector.
11915     if (!VecIn2.getNode() && (isNullConstant(Op) ||
11916         (Op.getOpcode() == ISD::ConstantFP &&
11917         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11918       UsesZeroVector = true;
11919       continue;
11920     }
11921
11922     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11923     // constant index, bail out.
11924     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11925         !isa<ConstantSDNode>(Op.getOperand(1))) {
11926       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11927       break;
11928     }
11929
11930     // We allow up to two distinct input vectors.
11931     SDValue ExtractedFromVec = Op.getOperand(0);
11932     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11933       continue;
11934
11935     if (!VecIn1.getNode()) {
11936       VecIn1 = ExtractedFromVec;
11937     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11938       VecIn2 = ExtractedFromVec;
11939     } else {
11940       // Too many inputs.
11941       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11942       break;
11943     }
11944   }
11945
11946   // If everything is good, we can make a shuffle operation.
11947   if (VecIn1.getNode()) {
11948     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11949     SmallVector<int, 8> Mask;
11950     for (unsigned i = 0; i != NumInScalars; ++i) {
11951       unsigned Opcode = N->getOperand(i).getOpcode();
11952       if (Opcode == ISD::UNDEF) {
11953         Mask.push_back(-1);
11954         continue;
11955       }
11956
11957       // Operands can also be zero.
11958       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11959         assert(UsesZeroVector &&
11960                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11961                "Unexpected node found!");
11962         Mask.push_back(NumInScalars+i);
11963         continue;
11964       }
11965
11966       // If extracting from the first vector, just use the index directly.
11967       SDValue Extract = N->getOperand(i);
11968       SDValue ExtVal = Extract.getOperand(1);
11969       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11970       if (Extract.getOperand(0) == VecIn1) {
11971         Mask.push_back(ExtIndex);
11972         continue;
11973       }
11974
11975       // Otherwise, use InIdx + InputVecSize
11976       Mask.push_back(InNumElements + ExtIndex);
11977     }
11978
11979     // Avoid introducing illegal shuffles with zero.
11980     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11981       return SDValue();
11982
11983     // We can't generate a shuffle node with mismatched input and output types.
11984     // Attempt to transform a single input vector to the correct type.
11985     if ((VT != VecIn1.getValueType())) {
11986       // If the input vector type has a different base type to the output
11987       // vector type, bail out.
11988       EVT VTElemType = VT.getVectorElementType();
11989       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11990           (VecIn2.getNode() &&
11991            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11992         return SDValue();
11993
11994       // If the input vector is too small, widen it.
11995       // We only support widening of vectors which are half the size of the
11996       // output registers. For example XMM->YMM widening on X86 with AVX.
11997       EVT VecInT = VecIn1.getValueType();
11998       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11999         // If we only have one small input, widen it by adding undef values.
12000         if (!VecIn2.getNode())
12001           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12002                                DAG.getUNDEF(VecIn1.getValueType()));
12003         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12004           // If we have two small inputs of the same type, try to concat them.
12005           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12006           VecIn2 = SDValue(nullptr, 0);
12007         } else
12008           return SDValue();
12009       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12010         // If the input vector is too large, try to split it.
12011         // We don't support having two input vectors that are too large.
12012         // If the zero vector was used, we can not split the vector,
12013         // since we'd need 3 inputs.
12014         if (UsesZeroVector || VecIn2.getNode())
12015           return SDValue();
12016
12017         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12018           return SDValue();
12019
12020         // Try to replace VecIn1 with two extract_subvectors
12021         // No need to update the masks, they should still be correct.
12022         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12023           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12024         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12025           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12026       } else
12027         return SDValue();
12028     }
12029
12030     if (UsesZeroVector)
12031       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12032                                 DAG.getConstantFP(0.0, dl, VT);
12033     else
12034       // If VecIn2 is unused then change it to undef.
12035       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12036
12037     // Check that we were able to transform all incoming values to the same
12038     // type.
12039     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12040         VecIn1.getValueType() != VT)
12041           return SDValue();
12042
12043     // Return the new VECTOR_SHUFFLE node.
12044     SDValue Ops[2];
12045     Ops[0] = VecIn1;
12046     Ops[1] = VecIn2;
12047     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12048   }
12049
12050   return SDValue();
12051 }
12052
12053 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12055   EVT OpVT = N->getOperand(0).getValueType();
12056
12057   // If the operands are legal vectors, leave them alone.
12058   if (TLI.isTypeLegal(OpVT))
12059     return SDValue();
12060
12061   SDLoc DL(N);
12062   EVT VT = N->getValueType(0);
12063   SmallVector<SDValue, 8> Ops;
12064
12065   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12066   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12067
12068   // Keep track of what we encounter.
12069   bool AnyInteger = false;
12070   bool AnyFP = false;
12071   for (const SDValue &Op : N->ops()) {
12072     if (ISD::BITCAST == Op.getOpcode() &&
12073         !Op.getOperand(0).getValueType().isVector())
12074       Ops.push_back(Op.getOperand(0));
12075     else if (ISD::UNDEF == Op.getOpcode())
12076       Ops.push_back(ScalarUndef);
12077     else
12078       return SDValue();
12079
12080     // Note whether we encounter an integer or floating point scalar.
12081     // If it's neither, bail out, it could be something weird like x86mmx.
12082     EVT LastOpVT = Ops.back().getValueType();
12083     if (LastOpVT.isFloatingPoint())
12084       AnyFP = true;
12085     else if (LastOpVT.isInteger())
12086       AnyInteger = true;
12087     else
12088       return SDValue();
12089   }
12090
12091   // If any of the operands is a floating point scalar bitcast to a vector,
12092   // use floating point types throughout, and bitcast everything.  
12093   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12094   if (AnyFP) {
12095     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12096     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12097     if (AnyInteger) {
12098       for (SDValue &Op : Ops) {
12099         if (Op.getValueType() == SVT)
12100           continue;
12101         if (Op.getOpcode() == ISD::UNDEF)
12102           Op = ScalarUndef;
12103         else
12104           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12105       }
12106     }
12107   }
12108
12109   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12110                                VT.getSizeInBits() / SVT.getSizeInBits());
12111   return DAG.getNode(ISD::BITCAST, DL, VT,
12112                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12113 }
12114
12115 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12116   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12117   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12118   // inputs come from at most two distinct vectors, turn this into a shuffle
12119   // node.
12120
12121   // If we only have one input vector, we don't need to do any concatenation.
12122   if (N->getNumOperands() == 1)
12123     return N->getOperand(0);
12124
12125   // Check if all of the operands are undefs.
12126   EVT VT = N->getValueType(0);
12127   if (ISD::allOperandsUndef(N))
12128     return DAG.getUNDEF(VT);
12129
12130   // Optimize concat_vectors where all but the first of the vectors are undef.
12131   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12132         return Op.getOpcode() == ISD::UNDEF;
12133       })) {
12134     SDValue In = N->getOperand(0);
12135     assert(In.getValueType().isVector() && "Must concat vectors");
12136
12137     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12138     if (In->getOpcode() == ISD::BITCAST &&
12139         !In->getOperand(0)->getValueType(0).isVector()) {
12140       SDValue Scalar = In->getOperand(0);
12141
12142       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12143       // look through the trunc so we can still do the transform:
12144       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12145       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12146           !TLI.isTypeLegal(Scalar.getValueType()) &&
12147           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12148         Scalar = Scalar->getOperand(0);
12149
12150       EVT SclTy = Scalar->getValueType(0);
12151
12152       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12153         return SDValue();
12154
12155       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12156                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12157       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12158         return SDValue();
12159
12160       SDLoc dl = SDLoc(N);
12161       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12162       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12163     }
12164   }
12165
12166   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12167   // We have already tested above for an UNDEF only concatenation.
12168   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12169   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12170   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12171     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12172   };
12173   bool AllBuildVectorsOrUndefs =
12174       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12175   if (AllBuildVectorsOrUndefs) {
12176     SmallVector<SDValue, 8> Opnds;
12177     EVT SVT = VT.getScalarType();
12178
12179     EVT MinVT = SVT;
12180     if (!SVT.isFloatingPoint()) {
12181       // If BUILD_VECTOR are from built from integer, they may have different
12182       // operand types. Get the smallest type and truncate all operands to it.
12183       bool FoundMinVT = false;
12184       for (const SDValue &Op : N->ops())
12185         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12186           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12187           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12188           FoundMinVT = true;
12189         }
12190       assert(FoundMinVT && "Concat vector type mismatch");
12191     }
12192
12193     for (const SDValue &Op : N->ops()) {
12194       EVT OpVT = Op.getValueType();
12195       unsigned NumElts = OpVT.getVectorNumElements();
12196
12197       if (ISD::UNDEF == Op.getOpcode())
12198         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12199
12200       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12201         if (SVT.isFloatingPoint()) {
12202           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12203           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12204         } else {
12205           for (unsigned i = 0; i != NumElts; ++i)
12206             Opnds.push_back(
12207                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12208         }
12209       }
12210     }
12211
12212     assert(VT.getVectorNumElements() == Opnds.size() &&
12213            "Concat vector type mismatch");
12214     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12215   }
12216
12217   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12218   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12219     return V;
12220
12221   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12222   // nodes often generate nop CONCAT_VECTOR nodes.
12223   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12224   // place the incoming vectors at the exact same location.
12225   SDValue SingleSource = SDValue();
12226   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12227
12228   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12229     SDValue Op = N->getOperand(i);
12230
12231     if (Op.getOpcode() == ISD::UNDEF)
12232       continue;
12233
12234     // Check if this is the identity extract:
12235     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12236       return SDValue();
12237
12238     // Find the single incoming vector for the extract_subvector.
12239     if (SingleSource.getNode()) {
12240       if (Op.getOperand(0) != SingleSource)
12241         return SDValue();
12242     } else {
12243       SingleSource = Op.getOperand(0);
12244
12245       // Check the source type is the same as the type of the result.
12246       // If not, this concat may extend the vector, so we can not
12247       // optimize it away.
12248       if (SingleSource.getValueType() != N->getValueType(0))
12249         return SDValue();
12250     }
12251
12252     unsigned IdentityIndex = i * PartNumElem;
12253     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12254     // The extract index must be constant.
12255     if (!CS)
12256       return SDValue();
12257
12258     // Check that we are reading from the identity index.
12259     if (CS->getZExtValue() != IdentityIndex)
12260       return SDValue();
12261   }
12262
12263   if (SingleSource.getNode())
12264     return SingleSource;
12265
12266   return SDValue();
12267 }
12268
12269 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12270   EVT NVT = N->getValueType(0);
12271   SDValue V = N->getOperand(0);
12272
12273   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12274     // Combine:
12275     //    (extract_subvec (concat V1, V2, ...), i)
12276     // Into:
12277     //    Vi if possible
12278     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12279     // type.
12280     if (V->getOperand(0).getValueType() != NVT)
12281       return SDValue();
12282     unsigned Idx = N->getConstantOperandVal(1);
12283     unsigned NumElems = NVT.getVectorNumElements();
12284     assert((Idx % NumElems) == 0 &&
12285            "IDX in concat is not a multiple of the result vector length.");
12286     return V->getOperand(Idx / NumElems);
12287   }
12288
12289   // Skip bitcasting
12290   if (V->getOpcode() == ISD::BITCAST)
12291     V = V.getOperand(0);
12292
12293   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12294     SDLoc dl(N);
12295     // Handle only simple case where vector being inserted and vector
12296     // being extracted are of same type, and are half size of larger vectors.
12297     EVT BigVT = V->getOperand(0).getValueType();
12298     EVT SmallVT = V->getOperand(1).getValueType();
12299     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12300       return SDValue();
12301
12302     // Only handle cases where both indexes are constants with the same type.
12303     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12304     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12305
12306     if (InsIdx && ExtIdx &&
12307         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12308         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12309       // Combine:
12310       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12311       // Into:
12312       //    indices are equal or bit offsets are equal => V1
12313       //    otherwise => (extract_subvec V1, ExtIdx)
12314       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12315           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12316         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12317       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12318                          DAG.getNode(ISD::BITCAST, dl,
12319                                      N->getOperand(0).getValueType(),
12320                                      V->getOperand(0)), N->getOperand(1));
12321     }
12322   }
12323
12324   return SDValue();
12325 }
12326
12327 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12328                                                  SDValue V, SelectionDAG &DAG) {
12329   SDLoc DL(V);
12330   EVT VT = V.getValueType();
12331
12332   switch (V.getOpcode()) {
12333   default:
12334     return V;
12335
12336   case ISD::CONCAT_VECTORS: {
12337     EVT OpVT = V->getOperand(0).getValueType();
12338     int OpSize = OpVT.getVectorNumElements();
12339     SmallBitVector OpUsedElements(OpSize, false);
12340     bool FoundSimplification = false;
12341     SmallVector<SDValue, 4> NewOps;
12342     NewOps.reserve(V->getNumOperands());
12343     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12344       SDValue Op = V->getOperand(i);
12345       bool OpUsed = false;
12346       for (int j = 0; j < OpSize; ++j)
12347         if (UsedElements[i * OpSize + j]) {
12348           OpUsedElements[j] = true;
12349           OpUsed = true;
12350         }
12351       NewOps.push_back(
12352           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12353                  : DAG.getUNDEF(OpVT));
12354       FoundSimplification |= Op == NewOps.back();
12355       OpUsedElements.reset();
12356     }
12357     if (FoundSimplification)
12358       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12359     return V;
12360   }
12361
12362   case ISD::INSERT_SUBVECTOR: {
12363     SDValue BaseV = V->getOperand(0);
12364     SDValue SubV = V->getOperand(1);
12365     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12366     if (!IdxN)
12367       return V;
12368
12369     int SubSize = SubV.getValueType().getVectorNumElements();
12370     int Idx = IdxN->getZExtValue();
12371     bool SubVectorUsed = false;
12372     SmallBitVector SubUsedElements(SubSize, false);
12373     for (int i = 0; i < SubSize; ++i)
12374       if (UsedElements[i + Idx]) {
12375         SubVectorUsed = true;
12376         SubUsedElements[i] = true;
12377         UsedElements[i + Idx] = false;
12378       }
12379
12380     // Now recurse on both the base and sub vectors.
12381     SDValue SimplifiedSubV =
12382         SubVectorUsed
12383             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12384             : DAG.getUNDEF(SubV.getValueType());
12385     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12386     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12387       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12388                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12389     return V;
12390   }
12391   }
12392 }
12393
12394 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12395                                        SDValue N1, SelectionDAG &DAG) {
12396   EVT VT = SVN->getValueType(0);
12397   int NumElts = VT.getVectorNumElements();
12398   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12399   for (int M : SVN->getMask())
12400     if (M >= 0 && M < NumElts)
12401       N0UsedElements[M] = true;
12402     else if (M >= NumElts)
12403       N1UsedElements[M - NumElts] = true;
12404
12405   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12406   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12407   if (S0 == N0 && S1 == N1)
12408     return SDValue();
12409
12410   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12411 }
12412
12413 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12414 // or turn a shuffle of a single concat into simpler shuffle then concat.
12415 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12416   EVT VT = N->getValueType(0);
12417   unsigned NumElts = VT.getVectorNumElements();
12418
12419   SDValue N0 = N->getOperand(0);
12420   SDValue N1 = N->getOperand(1);
12421   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12422
12423   SmallVector<SDValue, 4> Ops;
12424   EVT ConcatVT = N0.getOperand(0).getValueType();
12425   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12426   unsigned NumConcats = NumElts / NumElemsPerConcat;
12427
12428   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12429   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12430   // half vector elements.
12431   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12432       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12433                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12434     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12435                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12436     N1 = DAG.getUNDEF(ConcatVT);
12437     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12438   }
12439
12440   // Look at every vector that's inserted. We're looking for exact
12441   // subvector-sized copies from a concatenated vector
12442   for (unsigned I = 0; I != NumConcats; ++I) {
12443     // Make sure we're dealing with a copy.
12444     unsigned Begin = I * NumElemsPerConcat;
12445     bool AllUndef = true, NoUndef = true;
12446     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12447       if (SVN->getMaskElt(J) >= 0)
12448         AllUndef = false;
12449       else
12450         NoUndef = false;
12451     }
12452
12453     if (NoUndef) {
12454       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12455         return SDValue();
12456
12457       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12458         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12459           return SDValue();
12460
12461       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12462       if (FirstElt < N0.getNumOperands())
12463         Ops.push_back(N0.getOperand(FirstElt));
12464       else
12465         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12466
12467     } else if (AllUndef) {
12468       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12469     } else { // Mixed with general masks and undefs, can't do optimization.
12470       return SDValue();
12471     }
12472   }
12473
12474   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12475 }
12476
12477 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12478   EVT VT = N->getValueType(0);
12479   unsigned NumElts = VT.getVectorNumElements();
12480
12481   SDValue N0 = N->getOperand(0);
12482   SDValue N1 = N->getOperand(1);
12483
12484   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12485
12486   // Canonicalize shuffle undef, undef -> undef
12487   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12488     return DAG.getUNDEF(VT);
12489
12490   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12491
12492   // Canonicalize shuffle v, v -> v, undef
12493   if (N0 == N1) {
12494     SmallVector<int, 8> NewMask;
12495     for (unsigned i = 0; i != NumElts; ++i) {
12496       int Idx = SVN->getMaskElt(i);
12497       if (Idx >= (int)NumElts) Idx -= NumElts;
12498       NewMask.push_back(Idx);
12499     }
12500     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12501                                 &NewMask[0]);
12502   }
12503
12504   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12505   if (N0.getOpcode() == ISD::UNDEF) {
12506     SmallVector<int, 8> NewMask;
12507     for (unsigned i = 0; i != NumElts; ++i) {
12508       int Idx = SVN->getMaskElt(i);
12509       if (Idx >= 0) {
12510         if (Idx >= (int)NumElts)
12511           Idx -= NumElts;
12512         else
12513           Idx = -1; // remove reference to lhs
12514       }
12515       NewMask.push_back(Idx);
12516     }
12517     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12518                                 &NewMask[0]);
12519   }
12520
12521   // Remove references to rhs if it is undef
12522   if (N1.getOpcode() == ISD::UNDEF) {
12523     bool Changed = false;
12524     SmallVector<int, 8> NewMask;
12525     for (unsigned i = 0; i != NumElts; ++i) {
12526       int Idx = SVN->getMaskElt(i);
12527       if (Idx >= (int)NumElts) {
12528         Idx = -1;
12529         Changed = true;
12530       }
12531       NewMask.push_back(Idx);
12532     }
12533     if (Changed)
12534       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12535   }
12536
12537   // If it is a splat, check if the argument vector is another splat or a
12538   // build_vector.
12539   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12540     SDNode *V = N0.getNode();
12541
12542     // If this is a bit convert that changes the element type of the vector but
12543     // not the number of vector elements, look through it.  Be careful not to
12544     // look though conversions that change things like v4f32 to v2f64.
12545     if (V->getOpcode() == ISD::BITCAST) {
12546       SDValue ConvInput = V->getOperand(0);
12547       if (ConvInput.getValueType().isVector() &&
12548           ConvInput.getValueType().getVectorNumElements() == NumElts)
12549         V = ConvInput.getNode();
12550     }
12551
12552     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12553       assert(V->getNumOperands() == NumElts &&
12554              "BUILD_VECTOR has wrong number of operands");
12555       SDValue Base;
12556       bool AllSame = true;
12557       for (unsigned i = 0; i != NumElts; ++i) {
12558         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12559           Base = V->getOperand(i);
12560           break;
12561         }
12562       }
12563       // Splat of <u, u, u, u>, return <u, u, u, u>
12564       if (!Base.getNode())
12565         return N0;
12566       for (unsigned i = 0; i != NumElts; ++i) {
12567         if (V->getOperand(i) != Base) {
12568           AllSame = false;
12569           break;
12570         }
12571       }
12572       // Splat of <x, x, x, x>, return <x, x, x, x>
12573       if (AllSame)
12574         return N0;
12575
12576       // Canonicalize any other splat as a build_vector.
12577       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12578       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12579       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12580                                   V->getValueType(0), Ops);
12581
12582       // We may have jumped through bitcasts, so the type of the
12583       // BUILD_VECTOR may not match the type of the shuffle.
12584       if (V->getValueType(0) != VT)
12585         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12586       return NewBV;
12587     }
12588   }
12589
12590   // There are various patterns used to build up a vector from smaller vectors,
12591   // subvectors, or elements. Scan chains of these and replace unused insertions
12592   // or components with undef.
12593   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12594     return S;
12595
12596   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12597       Level < AfterLegalizeVectorOps &&
12598       (N1.getOpcode() == ISD::UNDEF ||
12599       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12600        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12601     SDValue V = partitionShuffleOfConcats(N, DAG);
12602
12603     if (V.getNode())
12604       return V;
12605   }
12606
12607   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12608   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12609   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12610     SmallVector<SDValue, 8> Ops;
12611     for (int M : SVN->getMask()) {
12612       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12613       if (M >= 0) {
12614         int Idx = M % NumElts;
12615         SDValue &S = (M < (int)NumElts ? N0 : N1);
12616         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12617           Op = S.getOperand(Idx);
12618         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12619           if (Idx == 0)
12620             Op = S.getOperand(0);
12621         } else {
12622           // Operand can't be combined - bail out.
12623           break;
12624         }
12625       }
12626       Ops.push_back(Op);
12627     }
12628     if (Ops.size() == VT.getVectorNumElements()) {
12629       // BUILD_VECTOR requires all inputs to be of the same type, find the
12630       // maximum type and extend them all.
12631       EVT SVT = VT.getScalarType();
12632       if (SVT.isInteger())
12633         for (SDValue &Op : Ops)
12634           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12635       if (SVT != VT.getScalarType())
12636         for (SDValue &Op : Ops)
12637           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12638                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12639                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12640       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12641     }
12642   }
12643
12644   // If this shuffle only has a single input that is a bitcasted shuffle,
12645   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12646   // back to their original types.
12647   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12648       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12649       TLI.isTypeLegal(VT)) {
12650
12651     // Peek through the bitcast only if there is one user.
12652     SDValue BC0 = N0;
12653     while (BC0.getOpcode() == ISD::BITCAST) {
12654       if (!BC0.hasOneUse())
12655         break;
12656       BC0 = BC0.getOperand(0);
12657     }
12658
12659     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12660       if (Scale == 1)
12661         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12662
12663       SmallVector<int, 8> NewMask;
12664       for (int M : Mask)
12665         for (int s = 0; s != Scale; ++s)
12666           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12667       return NewMask;
12668     };
12669
12670     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12671       EVT SVT = VT.getScalarType();
12672       EVT InnerVT = BC0->getValueType(0);
12673       EVT InnerSVT = InnerVT.getScalarType();
12674
12675       // Determine which shuffle works with the smaller scalar type.
12676       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12677       EVT ScaleSVT = ScaleVT.getScalarType();
12678
12679       if (TLI.isTypeLegal(ScaleVT) &&
12680           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12681           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12682
12683         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12684         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12685
12686         // Scale the shuffle masks to the smaller scalar type.
12687         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12688         SmallVector<int, 8> InnerMask =
12689             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12690         SmallVector<int, 8> OuterMask =
12691             ScaleShuffleMask(SVN->getMask(), OuterScale);
12692
12693         // Merge the shuffle masks.
12694         SmallVector<int, 8> NewMask;
12695         for (int M : OuterMask)
12696           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12697
12698         // Test for shuffle mask legality over both commutations.
12699         SDValue SV0 = BC0->getOperand(0);
12700         SDValue SV1 = BC0->getOperand(1);
12701         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12702         if (!LegalMask) {
12703           std::swap(SV0, SV1);
12704           ShuffleVectorSDNode::commuteMask(NewMask);
12705           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12706         }
12707
12708         if (LegalMask) {
12709           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12710           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12711           return DAG.getNode(
12712               ISD::BITCAST, SDLoc(N), VT,
12713               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12714         }
12715       }
12716     }
12717   }
12718
12719   // Canonicalize shuffles according to rules:
12720   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12721   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12722   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12723   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12724       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12725       TLI.isTypeLegal(VT)) {
12726     // The incoming shuffle must be of the same type as the result of the
12727     // current shuffle.
12728     assert(N1->getOperand(0).getValueType() == VT &&
12729            "Shuffle types don't match");
12730
12731     SDValue SV0 = N1->getOperand(0);
12732     SDValue SV1 = N1->getOperand(1);
12733     bool HasSameOp0 = N0 == SV0;
12734     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12735     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12736       // Commute the operands of this shuffle so that next rule
12737       // will trigger.
12738       return DAG.getCommutedVectorShuffle(*SVN);
12739   }
12740
12741   // Try to fold according to rules:
12742   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12743   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12744   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12745   // Don't try to fold shuffles with illegal type.
12746   // Only fold if this shuffle is the only user of the other shuffle.
12747   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12748       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12749     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12750
12751     // The incoming shuffle must be of the same type as the result of the
12752     // current shuffle.
12753     assert(OtherSV->getOperand(0).getValueType() == VT &&
12754            "Shuffle types don't match");
12755
12756     SDValue SV0, SV1;
12757     SmallVector<int, 4> Mask;
12758     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12759     // operand, and SV1 as the second operand.
12760     for (unsigned i = 0; i != NumElts; ++i) {
12761       int Idx = SVN->getMaskElt(i);
12762       if (Idx < 0) {
12763         // Propagate Undef.
12764         Mask.push_back(Idx);
12765         continue;
12766       }
12767
12768       SDValue CurrentVec;
12769       if (Idx < (int)NumElts) {
12770         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12771         // shuffle mask to identify which vector is actually referenced.
12772         Idx = OtherSV->getMaskElt(Idx);
12773         if (Idx < 0) {
12774           // Propagate Undef.
12775           Mask.push_back(Idx);
12776           continue;
12777         }
12778
12779         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12780                                            : OtherSV->getOperand(1);
12781       } else {
12782         // This shuffle index references an element within N1.
12783         CurrentVec = N1;
12784       }
12785
12786       // Simple case where 'CurrentVec' is UNDEF.
12787       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12788         Mask.push_back(-1);
12789         continue;
12790       }
12791
12792       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12793       // will be the first or second operand of the combined shuffle.
12794       Idx = Idx % NumElts;
12795       if (!SV0.getNode() || SV0 == CurrentVec) {
12796         // Ok. CurrentVec is the left hand side.
12797         // Update the mask accordingly.
12798         SV0 = CurrentVec;
12799         Mask.push_back(Idx);
12800         continue;
12801       }
12802
12803       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12804       if (SV1.getNode() && SV1 != CurrentVec)
12805         return SDValue();
12806
12807       // Ok. CurrentVec is the right hand side.
12808       // Update the mask accordingly.
12809       SV1 = CurrentVec;
12810       Mask.push_back(Idx + NumElts);
12811     }
12812
12813     // Check if all indices in Mask are Undef. In case, propagate Undef.
12814     bool isUndefMask = true;
12815     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12816       isUndefMask &= Mask[i] < 0;
12817
12818     if (isUndefMask)
12819       return DAG.getUNDEF(VT);
12820
12821     if (!SV0.getNode())
12822       SV0 = DAG.getUNDEF(VT);
12823     if (!SV1.getNode())
12824       SV1 = DAG.getUNDEF(VT);
12825
12826     // Avoid introducing shuffles with illegal mask.
12827     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12828       ShuffleVectorSDNode::commuteMask(Mask);
12829
12830       if (!TLI.isShuffleMaskLegal(Mask, VT))
12831         return SDValue();
12832
12833       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12834       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12835       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12836       std::swap(SV0, SV1);
12837     }
12838
12839     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12840     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12841     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12842     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12843   }
12844
12845   return SDValue();
12846 }
12847
12848 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12849   SDValue InVal = N->getOperand(0);
12850   EVT VT = N->getValueType(0);
12851
12852   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12853   // with a VECTOR_SHUFFLE.
12854   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12855     SDValue InVec = InVal->getOperand(0);
12856     SDValue EltNo = InVal->getOperand(1);
12857
12858     // FIXME: We could support implicit truncation if the shuffle can be
12859     // scaled to a smaller vector scalar type.
12860     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12861     if (C0 && VT == InVec.getValueType() &&
12862         VT.getScalarType() == InVal.getValueType()) {
12863       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12864       int Elt = C0->getZExtValue();
12865       NewMask[0] = Elt;
12866
12867       if (TLI.isShuffleMaskLegal(NewMask, VT))
12868         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12869                                     NewMask);
12870     }
12871   }
12872
12873   return SDValue();
12874 }
12875
12876 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12877   SDValue N0 = N->getOperand(0);
12878   SDValue N2 = N->getOperand(2);
12879
12880   // If the input vector is a concatenation, and the insert replaces
12881   // one of the halves, we can optimize into a single concat_vectors.
12882   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12883       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12884     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12885     EVT VT = N->getValueType(0);
12886
12887     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12888     // (concat_vectors Z, Y)
12889     if (InsIdx == 0)
12890       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12891                          N->getOperand(1), N0.getOperand(1));
12892
12893     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12894     // (concat_vectors X, Z)
12895     if (InsIdx == VT.getVectorNumElements()/2)
12896       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12897                          N0.getOperand(0), N->getOperand(1));
12898   }
12899
12900   return SDValue();
12901 }
12902
12903 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12904   SDValue N0 = N->getOperand(0);
12905
12906   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12907   if (N0->getOpcode() == ISD::FP16_TO_FP)
12908     return N0->getOperand(0);
12909
12910   return SDValue();
12911 }
12912
12913 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12914 /// with the destination vector and a zero vector.
12915 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12916 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12917 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12918   EVT VT = N->getValueType(0);
12919   SDValue LHS = N->getOperand(0);
12920   SDValue RHS = N->getOperand(1);
12921   SDLoc dl(N);
12922
12923   // Make sure we're not running after operation legalization where it 
12924   // may have custom lowered the vector shuffles.
12925   if (LegalOperations)
12926     return SDValue();
12927
12928   if (N->getOpcode() != ISD::AND)
12929     return SDValue();
12930
12931   if (RHS.getOpcode() == ISD::BITCAST)
12932     RHS = RHS.getOperand(0);
12933
12934   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12935     SmallVector<int, 8> Indices;
12936     unsigned NumElts = RHS.getNumOperands();
12937
12938     for (unsigned i = 0; i != NumElts; ++i) {
12939       SDValue Elt = RHS.getOperand(i);
12940       if (isAllOnesConstant(Elt))
12941         Indices.push_back(i);
12942       else if (isNullConstant(Elt))
12943         Indices.push_back(NumElts+i);
12944       else
12945         return SDValue();
12946     }
12947
12948     // Let's see if the target supports this vector_shuffle.
12949     EVT RVT = RHS.getValueType();
12950     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12951       return SDValue();
12952
12953     // Return the new VECTOR_SHUFFLE node.
12954     EVT EltVT = RVT.getVectorElementType();
12955     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12956                                    DAG.getConstant(0, dl, EltVT));
12957     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12958     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12959     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12960     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12961   }
12962
12963   return SDValue();
12964 }
12965
12966 /// Visit a binary vector operation, like ADD.
12967 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12968   assert(N->getValueType(0).isVector() &&
12969          "SimplifyVBinOp only works on vectors!");
12970
12971   SDValue LHS = N->getOperand(0);
12972   SDValue RHS = N->getOperand(1);
12973
12974   if (SDValue Shuffle = XformToShuffleWithZero(N))
12975     return Shuffle;
12976
12977   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12978   // this operation.
12979   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12980       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12981     // Check if both vectors are constants. If not bail out.
12982     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12983           cast<BuildVectorSDNode>(RHS)->isConstant()))
12984       return SDValue();
12985
12986     SmallVector<SDValue, 8> Ops;
12987     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12988       SDValue LHSOp = LHS.getOperand(i);
12989       SDValue RHSOp = RHS.getOperand(i);
12990
12991       // Can't fold divide by zero.
12992       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12993           N->getOpcode() == ISD::FDIV) {
12994         if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
12995              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12996           break;
12997       }
12998
12999       EVT VT = LHSOp.getValueType();
13000       EVT RVT = RHSOp.getValueType();
13001       if (RVT != VT) {
13002         // Integer BUILD_VECTOR operands may have types larger than the element
13003         // size (e.g., when the element type is not legal).  Prior to type
13004         // legalization, the types may not match between the two BUILD_VECTORS.
13005         // Truncate one of the operands to make them match.
13006         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13007           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13008         } else {
13009           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13010           VT = RVT;
13011         }
13012       }
13013       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13014                                    LHSOp, RHSOp);
13015       if (FoldOp.getOpcode() != ISD::UNDEF &&
13016           FoldOp.getOpcode() != ISD::Constant &&
13017           FoldOp.getOpcode() != ISD::ConstantFP)
13018         break;
13019       Ops.push_back(FoldOp);
13020       AddToWorklist(FoldOp.getNode());
13021     }
13022
13023     if (Ops.size() == LHS.getNumOperands())
13024       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13025   }
13026
13027   // Type legalization might introduce new shuffles in the DAG.
13028   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13029   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13030   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13031       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13032       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13033       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13034     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13035     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13036
13037     if (SVN0->getMask().equals(SVN1->getMask())) {
13038       EVT VT = N->getValueType(0);
13039       SDValue UndefVector = LHS.getOperand(1);
13040       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13041                                      LHS.getOperand(0), RHS.getOperand(0));
13042       AddUsersToWorklist(N);
13043       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13044                                   &SVN0->getMask()[0]);
13045     }
13046   }
13047
13048   return SDValue();
13049 }
13050
13051 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13052                                     SDValue N1, SDValue N2){
13053   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13054
13055   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13056                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13057
13058   // If we got a simplified select_cc node back from SimplifySelectCC, then
13059   // break it down into a new SETCC node, and a new SELECT node, and then return
13060   // the SELECT node, since we were called with a SELECT node.
13061   if (SCC.getNode()) {
13062     // Check to see if we got a select_cc back (to turn into setcc/select).
13063     // Otherwise, just return whatever node we got back, like fabs.
13064     if (SCC.getOpcode() == ISD::SELECT_CC) {
13065       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13066                                   N0.getValueType(),
13067                                   SCC.getOperand(0), SCC.getOperand(1),
13068                                   SCC.getOperand(4));
13069       AddToWorklist(SETCC.getNode());
13070       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13071                            SCC.getOperand(2), SCC.getOperand(3));
13072     }
13073
13074     return SCC;
13075   }
13076   return SDValue();
13077 }
13078
13079 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13080 /// being selected between, see if we can simplify the select.  Callers of this
13081 /// should assume that TheSelect is deleted if this returns true.  As such, they
13082 /// should return the appropriate thing (e.g. the node) back to the top-level of
13083 /// the DAG combiner loop to avoid it being looked at.
13084 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13085                                     SDValue RHS) {
13086
13087   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13088   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13089   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13090     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13091       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13092       SDValue Sqrt = RHS;
13093       ISD::CondCode CC;
13094       SDValue CmpLHS;
13095       const ConstantFPSDNode *NegZero = nullptr;
13096
13097       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13098         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13099         CmpLHS = TheSelect->getOperand(0);
13100         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13101       } else {
13102         // SELECT or VSELECT
13103         SDValue Cmp = TheSelect->getOperand(0);
13104         if (Cmp.getOpcode() == ISD::SETCC) {
13105           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13106           CmpLHS = Cmp.getOperand(0);
13107           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13108         }
13109       }
13110       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13111           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13112           CC == ISD::SETULT || CC == ISD::SETLT)) {
13113         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13114         CombineTo(TheSelect, Sqrt);
13115         return true;
13116       }
13117     }
13118   }
13119   // Cannot simplify select with vector condition
13120   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13121
13122   // If this is a select from two identical things, try to pull the operation
13123   // through the select.
13124   if (LHS.getOpcode() != RHS.getOpcode() ||
13125       !LHS.hasOneUse() || !RHS.hasOneUse())
13126     return false;
13127
13128   // If this is a load and the token chain is identical, replace the select
13129   // of two loads with a load through a select of the address to load from.
13130   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13131   // constants have been dropped into the constant pool.
13132   if (LHS.getOpcode() == ISD::LOAD) {
13133     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13134     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13135
13136     // Token chains must be identical.
13137     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13138         // Do not let this transformation reduce the number of volatile loads.
13139         LLD->isVolatile() || RLD->isVolatile() ||
13140         // FIXME: If either is a pre/post inc/dec load,
13141         // we'd need to split out the address adjustment.
13142         LLD->isIndexed() || RLD->isIndexed() ||
13143         // If this is an EXTLOAD, the VT's must match.
13144         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13145         // If this is an EXTLOAD, the kind of extension must match.
13146         (LLD->getExtensionType() != RLD->getExtensionType() &&
13147          // The only exception is if one of the extensions is anyext.
13148          LLD->getExtensionType() != ISD::EXTLOAD &&
13149          RLD->getExtensionType() != ISD::EXTLOAD) ||
13150         // FIXME: this discards src value information.  This is
13151         // over-conservative. It would be beneficial to be able to remember
13152         // both potential memory locations.  Since we are discarding
13153         // src value info, don't do the transformation if the memory
13154         // locations are not in the default address space.
13155         LLD->getPointerInfo().getAddrSpace() != 0 ||
13156         RLD->getPointerInfo().getAddrSpace() != 0 ||
13157         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13158                                       LLD->getBasePtr().getValueType()))
13159       return false;
13160
13161     // Check that the select condition doesn't reach either load.  If so,
13162     // folding this will induce a cycle into the DAG.  If not, this is safe to
13163     // xform, so create a select of the addresses.
13164     SDValue Addr;
13165     if (TheSelect->getOpcode() == ISD::SELECT) {
13166       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13167       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13168           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13169         return false;
13170       // The loads must not depend on one another.
13171       if (LLD->isPredecessorOf(RLD) ||
13172           RLD->isPredecessorOf(LLD))
13173         return false;
13174       Addr = DAG.getSelect(SDLoc(TheSelect),
13175                            LLD->getBasePtr().getValueType(),
13176                            TheSelect->getOperand(0), LLD->getBasePtr(),
13177                            RLD->getBasePtr());
13178     } else {  // Otherwise SELECT_CC
13179       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13180       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13181
13182       if ((LLD->hasAnyUseOfValue(1) &&
13183            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13184           (RLD->hasAnyUseOfValue(1) &&
13185            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13186         return false;
13187
13188       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13189                          LLD->getBasePtr().getValueType(),
13190                          TheSelect->getOperand(0),
13191                          TheSelect->getOperand(1),
13192                          LLD->getBasePtr(), RLD->getBasePtr(),
13193                          TheSelect->getOperand(4));
13194     }
13195
13196     SDValue Load;
13197     // It is safe to replace the two loads if they have different alignments,
13198     // but the new load must be the minimum (most restrictive) alignment of the
13199     // inputs.
13200     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13201     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13202     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13203       Load = DAG.getLoad(TheSelect->getValueType(0),
13204                          SDLoc(TheSelect),
13205                          // FIXME: Discards pointer and AA info.
13206                          LLD->getChain(), Addr, MachinePointerInfo(),
13207                          LLD->isVolatile(), LLD->isNonTemporal(),
13208                          isInvariant, Alignment);
13209     } else {
13210       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13211                             RLD->getExtensionType() : LLD->getExtensionType(),
13212                             SDLoc(TheSelect),
13213                             TheSelect->getValueType(0),
13214                             // FIXME: Discards pointer and AA info.
13215                             LLD->getChain(), Addr, MachinePointerInfo(),
13216                             LLD->getMemoryVT(), LLD->isVolatile(),
13217                             LLD->isNonTemporal(), isInvariant, Alignment);
13218     }
13219
13220     // Users of the select now use the result of the load.
13221     CombineTo(TheSelect, Load);
13222
13223     // Users of the old loads now use the new load's chain.  We know the
13224     // old-load value is dead now.
13225     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13226     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13227     return true;
13228   }
13229
13230   return false;
13231 }
13232
13233 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13234 /// where 'cond' is the comparison specified by CC.
13235 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13236                                       SDValue N2, SDValue N3,
13237                                       ISD::CondCode CC, bool NotExtCompare) {
13238   // (x ? y : y) -> y.
13239   if (N2 == N3) return N2;
13240
13241   EVT VT = N2.getValueType();
13242   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13243   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13244
13245   // Determine if the condition we're dealing with is constant
13246   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13247                               N0, N1, CC, DL, false);
13248   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13249
13250   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13251     // fold select_cc true, x, y -> x
13252     // fold select_cc false, x, y -> y
13253     return !SCCC->isNullValue() ? N2 : N3;
13254   }
13255
13256   // Check to see if we can simplify the select into an fabs node
13257   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13258     // Allow either -0.0 or 0.0
13259     if (CFP->getValueAPF().isZero()) {
13260       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13261       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13262           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13263           N2 == N3.getOperand(0))
13264         return DAG.getNode(ISD::FABS, DL, VT, N0);
13265
13266       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13267       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13268           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13269           N2.getOperand(0) == N3)
13270         return DAG.getNode(ISD::FABS, DL, VT, N3);
13271     }
13272   }
13273
13274   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13275   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13276   // in it.  This is a win when the constant is not otherwise available because
13277   // it replaces two constant pool loads with one.  We only do this if the FP
13278   // type is known to be legal, because if it isn't, then we are before legalize
13279   // types an we want the other legalization to happen first (e.g. to avoid
13280   // messing with soft float) and if the ConstantFP is not legal, because if
13281   // it is legal, we may not need to store the FP constant in a constant pool.
13282   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13283     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13284       if (TLI.isTypeLegal(N2.getValueType()) &&
13285           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13286                TargetLowering::Legal &&
13287            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13288            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13289           // If both constants have multiple uses, then we won't need to do an
13290           // extra load, they are likely around in registers for other users.
13291           (TV->hasOneUse() || FV->hasOneUse())) {
13292         Constant *Elts[] = {
13293           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13294           const_cast<ConstantFP*>(TV->getConstantFPValue())
13295         };
13296         Type *FPTy = Elts[0]->getType();
13297         const DataLayout &TD = *TLI.getDataLayout();
13298
13299         // Create a ConstantArray of the two constants.
13300         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13301         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13302                                             TD.getPrefTypeAlignment(FPTy));
13303         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13304
13305         // Get the offsets to the 0 and 1 element of the array so that we can
13306         // select between them.
13307         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13308         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13309         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13310
13311         SDValue Cond = DAG.getSetCC(DL,
13312                                     getSetCCResultType(N0.getValueType()),
13313                                     N0, N1, CC);
13314         AddToWorklist(Cond.getNode());
13315         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13316                                           Cond, One, Zero);
13317         AddToWorklist(CstOffset.getNode());
13318         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13319                             CstOffset);
13320         AddToWorklist(CPIdx.getNode());
13321         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13322                            MachinePointerInfo::getConstantPool(), false,
13323                            false, false, Alignment);
13324       }
13325     }
13326
13327   // Check to see if we can perform the "gzip trick", transforming
13328   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13329   if (isNullConstant(N3) && CC == ISD::SETLT &&
13330       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13331        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13332     EVT XType = N0.getValueType();
13333     EVT AType = N2.getValueType();
13334     if (XType.bitsGE(AType)) {
13335       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13336       // single-bit constant.
13337       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13338         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13339         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13340         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13341                                        getShiftAmountTy(N0.getValueType()));
13342         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13343                                     XType, N0, ShCt);
13344         AddToWorklist(Shift.getNode());
13345
13346         if (XType.bitsGT(AType)) {
13347           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13348           AddToWorklist(Shift.getNode());
13349         }
13350
13351         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13352       }
13353
13354       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13355                                   XType, N0,
13356                                   DAG.getConstant(XType.getSizeInBits() - 1,
13357                                                   SDLoc(N0),
13358                                          getShiftAmountTy(N0.getValueType())));
13359       AddToWorklist(Shift.getNode());
13360
13361       if (XType.bitsGT(AType)) {
13362         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13363         AddToWorklist(Shift.getNode());
13364       }
13365
13366       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13367     }
13368   }
13369
13370   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13371   // where y is has a single bit set.
13372   // A plaintext description would be, we can turn the SELECT_CC into an AND
13373   // when the condition can be materialized as an all-ones register.  Any
13374   // single bit-test can be materialized as an all-ones register with
13375   // shift-left and shift-right-arith.
13376   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13377       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13378     SDValue AndLHS = N0->getOperand(0);
13379     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13380     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13381       // Shift the tested bit over the sign bit.
13382       APInt AndMask = ConstAndRHS->getAPIntValue();
13383       SDValue ShlAmt =
13384         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13385                         getShiftAmountTy(AndLHS.getValueType()));
13386       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13387
13388       // Now arithmetic right shift it all the way over, so the result is either
13389       // all-ones, or zero.
13390       SDValue ShrAmt =
13391         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13392                         getShiftAmountTy(Shl.getValueType()));
13393       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13394
13395       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13396     }
13397   }
13398
13399   // fold select C, 16, 0 -> shl C, 4
13400   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13401       TLI.getBooleanContents(N0.getValueType()) ==
13402           TargetLowering::ZeroOrOneBooleanContent) {
13403
13404     // If the caller doesn't want us to simplify this into a zext of a compare,
13405     // don't do it.
13406     if (NotExtCompare && N2C->isOne())
13407       return SDValue();
13408
13409     // Get a SetCC of the condition
13410     // NOTE: Don't create a SETCC if it's not legal on this target.
13411     if (!LegalOperations ||
13412         TLI.isOperationLegal(ISD::SETCC,
13413           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13414       SDValue Temp, SCC;
13415       // cast from setcc result type to select result type
13416       if (LegalTypes) {
13417         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13418                             N0, N1, CC);
13419         if (N2.getValueType().bitsLT(SCC.getValueType()))
13420           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13421                                         N2.getValueType());
13422         else
13423           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13424                              N2.getValueType(), SCC);
13425       } else {
13426         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13427         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13428                            N2.getValueType(), SCC);
13429       }
13430
13431       AddToWorklist(SCC.getNode());
13432       AddToWorklist(Temp.getNode());
13433
13434       if (N2C->isOne())
13435         return Temp;
13436
13437       // shl setcc result by log2 n2c
13438       return DAG.getNode(
13439           ISD::SHL, DL, N2.getValueType(), Temp,
13440           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13441                           getShiftAmountTy(Temp.getValueType())));
13442     }
13443   }
13444
13445   // Check to see if this is the equivalent of setcc
13446   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13447   // otherwise, go ahead with the folds.
13448   if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13449     EVT XType = N0.getValueType();
13450     if (!LegalOperations ||
13451         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13452       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13453       if (Res.getValueType() != VT)
13454         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13455       return Res;
13456     }
13457
13458     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13459     if (isNullConstant(N1) && CC == ISD::SETEQ &&
13460         (!LegalOperations ||
13461          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13462       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13463       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13464                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13465                                          SDLoc(Ctlz),
13466                                        getShiftAmountTy(Ctlz.getValueType())));
13467     }
13468     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13469     if (isNullConstant(N1) && CC == ISD::SETGT) {
13470       SDLoc DL(N0);
13471       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13472                                   XType, DAG.getConstant(0, DL, XType), N0);
13473       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13474       return DAG.getNode(ISD::SRL, DL, XType,
13475                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13476                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13477                                          getShiftAmountTy(XType)));
13478     }
13479     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13480     if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13481       SDLoc DL(N0);
13482       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13483                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13484                                          getShiftAmountTy(N0.getValueType())));
13485       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13486                                                                     XType));
13487     }
13488   }
13489
13490   // Check to see if this is an integer abs.
13491   // select_cc setg[te] X,  0,  X, -X ->
13492   // select_cc setgt    X, -1,  X, -X ->
13493   // select_cc setl[te] X,  0, -X,  X ->
13494   // select_cc setlt    X,  1, -X,  X ->
13495   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13496   if (N1C) {
13497     ConstantSDNode *SubC = nullptr;
13498     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13499          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13500         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13501       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13502     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13503               (N1C->isOne() && CC == ISD::SETLT)) &&
13504              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13505       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13506
13507     EVT XType = N0.getValueType();
13508     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13509       SDLoc DL(N0);
13510       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13511                                   N0,
13512                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13513                                          getShiftAmountTy(N0.getValueType())));
13514       SDValue Add = DAG.getNode(ISD::ADD, DL,
13515                                 XType, N0, Shift);
13516       AddToWorklist(Shift.getNode());
13517       AddToWorklist(Add.getNode());
13518       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13519     }
13520   }
13521
13522   return SDValue();
13523 }
13524
13525 /// This is a stub for TargetLowering::SimplifySetCC.
13526 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13527                                    SDValue N1, ISD::CondCode Cond,
13528                                    SDLoc DL, bool foldBooleans) {
13529   TargetLowering::DAGCombinerInfo
13530     DagCombineInfo(DAG, Level, false, this);
13531   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13532 }
13533
13534 /// Given an ISD::SDIV node expressing a divide by constant, return
13535 /// a DAG expression to select that will generate the same value by multiplying
13536 /// by a magic number.
13537 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13538 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13539   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13540   if (!C)
13541     return SDValue();
13542
13543   // Avoid division by zero.
13544   if (C->isNullValue())
13545     return SDValue();
13546
13547   std::vector<SDNode*> Built;
13548   SDValue S =
13549       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13550
13551   for (SDNode *N : Built)
13552     AddToWorklist(N);
13553   return S;
13554 }
13555
13556 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13557 /// DAG expression that will generate the same value by right shifting.
13558 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13559   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13560   if (!C)
13561     return SDValue();
13562
13563   // Avoid division by zero.
13564   if (C->isNullValue())
13565     return SDValue();
13566
13567   std::vector<SDNode *> Built;
13568   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13569
13570   for (SDNode *N : Built)
13571     AddToWorklist(N);
13572   return S;
13573 }
13574
13575 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13576 /// expression that will generate the same value by multiplying by a magic
13577 /// number.
13578 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13579 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13580   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13581   if (!C)
13582     return SDValue();
13583
13584   // Avoid division by zero.
13585   if (C->isNullValue())
13586     return SDValue();
13587
13588   std::vector<SDNode*> Built;
13589   SDValue S =
13590       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13591
13592   for (SDNode *N : Built)
13593     AddToWorklist(N);
13594   return S;
13595 }
13596
13597 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13598   if (Level >= AfterLegalizeDAG)
13599     return SDValue();
13600
13601   // Expose the DAG combiner to the target combiner implementations.
13602   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13603
13604   unsigned Iterations = 0;
13605   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13606     if (Iterations) {
13607       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13608       // For the reciprocal, we need to find the zero of the function:
13609       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13610       //     =>
13611       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13612       //     does not require additional intermediate precision]
13613       EVT VT = Op.getValueType();
13614       SDLoc DL(Op);
13615       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13616
13617       AddToWorklist(Est.getNode());
13618
13619       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13620       for (unsigned i = 0; i < Iterations; ++i) {
13621         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13622         AddToWorklist(NewEst.getNode());
13623
13624         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13625         AddToWorklist(NewEst.getNode());
13626
13627         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13628         AddToWorklist(NewEst.getNode());
13629
13630         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13631         AddToWorklist(Est.getNode());
13632       }
13633     }
13634     return Est;
13635   }
13636
13637   return SDValue();
13638 }
13639
13640 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13641 /// For the reciprocal sqrt, we need to find the zero of the function:
13642 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13643 ///     =>
13644 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13645 /// As a result, we precompute A/2 prior to the iteration loop.
13646 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13647                                           unsigned Iterations) {
13648   EVT VT = Arg.getValueType();
13649   SDLoc DL(Arg);
13650   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13651
13652   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13653   // this entire sequence requires only one FP constant.
13654   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13655   AddToWorklist(HalfArg.getNode());
13656
13657   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13658   AddToWorklist(HalfArg.getNode());
13659
13660   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13661   for (unsigned i = 0; i < Iterations; ++i) {
13662     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13663     AddToWorklist(NewEst.getNode());
13664
13665     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13666     AddToWorklist(NewEst.getNode());
13667
13668     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13669     AddToWorklist(NewEst.getNode());
13670
13671     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13672     AddToWorklist(Est.getNode());
13673   }
13674   return Est;
13675 }
13676
13677 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13678 /// For the reciprocal sqrt, we need to find the zero of the function:
13679 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13680 ///     =>
13681 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13682 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13683                                           unsigned Iterations) {
13684   EVT VT = Arg.getValueType();
13685   SDLoc DL(Arg);
13686   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13687   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13688
13689   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13690   for (unsigned i = 0; i < Iterations; ++i) {
13691     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13692     AddToWorklist(HalfEst.getNode());
13693
13694     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13695     AddToWorklist(Est.getNode());
13696
13697     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13698     AddToWorklist(Est.getNode());
13699
13700     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13701     AddToWorklist(Est.getNode());
13702
13703     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13704     AddToWorklist(Est.getNode());
13705   }
13706   return Est;
13707 }
13708
13709 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13710   if (Level >= AfterLegalizeDAG)
13711     return SDValue();
13712
13713   // Expose the DAG combiner to the target combiner implementations.
13714   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13715   unsigned Iterations = 0;
13716   bool UseOneConstNR = false;
13717   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13718     AddToWorklist(Est.getNode());
13719     if (Iterations) {
13720       Est = UseOneConstNR ?
13721         BuildRsqrtNROneConst(Op, Est, Iterations) :
13722         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13723     }
13724     return Est;
13725   }
13726
13727   return SDValue();
13728 }
13729
13730 /// Return true if base is a frame index, which is known not to alias with
13731 /// anything but itself.  Provides base object and offset as results.
13732 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13733                            const GlobalValue *&GV, const void *&CV) {
13734   // Assume it is a primitive operation.
13735   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13736
13737   // If it's an adding a simple constant then integrate the offset.
13738   if (Base.getOpcode() == ISD::ADD) {
13739     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13740       Base = Base.getOperand(0);
13741       Offset += C->getZExtValue();
13742     }
13743   }
13744
13745   // Return the underlying GlobalValue, and update the Offset.  Return false
13746   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13747   // by multiple nodes with different offsets.
13748   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13749     GV = G->getGlobal();
13750     Offset += G->getOffset();
13751     return false;
13752   }
13753
13754   // Return the underlying Constant value, and update the Offset.  Return false
13755   // for ConstantSDNodes since the same constant pool entry may be represented
13756   // by multiple nodes with different offsets.
13757   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13758     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13759                                          : (const void *)C->getConstVal();
13760     Offset += C->getOffset();
13761     return false;
13762   }
13763   // If it's any of the following then it can't alias with anything but itself.
13764   return isa<FrameIndexSDNode>(Base);
13765 }
13766
13767 /// Return true if there is any possibility that the two addresses overlap.
13768 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13769   // If they are the same then they must be aliases.
13770   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13771
13772   // If they are both volatile then they cannot be reordered.
13773   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13774
13775   // Gather base node and offset information.
13776   SDValue Base1, Base2;
13777   int64_t Offset1, Offset2;
13778   const GlobalValue *GV1, *GV2;
13779   const void *CV1, *CV2;
13780   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13781                                       Base1, Offset1, GV1, CV1);
13782   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13783                                       Base2, Offset2, GV2, CV2);
13784
13785   // If they have a same base address then check to see if they overlap.
13786   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13787     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13788              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13789
13790   // It is possible for different frame indices to alias each other, mostly
13791   // when tail call optimization reuses return address slots for arguments.
13792   // To catch this case, look up the actual index of frame indices to compute
13793   // the real alias relationship.
13794   if (isFrameIndex1 && isFrameIndex2) {
13795     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13796     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13797     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13798     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13799              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13800   }
13801
13802   // Otherwise, if we know what the bases are, and they aren't identical, then
13803   // we know they cannot alias.
13804   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13805     return false;
13806
13807   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13808   // compared to the size and offset of the access, we may be able to prove they
13809   // do not alias.  This check is conservative for now to catch cases created by
13810   // splitting vector types.
13811   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13812       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13813       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13814        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13815       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13816     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13817     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13818
13819     // There is no overlap between these relatively aligned accesses of similar
13820     // size, return no alias.
13821     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13822         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13823       return false;
13824   }
13825
13826   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13827                    ? CombinerGlobalAA
13828                    : DAG.getSubtarget().useAA();
13829 #ifndef NDEBUG
13830   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13831       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13832     UseAA = false;
13833 #endif
13834   if (UseAA &&
13835       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13836     // Use alias analysis information.
13837     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13838                                  Op1->getSrcValueOffset());
13839     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13840         Op0->getSrcValueOffset() - MinOffset;
13841     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13842         Op1->getSrcValueOffset() - MinOffset;
13843     AliasAnalysis::AliasResult AAResult =
13844         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13845                                          Overlap1,
13846                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13847                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13848                                          Overlap2,
13849                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13850     if (AAResult == AliasAnalysis::NoAlias)
13851       return false;
13852   }
13853
13854   // Otherwise we have to assume they alias.
13855   return true;
13856 }
13857
13858 /// Walk up chain skipping non-aliasing memory nodes,
13859 /// looking for aliasing nodes and adding them to the Aliases vector.
13860 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13861                                    SmallVectorImpl<SDValue> &Aliases) {
13862   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13863   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13864
13865   // Get alias information for node.
13866   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13867
13868   // Starting off.
13869   Chains.push_back(OriginalChain);
13870   unsigned Depth = 0;
13871
13872   // Look at each chain and determine if it is an alias.  If so, add it to the
13873   // aliases list.  If not, then continue up the chain looking for the next
13874   // candidate.
13875   while (!Chains.empty()) {
13876     SDValue Chain = Chains.back();
13877     Chains.pop_back();
13878
13879     // For TokenFactor nodes, look at each operand and only continue up the
13880     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13881     // find more and revert to original chain since the xform is unlikely to be
13882     // profitable.
13883     //
13884     // FIXME: The depth check could be made to return the last non-aliasing
13885     // chain we found before we hit a tokenfactor rather than the original
13886     // chain.
13887     if (Depth > 6 || Aliases.size() == 2) {
13888       Aliases.clear();
13889       Aliases.push_back(OriginalChain);
13890       return;
13891     }
13892
13893     // Don't bother if we've been before.
13894     if (!Visited.insert(Chain.getNode()).second)
13895       continue;
13896
13897     switch (Chain.getOpcode()) {
13898     case ISD::EntryToken:
13899       // Entry token is ideal chain operand, but handled in FindBetterChain.
13900       break;
13901
13902     case ISD::LOAD:
13903     case ISD::STORE: {
13904       // Get alias information for Chain.
13905       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13906           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13907
13908       // If chain is alias then stop here.
13909       if (!(IsLoad && IsOpLoad) &&
13910           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13911         Aliases.push_back(Chain);
13912       } else {
13913         // Look further up the chain.
13914         Chains.push_back(Chain.getOperand(0));
13915         ++Depth;
13916       }
13917       break;
13918     }
13919
13920     case ISD::TokenFactor:
13921       // We have to check each of the operands of the token factor for "small"
13922       // token factors, so we queue them up.  Adding the operands to the queue
13923       // (stack) in reverse order maintains the original order and increases the
13924       // likelihood that getNode will find a matching token factor (CSE.)
13925       if (Chain.getNumOperands() > 16) {
13926         Aliases.push_back(Chain);
13927         break;
13928       }
13929       for (unsigned n = Chain.getNumOperands(); n;)
13930         Chains.push_back(Chain.getOperand(--n));
13931       ++Depth;
13932       break;
13933
13934     default:
13935       // For all other instructions we will just have to take what we can get.
13936       Aliases.push_back(Chain);
13937       break;
13938     }
13939   }
13940
13941   // We need to be careful here to also search for aliases through the
13942   // value operand of a store, etc. Consider the following situation:
13943   //   Token1 = ...
13944   //   L1 = load Token1, %52
13945   //   S1 = store Token1, L1, %51
13946   //   L2 = load Token1, %52+8
13947   //   S2 = store Token1, L2, %51+8
13948   //   Token2 = Token(S1, S2)
13949   //   L3 = load Token2, %53
13950   //   S3 = store Token2, L3, %52
13951   //   L4 = load Token2, %53+8
13952   //   S4 = store Token2, L4, %52+8
13953   // If we search for aliases of S3 (which loads address %52), and we look
13954   // only through the chain, then we'll miss the trivial dependence on L1
13955   // (which also loads from %52). We then might change all loads and
13956   // stores to use Token1 as their chain operand, which could result in
13957   // copying %53 into %52 before copying %52 into %51 (which should
13958   // happen first).
13959   //
13960   // The problem is, however, that searching for such data dependencies
13961   // can become expensive, and the cost is not directly related to the
13962   // chain depth. Instead, we'll rule out such configurations here by
13963   // insisting that we've visited all chain users (except for users
13964   // of the original chain, which is not necessary). When doing this,
13965   // we need to look through nodes we don't care about (otherwise, things
13966   // like register copies will interfere with trivial cases).
13967
13968   SmallVector<const SDNode *, 16> Worklist;
13969   for (const SDNode *N : Visited)
13970     if (N != OriginalChain.getNode())
13971       Worklist.push_back(N);
13972
13973   while (!Worklist.empty()) {
13974     const SDNode *M = Worklist.pop_back_val();
13975
13976     // We have already visited M, and want to make sure we've visited any uses
13977     // of M that we care about. For uses that we've not visisted, and don't
13978     // care about, queue them to the worklist.
13979
13980     for (SDNode::use_iterator UI = M->use_begin(),
13981          UIE = M->use_end(); UI != UIE; ++UI)
13982       if (UI.getUse().getValueType() == MVT::Other &&
13983           Visited.insert(*UI).second) {
13984         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13985           // We've not visited this use, and we care about it (it could have an
13986           // ordering dependency with the original node).
13987           Aliases.clear();
13988           Aliases.push_back(OriginalChain);
13989           return;
13990         }
13991
13992         // We've not visited this use, but we don't care about it. Mark it as
13993         // visited and enqueue it to the worklist.
13994         Worklist.push_back(*UI);
13995       }
13996   }
13997 }
13998
13999 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14000 /// (aliasing node.)
14001 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14002   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14003
14004   // Accumulate all the aliases to this node.
14005   GatherAllAliases(N, OldChain, Aliases);
14006
14007   // If no operands then chain to entry token.
14008   if (Aliases.size() == 0)
14009     return DAG.getEntryNode();
14010
14011   // If a single operand then chain to it.  We don't need to revisit it.
14012   if (Aliases.size() == 1)
14013     return Aliases[0];
14014
14015   // Construct a custom tailored token factor.
14016   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14017 }
14018
14019 /// This is the entry point for the file.
14020 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14021                            CodeGenOpt::Level OptLevel) {
14022   /// This is the main entry point to this class.
14023   DAGCombiner(*this, AA, OptLevel).Run(Level);
14024 }